diff --git "a/681.jsonl" "b/681.jsonl"
new file mode 100644--- /dev/null
+++ "b/681.jsonl"
@@ -0,0 +1,678 @@
+{"seq_id":"149886295","text":"\"\"\"empty message\n\nRevision ID: 4e6f542c9d30\nRevises: 566923beeedb\nCreate Date: 2015-03-17 11:57:22.460102\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '4e6f542c9d30'\ndown_revision = '566923beeedb'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('whatsup', sa.Column('pub_date', sa.DateTime(), nullable=True))\n op.add_column('whatsup_comments', sa.Column('pub_date', sa.DateTime(), nullable=True))\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('whatsup_comments', 'pub_date')\n op.drop_column('whatsup', 'pub_date')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/4e6f542c9d30_.py","file_name":"4e6f542c9d30_.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"232099283","text":"from time import sleep\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom django.utils import timezone\n\nfrom rango.models import Category, Page\n\n\nclass CategoryMethodTests(TestCase):\n def test_ensure_views_are_positive(self):\n\n \"\"\"\n ensure_views_are_positive should results True for categories where views are zero or positive\n \"\"\"\n cat = Category(name='test', views = -1, likes=0)\n cat.save()\n self.assertEqual((cat.views >= 0), True)\n\n def test_slug_line_creation(self):\n \"\"\"\n slug_line_creation checks to make sure that when we add a category an appropriate slug line is created\n i.e. \"Random Category String\" -> \"random-category-string\"\n \"\"\"\n\n cat = Category(name = 'Random Category String')\n cat.save()\n self.assertEqual(cat.slug, 'random-category-string')\n\nclass IndexViewTests(TestCase):\n def test_index_view_with_no_categories(self):\n \"\"\"\n If no questions exist, an appropriate message should be displayed.\n \"\"\"\n response = self.client.get(reverse('index'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"There are no categories present.\")\n self.assertQuerysetEqual(response.context['categories'], [])\n\n def test_index_view_with_categories(self):\n \"\"\"\n If no questions exist, an appropriate message should be displayed.\n \"\"\"\n add_cat('test',1,1)\n add_cat('temp',1,1)\n add_cat('tmp',1,1)\n add_cat('tmp test temp',1,1)\n\n response = self.client.get(reverse('index'))\n self.assertEqual(response.status_code, 200)\n self.assertContains(response, \"tmp test temp\")\n\n num_cats = len(response.context['categories'])\n self.assertEqual(num_cats, 4)\n\n def test_to_ensure_if_last_visit_and_first_visit_are_not_future(self):\n cat = add_cat('test',1,1)\n page = Page(title='Google.com', category = cat)\n page.save()\n self.assertEqual((page.first_visit > timezone.now()), False)\n sleep(5)\n page.save()\n self.assertEqual((page.last_visit > timezone.now()), False)\n\n def test_to_insure_if_last_visit_and_first_visit_are_equals_or_in_right_order(self):\n cat = add_cat('test',1,1)\n page = Page(title='Google.com', category = cat)\n page.save()\n #self.assertEqual(page.last_visit == page.first_visit or page.last_visit > page.first_visit, True)\n self.assertEqual(page.last_visit == page.first_visit, True)\n\n sleep(5)\n page.save()\n self.assertEqual(page.last_visit > page.first_visit, True)\n\n\n\"\"\"\n def test_index_view_to_ensure_if_first_visit_is_valid(self):\n cat = add_cat('test',1,1)\n page = add_page(cat, 'Google.com', 'http://www.google.com')\n self.assertEqual((page.first_visit > timezone.now()), False)\n\"\"\"\n\n\ndef add_cat(name, views, likes):\n c = Category.objects.get_or_create(name=name)[0]\n c.views = views\n c.likes = likes\n c.save()\n #print \"Category id: \"+str(c.id)\n return c\n\ndef add_page(category, title, url):\n p = Page.objects.create()\n Page.objects.get_or_create(title=title)[0]\n p.category = category\n p.url = url\n p.save()\n return p\n","sub_path":"rango/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"450588221","text":"from aiogram.types import Message\nfrom aiogram.types import CallbackQuery\nfrom aiogram.dispatcher.dispatcher import FSMContext\n\nfrom re import match as re_match\n\nfrom keyboards.inline.cancel import calcel_button\nfrom states.fio_state import AuthState\n\nfrom decorators import auth\nfrom loader import dp, sql\n\n\n@dp.message_handler(commands='set_profile', state=None)\n@auth\nasync def set_profile_info(message: Message):\n await AuthState.fio_check.set()\n await message.answer('Введите ваши фамилию имя и отчетсво.\\nВ одну строку, через пробел.', reply_markup=calcel_button)\n\n\n@dp.message_handler(content_types='text', state=AuthState.fio_check)\nasync def set_fio(message: Message, state: FSMContext):\n user_data = message.text.strip().lower()\n user_id = message.chat.id\n\n if user_data and re_match(r'^[А-Яа-я]{2,20} [А-Яа-я]{2,20} [А-Яа-я]{2,20}$', user_data):\n result = sql.update_user_fio(user_id, user_data.title())\n if result:\n await message.answer('Данные успешно обновлены')\n await state.update_data(set_fio_check=1)\n await state.finish()\n\n else:\n keyboard = calcel_button\n await message.answer('Ошибка. Некорректные данные. Попробуйте ввести заново.', reply_markup=keyboard)\n\n\n@dp.callback_query_handler(text='cancel')\nasync def send_cancel(call: CallbackQuery):\n await call.message.edit_reply_markup(reply_markup=None)\n await call.answer('Отменено.\\nНо зачем это делать сейчас?')\n\n\n@dp.callback_query_handler(text='cancel', state=AuthState.fio_check)\nasync def send_cancel(call: CallbackQuery, state: FSMContext):\n await call.message.edit_reply_markup(reply_markup=None)\n\n await state.finish()\n await call.answer('Отменено')","sub_path":"handlers/users/set_profile.py","file_name":"set_profile.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"386804762","text":"\"\"\"\nHelper functions to achieve certain EC2 related tasks faster.\nFunctions return ec2.Instance instances (Errrrh!) instead of boto3 iterators.\n\nlist of tasks:\n1. get instances of a given module & version;\n2. get instances that match certain filters;\n\nAuthor: lihaomin@tp-link.com.cn\nCopyright: whatever fucks.\n\"\"\"\nimport re\n\nfrom .tags import get_resource_name\n\n\ndef version_cmp(ver1, ver2):\n \"\"\"Compare version numbers.\"\"\"\n arr_ver1 = ver1.split('.')\n arr_ver2 = ver2.split('.')\n len1 = len(arr_ver1)\n len2 = len(arr_ver2)\n # number of comparisons to make:\n cmp_count = min(len1, len2)\n i = 0\n # compare each segment:\n while i < cmp_count:\n try:\n m = int(arr_ver1[i])\n except:\n raise Exception(\n \"Cannot parse segment as integer: %s.\"%(arr_ver1[i])\n )\n try:\n n = int(arr_ver2[i])\n except:\n raise Exception(\n \"Cannot parse segment as integer: %s.\"%(arr_ver2[i])\n )\n if m < n:\n return -1\n if m > n:\n return 1\n i += 1\n # if segments are the same, the longer one wins:\n if len1 < len2:\n return -1\n if len1 > len2:\n return 1\n # otherwise return equal:\n return 0\n\n\ndef name_cmp(x, y):\n \"\"\"Compare instance names.\n \n For modules with +10 instances, string length needs to be considered, \n otherwise 'xxx-9' will be greater than 'xxx-10'.\"\"\"\n len_x = len(x)\n len_y = len(y)\n if len_x < len_y:\n return -1\n if len_x > len_y:\n return 1\n if x < y:\n return -1\n if x > y:\n return 1\n return 0\n\n\ndef to_name_dict(instances):\n \"\"\"Convert instances to a dictionary with their names as keys.\"\"\"\n ret = {}\n for instance in instances:\n name = get_resource_name(instance)\n if name is None:\n raise Exception(\"Instance %s has no 'Name' tag.\"%(instance.id,))\n else:\n ret.update({name: instance})\n return ret\n\n\ndef get_instance_names(instances):\n \"\"\"Return a sorted list of instance names.\"\"\"\n names = [get_resource_name(instance) for instance in instances]\n names.sort(cmp=name_cmp)\n return names\n\n\ndef get_instances_by_filters(ec2res, filters):\n \"\"\"Get instances by simple dict filters.\"\"\"\n boto3filters = []\n for filter_name in filters:\n if type(filters[filter_name]) in (str, int, float, unicode):\n filter_values = [filters[filter_name],]\n else:\n filter_values = filters[filter_name]\n boto3filters.append({\n 'Name': filter_name,\n 'Values': filter_values\n })\n return ec2res.instances.filter(Filters=boto3filters)\n\n\ndef get_module_instances(ec2res, module, version):\n \"\"\"Get instances with names contain '*---*'\"\"\"\n filters = {\n 'tag:Name': \"*-%s-%s-*\"%(module, version),\n 'instance-state-name': ['running', 'stopped', 'pending', 'stopping', 'shutting-down']\n }\n instances = []\n for instance in get_instances_by_filters(ec2res, filters):\n instances.append(instance)\n try:\n instances.sort(cmp=name_cmp, key=lambda x: get_resource_name(x))\n except Exception as ex:\n raise ex\n return instances\n\n\ndef get_instance_module_version(instance):\n # env module version region az number\n p = \"([adeprtuv]+)-([a-zA-Z0-9_]+)-([\\d\\._a-zA-Z]+)-([a-zA-Z\\d]+)-([\\da-zA-Z])-(\\d+)\"\n name = get_resource_name(instance)\n if name is not None:\n m = re.match(p, name)\n if m is not None:\n module = m.groups()[1]\n version = m.groups()[2]\n return (module, version)\n else:\n raise Exception(\"Invalid instance name: %s\"%(name,))\n else:\n raise Exception(\"Instance name tag not found: %s\"%(str(instance.tags,)))\n","sub_path":"PrdDeployer/boto3helper/ec2.py","file_name":"ec2.py","file_ext":"py","file_size_in_byte":3906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"558449169","text":"import os\nimport sys\nimport zipfile\n\nimport pandas as pd\nfrom text_analytic_tools.common.gensim_utility import CompressedFileReader\n\nroot_folder = os.path.join(os.getcwd().split('welfare_state_analytics')[0], 'welfare_state_analytics')\n\nsys.path = list(set(sys.path + [root_folder]))\n\n\ndef load_index(filename):\n \"\"\"Loads document index as a Pandas dataframe.\n The CSV file is a merge of all datasets CSV files downloaded from RÖD using merge_prot_csv.sh\n The CSV file has meen manually cleaned: \\\"\\\"\\\" => \\\"\\\" and invalid char exists in file (done manually)\n\n Parameters\n ----------\n filename : str\n Name of (cleaned) output from merge_prot_csv.sh\n\n Returns\n -------\n DataFrame\n Document index\n \"\"\"\n meta_columns = [\n \"hangar_id\",\n \"dok_id\",\n \"rm\",\n \"beteckning\",\n \"doktyp\",\n \"typ\",\n \"subtyp\",\n \"tempbeteckning\",\n \"organ\",\n \"mottagare\",\n \"nummer\",\n \"datum\",\n \"systemdatum\",\n \"titel\",\n \"subtitel\",\n \"status\",\n \"relaterat_id\",\n ]\n #\n df = pd.read_csv(filename, header=None, sep=',', quotechar='\"')\n df.columns = meta_columns\n df = df.set_index('dok_id')\n # Update faulty value: G209106\t1978/79\t106\tprot\tprot\tprot\t\t\t\t===>107<===\n # df.set_value('G209106', 'nummer', 106)\n return df\n\n\ndef rename_text_corpus_files(document_index, source_filename, target_filename):\n \"\"\"Renames text files downloaded from RÖD in accordance to names of documents downloaded from KB-LABB.\n The files is renamed to \"prot_YYYYyy_nn.txt\" e.g. \"prot_198990__142.txt\"\n\n Parameters\n ----------\n document_index : DataFrame\n Document index\n source_filename : str\n Source corpus filename\n target_filename : str\n Taret corpus filename\n \"\"\"\n\n def get_rm_tag(rm):\n \"\"\"Returns 'riksmötet' as YYYYyy if rm is yyyy/yyyy else rm\"\"\"\n rm_parts = rm.split(\"/\")\n if len(rm_parts) == 1:\n return rm\n return rm_parts[0] + rm_parts[1][-2:]\n\n reader = CompressedFileReader(source_filename)\n\n with zipfile.ZipFile(target_filename, \"w\") as of:\n for document_name, content in reader:\n doc_id = document_name.split(\".\")[0]\n meta = document_index.loc[doc_id.upper()].to_dict()\n target_name = f'prot_{get_rm_tag(meta[\"rm\"])}__{meta[\"beteckning\"]}.txt'\n of.writestr(target_name, content, zipfile.ZIP_DEFLATED)\n\n print(\"Done!\")\n\n\nif __name__ == \"__main__\":\n\n data_folder = os.path.join(root_folder, 'data/riksdagens_protokoll')\n source_corpus_filename = os.path.join(data_folder, 'prot-1971-2021.text.zip')\n target_corpus_filename = os.path.join(data_folder, 'prot-1971-2021.corpus.txt.zip')\n index_filename = os.path.join(data_folder, 'prot-1971-2021.csv')\n excel_index_filename = os.path.join(data_folder, 'prot-1971-2021.index.xlsx')\n\n document_index = load_index(index_filename)\n\n document_index.to_excel(excel_index_filename)\n\n rename_text_corpus_files(document_index, source_corpus_filename, target_corpus_filename)\n","sub_path":"scripts/riksdagens_protokoll/step.1-compile_corpus/riksdagens_open_data/vault/rename-text-files.py","file_name":"rename-text-files.py","file_ext":"py","file_size_in_byte":3140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"177089967","text":"\"\"\"\nDefinition of ListNode\nclass ListNode(object):\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param head: The head of linked list.\n @return: nothing\n \"\"\"\n\n def reorderList(self, head):\n # write your code here\n if not head or not head.next: return\n\n # find mid\n p1 = p2 = head\n while p2.next and p2.next.next:\n p1 = p1.next\n p2 = p2.next.next\n\n # reverse the half after mid\n pre_mid, pre_cur = p1, p1.next\n while pre_cur.next:\n cur = pre_cur.next\n pre_cur.next = cur.next\n cur.next = pre_mid.next\n pre_mid.next = cur\n\n # reorder\n p1, p2 = head, pre_mid.next\n while p1 != pre_mid:\n pre_mid.next = p2.next\n p2.next = p1.next\n p1.next = p2\n p1 = p2.next\n p2 = pre_mid.next\n\n return\n","sub_path":"lintcode/99-reorder-list.py","file_name":"99-reorder-list.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"441147144","text":"from FormigasSolucao import *\n#from past.builtins import xrange #external library\n\ndef CaminhoJulgamento(formigacaminho, pecas):\n ataques = CalculaCustoCaminho(formigacaminho)\n if ataques > pecas:\n return 0\n return 1\n\n\nclass FormigasFeromonio:\n\n def __init__(self, n, evaporacao):\n self.P = evaporacao/100\n self.dimensao = n\n self.Matriz = []\n for i in range(n):\n # Original era 1\n self.Matriz.append([(1000, [])] * n) # Tupla\n\n def __atualizacao__(self, formigueiro):\n self.__evaporacao__()\n self.__deposito__(formigueiro)\n\n def __evaporacao__(self):\n # vetor = list(map(lambda x: x.decisao(feromonio), formigueiro.formigueiro))\n # Experimentar dois maps aninhados\n # Experimentar substituir a matriz pelo retorno do map\n # map(lambda x: (round(i * (1 - self.P), 5) for i in x), self.Matriz) # Test\n map(lambda linha: ( map(lambda tupla: round(tupla[0] * (1 - self.P), 5), linha)), self.Matriz )\n #print(self.Matriz)\n '''for i in self.Matriz:\n i = [round(x * (1 - self.P), 5) for x in i]'''\n\n '''def __evaporacao__(self):\n for i in range(self.dimensao):\n for j in range(self.dimensao):\n self.Matriz[i][j] *= (1 - self.P)'''\n\n def __deposito__(self, formigueiro):\n for i in range(formigueiro.k): # número de formigas\n for j in range(self.dimensao): # n\n # adição\n # para cada coluna, captura a linha armazenada no caminho da formiga para adicionar o feromônio padrão\n # o Lk poderia ser uma heurística de peças se atacando em vez da dimensão\n try:\n # Custo mais fiel\n\n alpha = Porcentagem(self.Matriz[formigueiro.formigueiro[i].caminho[j]][j][1]) # Bom\n betha = 1 - alpha # Ruim\n\n self.Matriz[formigueiro.formigueiro[i].caminho[j]][j][0] += \\\n (formigueiro.formigueiro[i].Q**alpha / CalculaCustoCaminho(formigueiro.formigueiro[i])**betha)\n # Custo mais rápido\n '''self.Matriz[ formigueiro.formigueiro[i].caminho[j] ][j] +=\\\n (formigueiro.formigueiro[i].Q/self.dimensao)'''\n\n except:\n print(\"Uma solução em potencial foi encontrada\\n\")\n FormigasSolucao(formigueiro.formigueiro[i].caminho)\n\n def __CaminhoHistorico__(self, formigacaminho, pecas):\n julgo = CaminhoJulgamento(formigacaminho, pecas)\n for linha in formigacaminho.caminho:\n self.Matriz[linha][formigacaminho.caminho.index(linha)][1].append(julgo)\n","sub_path":"NRainhas_FormigueiroFinal/FormigasFeromonio.py","file_name":"FormigasFeromonio.py","file_ext":"py","file_size_in_byte":2756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"260620828","text":"numbers = {'01': 'первое',\n'02': 'второе',\n'03': 'третье',\n'04': 'четвертое',\n'05': 'пятое',\n'06': 'шестое',\n'07': 'седьмое',\n'08': 'восьмое',\n'09': 'девятое',\n'10': 'десятое',\n'11': 'одиннадцатое',\n'12': 'двенадцатое',\n'13': 'тринадцатое',\n'14': 'четырнадцатое',\n'15': 'пятнадцатое',\n'16': 'шестнадцатое',\n'17': 'семнадцатое',\n'18': 'восемнадцатое',\n'19': 'девятнадцатое',\n'20': 'двадцатое',\n'21': 'двадцать первое',\n'22': 'двадцать второе',\n'23': 'двадцать третье',\n'24': 'двадцать четвертое',\n'25': 'двадцать пятое',\n'26': 'двадцать шестое',\n'27': 'двадцать седьмое',\n'28': 'двадцать восьмое',\n'29': 'двадцать девятое',\n'30': 'тридцатое',\n'31': 'тридцать первое'}\n\n\ndef number_to_word(x):\n if x in numbers.keys():\n return numbers[str(x)]\n return False\n\n\n\n","sub_path":"numbers.py","file_name":"numbers.py","file_ext":"py","file_size_in_byte":1107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"24127794","text":"# https://www.hackerrank.com/challenges/taum-and-bday/problem\n\nfor t in range(int(input())):\n\tb,w=input().split()\n\tbc,wc,z=input().split()\n\tbc,wc,z=int(bc),int(wc),int(z)\n\tr=0\n\tif abs(bc-wc)>z:\n\t\tif bc 1:\n\t\t\tdel images[type]\n\t\t\tsession['images_to_edit'] = images\n\n\t\t\treturn redirect(url_for('admin.edit_product_image'))\n\t\t\n\t\telse: \n\t\t\treturn redirect(url_for('main.index'))\n\t\n\t\t\n\treturn render_template('admin/edit_product_image.html', image=image, form=form, type=type, dimension=dimension)\n\t\t\n","sub_path":"app/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"219956533","text":"import aiohttp\nimport asyncio\nimport collections\nimport enum\nimport itertools\nimport logging\nimport pkgutil\nimport sys\nimport traceback\nfrom discord.ext import commands\nfrom . import config, actions\nfrom .db import storage\nfrom .utils import fake, format\nfrom .context import HouraiContext\n\nlog = logging.getLogger(__name__)\n\n\nclass CounterKeys(enum.Enum):\n MESSAGES_RECIEVED = 0x100 # noqa: E221\n MESSAGES_DELETED = 0x101 # noqa: E221\n MESSAGES_EDITED = 0x102 # noqa: E221\n MEMBERS_JOINED = 0x200 # noqa: E221\n MEMBERS_LEFT = 0x201 # noqa: E221\n MEMBERS_BANNED = 0x202 # noqa: E221\n MEMBERS_UNBANNED = 0x203 # noqa: E221\n MEMBERS_VERIFIED = 0x204 # noqa: E221\n MEMBERS_REJECTED = 0x205 # noqa: E221\n\n def __repr__(self):\n return self.name\n\n\nclass CogLoadError(Exception):\n pass\n\n\nclass CommandInterpreter:\n\n def __init__(self, bot):\n self.bot = bot\n\n async def execute(self, ctx):\n raise NotImplementedError\n\n\nclass CommandExcecutor(CommandInterpreter):\n\n def __init__(self, interpreters):\n self.interpreters = interpreters\n\n async def execute(self, ctx):\n err = errors.CommandNotFound('Command \"{ctx.invoked_with}\" is not found')\n for interpreter in self.interpreters:\n try:\n await interpreter.execute(ctx, self)\n return\n except errors.CommandNotFound:\n pass\n except Exception as e:\n err = e\n break\n ctx.bot.dispatch('command_error', err)\n\n\nclass DefaultCommandInterpreter(CommandInterpreter):\n\n async def execute(self, ctx, executor):\n bot = ctx.bot\n if ctx.command is not None:\n bot.dispatch('command', ctx)\n if await bot.can_run(ctx, call_once=True):\n await ctx.command.invoke(ctx)\n bot.dispatch('command_completion', ctx)\n elif ctx.invoked_with:\n raise errors.CommandNotFound('Command \"{ctx.invoked_with}\" is not found')\n\n\nclass AliasInterpreter(CommandInterpreter):\n pass\n\n\n\nclass Hourai(commands.AutoShardedBot):\n\n def __init__(self, *args, **kwargs):\n self.logger = log\n try:\n self.config = kwargs['config']\n except KeyError:\n raise ValueError(\n '\"config\" must be specified when initialzing Hourai.')\n kwargs.setdefault('command_prefix', self.config.command_prefix)\n # kwargs.setdefault('help_command', HouraiHelpCommand())\n self.storage = kwargs.get('storage') or storage.Storage(self.config)\n super().__init__(*args, **kwargs)\n self.http_session = aiohttp.ClientSession(loop=self.loop)\n self.actions = actions.ActionManager(self)\n\n # Counters\n self.guild_counters = collections.defaultdict(collections.Counter)\n self.channel_counters = collections.defaultdict(collections.Counter)\n self.user_counters = collections.defaultdict(collections.Counter)\n\n def create_storage_session(self):\n return self.storage.create_session()\n\n def run(self, *args, **kwargs):\n try:\n import uvloop\n uvloop.install()\n log.info('uvloop found and installed.')\n except ImportError:\n log.warn('uvloop not found, may not be running at peak '\n 'performance.')\n super().run(*args, **kwargs)\n\n async def start(self, *args, **kwargs):\n await self.storage.init()\n await self.http_session.__aenter__()\n await super().start(*args, **kwargs)\n\n async def close(self):\n await self.http_session.__aexit__()\n await super().close()\n\n async def on_ready(self):\n log.info(f'Bot Ready: {self.user.name} ({self.user.id})')\n\n async def on_message(self, message):\n if message.author.bot:\n return\n await self.process_commands(message)\n\n async def get_prefix(self, message):\n if isinstance(message, fake.FakeMessage):\n return ''\n return await super().get_prefix(message)\n\n def get_context(self, msg, *args, **kwargs):\n if isinstance(msg, fake.FakeMessage):\n msg._state = self._connection\n return super().get_context(msg, cls=HouraiContext, **kwargs)\n\n def get_automated_context(self, **kwargs):\n \"\"\"\n Creates a fake context for automated uses. Mainly used to automatically\n run commands in response to configured triggers.\n \"\"\"\n return self.get_context(fake.FakeMessage(**kwargs))\n\n async def process_commands(self, msg):\n if msg.author.bot:\n return\n\n ctx = await self.get_context(msg)\n\n if ctx.prefix is None:\n return\n\n async with ctx:\n await self.invoke(ctx)\n log.debug(f'Command successfully executed: {msg}')\n\n def add_cog(self, cog):\n super().add_cog(cog)\n log.info(\"Cog {} loaded.\".format(cog.__class__.__name__))\n\n async def on_error(self, event, *args, **kwargs):\n error = f'Exception in event {event} (args={args}, kwargs={kwargs}):'\n self.logger.exception(error)\n _, error, _ = sys.exc_info()\n self.loop.create_task(self.send_owner_error(error))\n\n async def on_command_error(self, ctx, error):\n err_msg = None\n if isinstance(error, commands.CheckFailure):\n err_msg = str(error)\n elif isinstance(error, commands.UserInputError):\n err_msg = (str(error) + '\\n') or ''\n err_msg += f\"Try `~help {ctx.command} for a reference.\"\n elif isinstance(error, commands.CommandInvokeError):\n trace = traceback.format_exception(type(error), error,\n error.__traceback__)\n trace_str = '\\n'.join(trace)\n log.error(f'In {ctx.command.qualified_name}:\\n{trace_str}\\n')\n self.loop.create_task(self.send_owner_error(error))\n err_msg = ('An unexpected error has occured and has been reported.'\n '\\nIf this happens consistently, please consider filing'\n 'a bug:\\n')\n log.debug(error)\n if err_msg:\n await ctx.send(err_msg)\n\n async def send_owner_error(self, error):\n owner = (await self.application_info()).owner\n trace = traceback.format_exception(type(error), error,\n error.__traceback__)\n trace_str = format.multiline_code('\\n'.join(trace))\n await owner.send(trace_str)\n\n async def execute_actions(self, actions):\n tasks = (action.execute(self) for action in actions)\n await asyncio.gather(*tasks)\n\n def load_extension(self, module):\n try:\n super().load_extension(module)\n self.logger.info(f'Loaded extension: {module}')\n except Exception:\n self.logger.exception(f'Failed to load extension: {module}')\n\n def load_all_extensions(self, base_module):\n disabled_extensions = self.get_config_value('disabled_extensions',\n type=tuple, default=())\n modules = pkgutil.iter_modules(base_module.__path__,\n base_module.__name__ + '.')\n for module in modules:\n if module.name not in disabled_extensions:\n self.load_extension(module.name)\n\n def spin_wait_until_ready(self):\n while not self.is_ready():\n pass\n\n def get_all_matching_members(self, user):\n return (m for m in self.get_all_members() if m.id == user.id)\n\n def get_config_value(self, *args, **kwargs):\n return config.get_config_value(self.config, *args, **kwargs)\n\n\nclass HouraiHelpCommand(commands.DefaultHelpCommand):\n\n async def send_bot_help(self, mapping):\n ctx = self.context\n bot = ctx.bot\n\n if bot.description:\n # portion\n self.paginator.add_line(bot.description, empty=True)\n\n self.paginator.add_line('')\n self.paginator.add_line('Available modules:')\n\n no_category = '\\u200b{0.no_category}:'.format(self)\n\n def get_category(command, *, no_category=no_category):\n cog = command.cog\n return cog.qualified_name + ':' if cog is not None else no_category\n filtered = await self.filter_commands(bot.commands, sort=True,\n key=get_category)\n to_iterate = itertools.groupby(filtered, key=get_category)\n\n for category, _ in to_iterate:\n self.paginator.add_line(' ' * 3 + category)\n\n command_name = self.clean_prefix + self.invoked_with\n note = (f\"Type {command_name} module for more info on a module.\\nYou\"\n f\" can also type {command_name} category for more info on a \"\n f\"category.\")\n self.paginator.add_line()\n self.paginator.add_line(note)\n await self.send_pages()\n","sub_path":"hourai/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":9170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"241255480","text":"import numpy as np\r\nimport pandas as pd\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.datasets import load_iris\r\ncols = []\r\ndata = pd.read_csv(\"train.csv\")\r\ntime = data['date']\r\ndays = []\r\nhours = []\r\nfor each in time:\r\n date, clock = each.split()\r\n year, month, day = date.split('-')\r\n hour, minute, seconds = clock.split(':')\r\n days.append(int(day))\r\n hours.append(int(hour))\r\ndata.drop(['date'], axis=1, inplace=True)\r\ndata['hour'] = hours\r\ndata['day'] = days\r\ncolumns = data.columns\r\nstd = StandardScaler()\r\ndata = std.fit_transform(data)\r\ndata = pd.DataFrame(data, columns=columns)\r\nlabel = pd.read_csv(\"train_label.csv\")\r\nl = []\r\ndata['label'] = label['label']\r\ndata.to_csv(\"standard_train.csv\")\r\nprint(\"Finished\")\r\nprint(data.shape)\r\n","sub_path":"DataPreprocess/Standard.py","file_name":"Standard.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"334665664","text":"\n\nfrom xai.brain.wordbase.verbs._burgeon import _BURGEON\n\n#calss header\nclass _BURGEONS(_BURGEON, ):\n\tdef __init__(self,): \n\t\t_BURGEON.__init__(self)\n\t\tself.name = \"BURGEONS\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"burgeon\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_burgeons.py","file_name":"_burgeons.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"337187218","text":"def isLeap( year ):\n\tif year <= 6:\n\t\tyear += 2000\n\telse:\n\t\tyear += 1900\n\n\tif not year % 4:\n\t\tif not year % 100 and year % 400:\n\t\t\treturn False\n\t\treturn True\n\treturn False\n\n\nMONTH_DAYS = [\n\t0,\n\t31,\n\t28,\n\t31,\n\t30,\n\t31,\n\t30,\n\t31,\n\t31,\n\t30,\n\t31,\n\t30,\n\t31,\n]\n\n\n\ndef doValidate( test ):\n\tif int( test ) % 11:\n\t\treturn \"NO\"\n\n\tyear = int( test[0:2] )\n\tmonth = int( test[2:4] )\n\tday = int( test[4:6] )\n\tcc = int( test[6:] )\n\n\tif month > 12:\n\t\tmonth -= 50\n\n\tif month < 1 or month > 12:\n\t\treturn \"NO\"\n\n\tif day < 1 or day > 31:\n\t\treturn \"NO\"\n\n\tif isLeap( year ):\n\t\tif month == 2 and day <= 29:\n\t\t\treturn \"YES\"\n\n\tif day > MONTH_DAYS[month]:\n\t\treturn \"NO\"\n\n\treturn \"YES\"\n\ndef validate(test):\n\tret = []\n\tfor t in test:\n\t\tret.append( doValidate( t ) )\n\n\treturn ret\n","sub_path":"d1d2_under_80/BirthNumbersValidator/solve/python/BirthNumbersValidator.py","file_name":"BirthNumbersValidator.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"417490252","text":"import os\nimport torch\nimport configs\nfrom model import DetectAngleModel\nimport numpy as np \nfrom PIL import Image\nimport random\nfrom matplotlib import pyplot as plt\nimport time\n\n# device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n# device = 'cpu'\ndevice = 'cuda:0'\n\nif __name__ == '__main__':\n with torch.no_grad():\n model = DetectAngleModel()\n model.load_state_dict(torch.load('./pths/rotate.pth'))\n # model = model.cuda().half()\n model.to(device)\n model.eval()\n\n for mode in random.sample(('1'), 1):\n time_used = 0\n print('mode ', mode)\n if mode == '1':\n img_mode = 'one'\n elif mode == '2':\n img_mode = 'two'\n elif mode == '3':\n img_mode = 'three'\n img_label_dir = os.path.join(configs.img_rootdir, img_mode, 'Label')\n for root, dirs, files in os.walk(img_label_dir):\n i = 0\n for file in sorted(files)[:800]:\n img_name = file[0: -4]+'.jpg'\n img_dir = os.path.join(configs.img_rootdir, img_mode, 'Image', img_name)\n img = Image.open(img_dir).convert('L')\n img = img.resize((224, 224))\n #plt.imshow(img)\n #plt.show()\n img = np.array(img)\n img = img / 255.\n img = torch.from_numpy(img).float()\n # print(img.dtype)\n img = torch.unsqueeze(img, 0)\n img = torch.unsqueeze(img, 0)\n # img = img.cuda().half()\n # print(img.dtype)\n if i == 0:\n img_ = img\n else:\n img_ = torch.cat((img_, img), 0)\n i += 1\n if i % 800 == 0:\n img = img_.to(device)\n #print(img.shape)\n start_time = time.time()\n output = model(img)\n time_used += time.time()-start_time\n i = 0\n # f.write(str(output)+'\\n')\n # if output[0][0] < output[0][1]:\n # print('image_pred = 1')\n # else:\n # print('image_pred = 0')\n # f.close()\n print('time used ={}'.format(time_used))\n","sub_path":"checks_recognize_v1/img_flip/predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"302669443","text":"# from big_ol_pile_of_manim_imports import *\nfrom manimlib.imports import *\n\"\"\"Update for newer version of manim\"\"\"\n\nclass DrawAnAxis(Scene):\n CONFIG = {\"plane_kwargs\" : {\n \"x_line_frequency\" : 2,\n \"y_line_frequency\" : 3\n }\n }\n \n def construct(self):\n my_plane = NumberPlane(**self.plane_kwargs)\n my_plane.add(my_plane.get_axis_labels())\n self.add(my_plane)\n self.wait()\n\n\nclass SimpleField(Scene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED\n },\n }\n\n def construct(self):\n plane = NumberPlane(**self.plane_kwargs) #Create axes and grid\n plane.add(plane.get_axis_labels()) #add x and y label\n self.add(plane) #Place grid on screen\n \n points = [x*RIGHT+y*UP for x in np.arange(-3,4,1) for y in np.arange(-3,4,1)] #List of vectors pointing to each grid point\n\n vec_field = [] #Empty list to use in for loop\n for point in points:\n field = 0.9*LEFT + 0.5*UP #Constant field up and to right\n result = Vector(field).shift(point) #Create vector and shift it to grid point\n vec_field.append(result) #Append to list\n\n \n draw_field = VGroup(*vec_field) #Pass list of vectors to create a VGroup\n \n self.play(ShowCreation(draw_field)) #Draw VGroup on screen\n\n\nclass FieldWithAxes(Scene):\n CONFIG = {\n \"plane_kwargs\" : {\n \"color\" : RED_B\n },\n \"point_charge_loc\" : 0*RIGHT + 0*UP,\n 'x_line_frequency' : 10,\n 'y_line_frequency' : 10\n }\n \n def construct(self):\n plane = NumberPlane(**self.plane_kwargs)\n #plane.main_lines_fade(.9)\n plane.add(plane.get_axis_labels())\n self.play(ShowCreation(plane))\n\n points = [x*RIGHT+y*UP for x in np.arange(-9,9,1) for y in np.arange(-5,5,1)]\n vec_field = [self.calc_field(point) for point in points]\n \n field = VGroup(*vec_field)\n \n self.play(ShowCreation(field))\n self.wait(1)\n\n\n def calc_field(self, point):\n x = point[0]\n y = point[1]\n #field = np.array((-y,x,0))/math.sqrt(x**2+y**2) #for circular field\n field = np.array(( -2*(y%2)+1 , -2*(x%2)+1 , 0 ))/3\n return Vector(field).shift(point)\n\n\n\n\n\n\n\n","sub_path":"Projects/Vector_Fields.py","file_name":"Vector_Fields.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"38600691","text":"import stanfordnlp\nimport time\nimport re\nfrom itertools import combinations\nimport json\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\n\nanalyser = SentimentIntensityAnalyzer()\n\ndef vader_polarity(text):\n \"\"\" Transform the output to a binary 0/1 result \"\"\"\n score = analyser.polarity_scores(text)\n return 1 if score['pos'] > score['neg'] else 0\n\n## 1. 삭제해도 되는 형용사들 넣었다 뺐다 반복하면서 augmentation 할 것\n## 2. 이것도 앞뒤로 문장 붙이면서 augmentation 진행할 것\n## 3. 감성분석해서 삭제한 문장이 원래 극성을 해치지 않으면\n\n\nstart = time.time()\n\nTPE_list = []\n\nwith open(\"C:/Users/ruin/Desktop/data/json_data/TPE_Pattern/EX_neg.json\") as json_file:\n# with open(\"C:/Users/ruin/Desktop/data/json_data/TPE_Pattern/EX_pos.json\") as json_file:\n json_data = json.load(json_file)\n\n splited_sentence = json_data['splited_sentence']\n parsed_sentence = json_data['parsed_sentence']\n augmented_sentence = json_data['augmented_text']\n\n# for a in range(len(augmented_sentence)):\n# for b in range(len(augmented_sentence[a])):\n# if(str(type(augmented_sentence[a][b]))) == \"\":\n# TPE_list.append(splited_sentence[a])\n\n\n# remove_dup = list(set(map(tuple, TPE_list)))\n\n\nnlp = stanfordnlp.Pipeline(processors='tokenize,pos,depparse')\nsent_list = []\n\nfor a in range(len(splited_sentence)):\n data = splited_sentence[a]\n\n for b in range(len(data)):\n word_list = []\n\n list1 = data[:b]\n list2 = data[b+1:]\n sentence = splited_sentence[a][b]\n\n doc = nlp(sentence) ## 모든 sentence에 대해 remove 실행하면서 대상 찾음.\n\n for i, _ in enumerate(doc.sentences):\n for word in doc.sentences[i].words:\n if word.dependency_relation == 'amod':\n word_list.append(word.text)\n\n if len(word_list) > 1:\n first_sent_list = []\n # print(\"기본 문장 : \" + splited_sentence[a][b])\n print(str(a + 1) + \" 번째 리스트의 \" + str(b + 1) + \" 번째 문장\")\n # print(\"원래 문장에 대한 감���분석 결과값 : \" + str(vader_polarity(sentence)))\n\n score_original = vader_polarity(sentence) ## 원래 문장에 대한 감성분석 스코어\n\n print(word_list) ## 삭제 대상 단어 리스트\n\n for c in range(len(word_list)):\n number = list(combinations(word_list, c + 1))\n for word_tuple in range(len(number)):\n t2l = list(number[word_tuple])\n sentencewords = sentence.split()\n\n resultwords = [word for word in sentencewords if word.lower() not in t2l]\n result = ' '.join(resultwords)\n score_remove = vader_polarity(result)\n\n if(score_original == score_remove):\n result_sentence = ' '.join(list1) + \" \" + result + \" \" + ' '.join(list2)\n # print(\"해당 문장에 대해서만 감성분석 결과값 : \" + str(vader_polarity(result)))\n print(result_sentence)\n first_sent_list.append(result_sentence)\n\n # print(\"전체 세그먼트에 대한 감성분석 결과값 : \" + str(vader_polarity(result_sentence)))\n\n sent_list.append(first_sent_list)\n # print('------------------------')\n\nprint(sent_list)\n\nsent_json = {}\nsent_json['removed_sentence'] = []\nsent_json['removed_sentence'].append(sent_list)\n\nwith open(\"C:/Users/ruin/Desktop/data/json_data/removed_data/test.json\", 'w') as outfile:\n json.dump(sent_json, outfile, indent=4)\n\n\nprint(\"time :\", time.time() - start) # 현재시각 - 시작시간 = 실행 시간","sub_path":"remove/depparse_with_sentiword.py","file_name":"depparse_with_sentiword.py","file_ext":"py","file_size_in_byte":3783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"188352437","text":"#!/usr/bin/python3.6\n\nimport itertools, os, re, sys\nfrom glob import glob\nfrom typing import List\nfrom debug import dprint\n\nIN_KERNEL = os.environ.get('KAGGLE_WORKING_DIR') is not None\nMODEL_PATH = '../input/' if IN_KERNEL else '../best_models/'\n\ndef run(command: List[str]) -> None:\n res = os.system('export PYTHONPATH=${PYTHONPATH}:/kaggle/working && ' + ' '.join(command))\n if res != 0:\n sys.exit()\n\ncoeff1, coeff2, coeff3 = 1.5, 1, 1.2\nmodels = {\n '4b_se_resnext101_352x352_f0_e16_0.6050.pth': coeff1,\n '4b_se_resnext101_352x352_f1_e29_0.6079.pth': coeff1,\n '4b_se_resnext101_352x352_f2_e24_0.6022.pth': coeff1,\n '4b_se_resnext101_352x352_f3_e21_0.6047.pth': coeff1,\n '4b_se_resnext101_352x352_f4_e24_0.6050.pth': coeff1,\n '2o_se_resnext101_def_aug_f0_e30_0.5994.pth': coeff2,\n '2o_se_resnext101_def_aug_f1_e30_0.6051.pth': coeff2,\n '2o_se_resnext101_def_aug_f2_e25_0.6022.pth': coeff2,\n '2o_se_resnext101_def_aug_f3_e26_0.6032.pth': coeff2,\n '2o_se_resnext101_def_aug_f4_e21_0.6032.pth': coeff2,\n '2b_se_resnext50_f0_e14_0.5975.pth': coeff3,\n '2b_se_resnext50_f1_e19_0.6006.pth': coeff3,\n '2b_se_resnext50_f2_e20_0.5973.pth': coeff3,\n '2b_se_resnext50_f3_e21_0.5982.pth': coeff3,\n '2b_se_resnext50_f4_e21_0.5978.pth': coeff3,\n }\n\nmodel2path = {os.path.basename(path): path for path in glob(MODEL_PATH + '**/*.pth')}\nfor model in models.keys():\n assert os.path.exists(model2path[model])\n\nfor model in models.keys():\n m = re.match(r'(.*)_f(\\d)_e\\d+.*\\.pth', os.path.basename(model))\n assert m\n\n script_name = f'train_{m.group(1)}.py'\n fold = m.group(2)\n\n cmd = ['python3.6', script_name, '--predict', '--weights', model2path[model],\n '--fold', fold, '--num_tta', '1']\n print('running', cmd)\n run(cmd)\n\ncmd = ['python3.6', 'blend.py', 'submission.csv']\n\nfor model, weight in models.items():\n name = os.path.splitext(os.path.basename(model))[0]\n predict = f'pred_level1_{name}.npz'\n cmd.extend([predict, str(weight)])\n\nprint('running', cmd)\nrun(cmd)\n","sub_path":"old_models/proto__101x2_50x1_a.py","file_name":"proto__101x2_50x1_a.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"25612773","text":"''' MDPGroupClass.py: Class for an MDP group '''\n\n# Python imports.\nfrom collections import defaultdict\nimport numpy as np\n\nclass Pattern(object):\n ''' Abstract dynamics class. '''\n\n def __init__(self, agent, s_id, a_id):\n \n self.n = agent.n_s_a[s_id][a_id] # scalar\n self.n_s = self.permute(agent.n_s_a_s[s_id][a_id]) # vector\n self.r = agent.r_s_a[s_id][a_id] # scalar\n\n def permute(self, vec):\n return -np.sort(-vec)\n \n def print_pattern(self):\n print(\"total visits: \", self.n)\n print(\"dynamics:\", self.n_s / self.n)\n print(\"rewards:\",self.r / self.n)\n \n def distance(self, other):\n '''\n Compare the difference between two MDPs\n '''\n if not isinstance(other, Pattern):\n return NotImplemented\n \n# dynamic = np.hstack((self.n_s / self.n, self.r/self.n))\n# other_dynamic = np.hstack((other.n_s / other.n, other.r/other.n))\n# distance = np.linalg.norm(dynamic - other_dynamic)\n dynamic = self.n_s / self.n\n other_dynamic = other.n_s / other.n\n reward = self.r / self.n\n other_reward = other.r / other.n\n \n if len(dynamic) == len(other_dynamic):\n distance = np.linalg.norm(dynamic - other_dynamic) + np.linalg.norm(reward - other_reward)\n \n elif len(dynamic) > len(other_dynamic):\n temp = np.zeros(len(dynamic))\n temp[:len(other_dynamic)] = other_dynamic\n distance = np.linalg.norm(dynamic - temp) + np.linalg.norm(reward - other_reward)\n \n else:\n temp = np.zeros(len(other_dynamic))\n temp[:len(dynamic)] = dynamic\n distance = np.linalg.norm(temp - other_dynamic) + np.linalg.norm(reward - other_reward)\n \n return distance\n \n\n def merge(self, other):\n if not isinstance(other, Pattern):\n return NotImplemented\n if self.n > 1e10: # sample size large enough, do not need to merge\n return\n self.n += other.n\n# print(self.n_s)\n# print(other.n_s)\n if len(self.n_s) == len(other.n_s):\n self.n_s += other.n_s\n elif len(self.n_s) > len(other.n_s):\n temp = np.zeros(len(self.n_s))\n temp[:len(other.n_s)] = other.n_s\n self.n_s += temp\n else:\n temp = np.zeros(len(other.n_s))\n temp[:len(self.n_s)] = self.n_s\n self.n_s = temp + other.n_s\n self.r += other.r\n\n def __str__(self):\n return str(self.name)\n\n\n\n","sub_path":"simple_rl/agents/PatternClass.py","file_name":"PatternClass.py","file_ext":"py","file_size_in_byte":2585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"212416883","text":"#!/usr/bin/env python3\n# coding=utf-8\n# 素数是指质数,一个大于1的自然数,除了1和它自身外,不能整除其他自然数的数叫做质数;否则称为合数\nclass PrimeNumbers(object):\n def __init__(self, start, end):\n self.start = start\n self.end = end\n\n def is_prime(self, k):\n if k < 2:\n return False\n for i in range(2, k):\n if k % i == 0:\n return False\n # for 循环结束,表明是素数\n return True\n\n # 迭代器接口\n def __iter__(self):\n for k in range(self.start, self.end + 1):\n if self.is_prime(k):\n yield k\n# test\nif __name__ == '__main__':\n for x in PrimeNumbers(1, 100):\n print(x)\n\n\n","sub_path":"01_Python_Basics/38-generator-yield.py","file_name":"38-generator-yield.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"404351679","text":"import numpy as np\nfrom Activation import ActivationFunction\n\n\nclass Layer:\n def __init__(self,number_members,Input_shape=None,Activation = None,Dropout = 0,Weight_param='Default'):\n self.Input_shape = Input_shape\n self.n_mem = number_members\n self.delayed = False\n self.bias = 0 #np.random.randn(self.n_mem).reshape(1,-1);\n\n self.Weight_param = Weight_param.lower();\n\n if(Dropout > 1): raise Exception('Probability exceed 1')\n self.Dropout = Dropout\n\n if self.Input_shape is not None and self.n_mem is not None:\n self.init_weight();\n else:\n self.delayed = True\n\n\n if Activation is None:\n Activation = (lambda x:x,lambda x:1)\n\n self.Activation = Activation[0];\n self.dActivation = Activation[1];\n\n def forwardprop(self,prev):\n if prev.shape[1] != self.Input_shape:\n raise Exception('dimension Exception')\n\n self.prev = prev\n self.bout = self.prev.dot(self.W) + self.bias\n self.aout = self.Activation(self.bout)\n self.aout = self.aout * np.random.choice(2,self.n_mem,p=[self.Dropout,1-self.Dropout])\n\n\n return self.aout\n\n def backprop(self):\n pass\n\n\n def init_weight(self):\n if self.Weight_param == 'xaiver': # recommend for sigmoid & tanh init\n self.W = np.random.randn(self.Input_shape, self.n_mem) / np.sqrt(self.Input_shape)\n elif self.Weight_param =='he': # recommend for relu\n self.bias = 0\n self.W = np.random.randn(self.Input_shape, self.n_mem) / np.sqrt(self.Input_shape/2)\n else:\n self.W = 0.01* np.random.randn(self.Input_shape, self.n_mem)\n\n def fill_delayed_value(self):\n if self.Input_shape is not None:\n self.init_weight();\n\nif __name__ == '__main__':\n\n I1 = np.random.randn(10).reshape(-1,10)\n L1 = Layer(Input_shape=I1.shape[1],number_members= 3,Activation=ActivationFunction.Relu)\n\n print(I1)\n print(L1.forwardprop(I1))\n print(L1.W)\n print(I1.dot(L1.W))\n print(L1.bout)\n print(L1.aout)\n","sub_path":"Layer.py","file_name":"Layer.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"284820895","text":"#!/usr/bin/env python3\n\nfrom sys import argv,version_info\nimport serial\n\nassert version_info >= (3,)\n\ndef send_bytes(data, port={'tty':'/dev/ttyACM0', 'baud':9600}):\n\tif type(port) is serial.Serial:\n\t\twrite=port.write\n\tif type(port) is dict:\n\t\twrite = serial.Serial(port['tty'], port['baud']).write\n\twrite(data)\n\ndef set_leds(led_dict, writebytefunc=(send_bytes,[],{})):\n\tBITMASK_1BIT = [0b00000001< dict:\n \"\"\"Return a item\"\"\"\n ref_genomes = {\n \"C. Jejuni\": \"NC_111\",\n \"M. upium\": \"NC_222\",\n \"C. difficile\": \"NC_333\",\n }\n item = dict(\n name=name,\n internal_id=internal_id,\n reads=\"1000\",\n container=\"96 well plate\",\n container_name=\"hej\",\n rml_plate_name=None,\n well_position=well_position,\n well_position_rml=None,\n sex=None,\n panels=None,\n require_qcok=True,\n application=\"MWRNXTR003\",\n source=None,\n status=None,\n customer=\"cust015\",\n family=None,\n priority=\"standard\",\n capture_kit=None,\n comment=\"comment\",\n index=None,\n reagent_label=None,\n tumour=False,\n custom_index=None,\n elution_buffer=\"Nuclease-free water\",\n organism=organism,\n reference_genome=ref_genomes[organism],\n extraction_method=\"MagNaPure 96 (contact Clinical Genomics before \" \"submission)\",\n analysis=\"fastq\",\n concentration_weight=\"1\",\n mother=None,\n father=None,\n )\n return item\n\n order = {\n \"customer\": \"cust000\",\n \"name\": \"test order\",\n \"internal_id\": \"lims_reference\",\n \"comment\": \"test comment\",\n \"ticket_number\": \"123456\",\n \"items\": [\n _get_item(\"Jag\", \"ms1\", \"D:5\", \"C. Jejuni\"),\n _get_item(\"testar\", \"ms2\", \"H:5\", \"M. upium\"),\n _get_item(\"list\", \"ms3\", \"A:6\", \"C. difficile\"),\n ],\n \"project_type\": \"microbial\",\n }\n return order\n\n\n@pytest.yield_fixture(scope=\"function\")\ndef microbial_store(base_store, microbial_submitted_order):\n \"\"\"Setup a store instance for testing analysis API.\"\"\"\n customer = base_store.customer(microbial_submitted_order[\"customer\"])\n\n order = base_store.MicrobialOrder(\n internal_id=microbial_submitted_order[\"internal_id\"],\n name=microbial_submitted_order[\"name\"],\n ticket_number=microbial_submitted_order[\"ticket_number\"],\n comment=microbial_submitted_order[\"comment\"],\n created_at=dt.datetime(2012, 3, 3, 10, 10, 10),\n updated_at=dt.datetime(2012, 3, 3, 10, 10, 10),\n ordered_at=dt.datetime(2012, 3, 3, 10, 10, 10),\n )\n\n order.customer = customer\n base_store.add(order)\n\n for sample_data in microbial_submitted_order[\"items\"]:\n application_version = base_store.application(sample_data[\"application\"]).versions[0]\n organism = base_store.Organism(\n internal_id=sample_data[\"organism\"], name=sample_data[\"organism\"]\n )\n base_store.add(organism)\n sample = base_store.add_microbial_sample(\n name=sample_data[\"name\"],\n sex=sample_data[\"sex\"],\n internal_id=sample_data[\"internal_id\"],\n ticket=microbial_submitted_order[\"ticket_number\"],\n reads=sample_data[\"reads\"],\n comment=sample_data[\"comment\"],\n organism=organism,\n priority=sample_data[\"priority\"],\n reference_genome=sample_data[\"reference_genome\"],\n application_version=application_version,\n )\n sample.microbial_order = order\n sample.application_version = application_version\n sample.customer = customer\n sample.organism = organism\n\n base_store.add(sample)\n\n base_store.commit()\n yield base_store\n\n\n@pytest.yield_fixture(scope=\"function\", name=\"analysis_obj\")\ndef fixture_analysis_obj(analysis_store):\n \"\"\"Fetch a analysis object from a populated store\"\"\"\n return analysis_store.analyses()[0]\n\n\n@pytest.yield_fixture(scope=\"function\")\ndef family_obj(analysis_obj):\n \"\"\"Return a family models object.\"\"\"\n return analysis_obj.family\n","sub_path":"tests/store/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":4584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"480193293","text":"import csv\nimport datetime\nimport time\nimport os.path\nfrom os import path\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup\n\nurl = 'https://chaturbate.com'\nfilename = 'files/test_' + datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')\n\n\ndef getPage(url,counter):\n\n\tdriver.get(url)\n\n\t\"\"\"\n\tif path.exists(htmlfile):\n\t\tfh = open(htmlfile,'r')\n\t\thtmlcontent = fh.read()\n\telse:\n\t\"\"\"\n\n\thtmlcontent = driver.page_source\n\n\t# write HTML file\n\tfh = open(filename + '_' + str(counter) + '.html','w')\n\tfh.write(htmlcontent)\n\n\t# parse HTML\n\tsoup = BeautifulSoup(htmlcontent)\n\n\tprint(soup.prettify())\n\n\tmylis = soup.findAll('li', {'class': 'room_list_room'})\n\tprint(len(mylis))\n\n\t# process each room box\n\tfor myli in mylis:\n\n\t\tprint(myli)\n\n\t\troom = {}\n\t\troom['name'] = myli.find('a').get('data-room')\n\t\troom['subject'] = myli.find('ul', {'class': 'subject'}).text.replace('\\n', '')\n\t\troom['location'] = myli.find('li', {'class': 'location'}).text\n\n\t\ttmp = myli.find('li', {'class': 'cams'}).text.replace(' ','')\n\t\ttmp = tmp.split(',')\n\t\troom['time'] = tmp[0].replace('hrs', '')\n\t\troom['viewers'] = tmp[1].replace('viewers', '')\n\n\t\ttmp = myli.find('div', {'class': 'title'}).find('span')\n\t\troom['age'] = tmp.text\n\t\troom['gender'] = tmp.attrs['class'][1]\n\n\t\trooms.append(room)\n\n\ttry:\n\t\t# get the link to the next page from the next button\n\t\tnext_button = driver.find_element_by_class_name('next')\n\t\tnextlink = next_button.get_attribute('href')\n\texcept:\n\t\tprint(\"captcha at \" + str(counter))\n\t\treturn False\n\n\tprint(nextlink)\n\n\t#if counter > 2:\n\t#\treturn False\n\n\tif nextlink.endswith('#'):\n\t\treturn False\n\telse:\n\t\treturn nextlink\n\n\ndriver = webdriver.Chrome()\nrooms = []\n\ncounter = 0\nnextstep = url\n\nwhile nextstep is not False:\n\tnextstep = getPage(nextstep,counter)\n\tcounter += 1\n\ttime.sleep(10)\n\ncsvfilename = filename + '.csv'\nkeys = rooms[0].keys()\nwith open(csvfilename, 'w', newline='') as output_file:\n\tdict_writer = csv.DictWriter(output_file, keys)\n\tdict_writer.writeheader()\n\tdict_writer.writerows(rooms)\n\ndriver.quit()","sub_path":"scrape_selenium.py","file_name":"scrape_selenium.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"9998765","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport os, sys\nimport traceback\n# sys.path.append(\"python_package/xlrd/lib/python\")\n# sys.path.append(\"python_package/xlwt/lib\")\nsys.path.append(os.path.join('python_package', 'xlrd', 'lib', 'python'))\nsys.path.append(os.path.join('python_package', 'xlwt', 'lib'))\nsys.path.append(os.path.join('python_package'))\n\nimport xlrd\nimport xlwt\nfrom xlrd import open_workbook\n\nimport ntpath\nimport json\n\n# create logger\n#----------------------------------------------------------------------\nimport logging\n\n# numeric_level = getattr(logging, loglevel.upper(), None)\n# if not isinstance(numeric_level, int):\n# raise ValueError('Invalid log level: %s' % loglevel)\n\n# logging.basicConfig(level=logging.INFO)\n\nlog = logging.getLogger('python_logger')\nlog.setLevel(logging.DEBUG)\n\nfh = logging.FileHandler('out.log', 'w')\nfh.setLevel(logging.DEBUG)\n# create console handler with a higher log level\nch = logging.StreamHandler()\nch.setLevel(logging.INFO)\n# create formatter and add it to the handlers\n# formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n# 2015-08-28 17:01:57,662 - simple_example - ERROR - error message\n\n# formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(filename)s:%(lineno)-4d: %(message)s')\nformatter = logging.Formatter('%(asctime)s %(levelname)-2s %(lineno)-4d: %(message)s')\n\nfh.setFormatter(formatter)\nch.setFormatter(formatter)\n# add the handlers to the logger\nlog.addHandler(fh)\nlog.addHandler(ch)\n#----------------------------------------------------------------------\n\n# 'application' code\n# logger.debug('debug message')\n# logger.info('info message')\n# logger.warn('warn message')\n# logger.error('error message')\n# logger.critical('critical message')\n#----------------------------------------------------------------------\n# create logger end\n\nMAX_ROW_NUM = 60000\n\n\ndef TestImport():\n log.info(\"test import success\")\n\nclass Order(object):\n def __init__(self, order_ID, dest_name, dest_province, dest_city, dest_country, dest_addr, dest_phone_num, src_name, note):\n self.order_ID = order_ID\n self.dest_name = dest_name\n self.dest_province = dest_province\n self.dest_city = dest_city\n self.dest_country = dest_country\n self.dest_addr = dest_addr\n self.dest_phone_num = dest_phone_num\n self.src_name = src_name\n self.note = note\n self.date = unicode(int(note[4:6])) + u'月' + unicode(int(note[6:8])) + u'日'\n self.ID = note[0:4]\n\n def __str__(self):\n return(\"Order object:\\n\"\n \" order_ID = {0}\\n\"\n \" dest_name = {1}\\n\"\n \" dest_province = {2}\\n\"\n \" dest_city = {3}\\n\"\n \" dest_country = {4}\\n\"\n \" dest_addr = {5}\\n\"\n \" dest_phone_num = {6}\\n\"\n \" src_name = {7}\\n\"\n \" note = {8}\\n\"\n \" date = {9}\\n\"\n \" ID = {10}\\n\"\n .format(self.order_ID.encode('UTF-8'), self.dest_name.encode('UTF-8'),\n self.dest_province.encode('UTF-8'), self.dest_city.encode('UTF-8'),\n self.dest_country.encode('UTF-8'), self.dest_addr.encode('UTF-8'),\n unicode(self.dest_phone_num)[:-2].encode('UTF-8'), self.src_name.encode('UTF-8'),\n self.note, self.date.encode('UTF-8'), self.ID\n ))\n\ndef WriteXls(path, element_list, element_info_list):\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet(\"right address\")\n\n head_list = [u\"订单号\",u\"商品名称\",u\"单位\",u\"数量\",u\"单价\",u\"重量\",u\"SKU编码\", u\"SKU名称\", u\"客户名称*\", u\"备注\",u\"收件人姓名\",u\"收件人省\",u\"收件人市\",u\"收件人区\",u\"收件人地址\",u\"收件人邮编\",u\"收件人电话\",u\"收件人手机\",u\"收件人邮箱\",u\"发件人姓名\",u\"发件人省\",u\"发件人市\",u\"发件人区\",u\"发件人地址\",u\"发件人邮编\",u\"发件人电话\",u\"发件人手机\",u\"发件人邮箱\",u\"扩展单号\",u\"批次号\",u\"大头笔\",u\"面单号\",u\"代收货款\",u\"到付款\",u\"网点ID\"]\n for index, item in enumerate(head_list) :\n sheet.write(0, index, item)\n\n for row in range(1, len(element_list) + 1):\n sheet.write(row, head_list.index(u\"数量\"), 1)\n sheet.write(row, head_list.index(u\"代收货款\"), element_info_list[1])\n sheet.write(row, head_list.index(u\"客户名称*\"), element_info_list[2].decode('GBK'))\n sheet.write(row, head_list.index(u\"备注\"), element_info_list[0] + element_info_list[3] + \"%04d\"%row)\n sheet.write(row, head_list.index(u\"收件人姓名\"), element_list[row - 1 ].dest_name)\n sheet.write(row, head_list.index(u\"收件人地址\"), element_list[row - 1].addr)\n sheet.write(row, head_list.index(u\"收件人电话\"), unicode(element_list[row - 1].phone_num)[:-2])\n sheet.write(row, head_list.index(u\"发件人姓名\"), element_list[row - 1].src_name)\n workbook.save(path)\n log.info(\"finish WriteXls:{}, row numbers:{}\".format(path, len(element_list)))\n\n\ndef WriteOrderToSheet(work_book, sheet_name, element_list) :\n sheet = work_book.add_sheet(sheet_name)\n\n head_list = [u'发件日期', u\"快递单号\", u\"收件人姓名\", u\"收件人省\", u\"收件人市\", u\"收件人区\", u\"收件人地址\", u\"收件人电话\", u\"客服\", u\"客户编码\"]\n\n for index, item in enumerate(head_list) :\n sheet.write(0, index, item)\n\n for row in range(1, len(element_list) + 1):\n sheet.write(row, 0, element_list[row - 1].date)\n sheet.write(row, 1, element_list[row - 1].order_ID)\n sheet.write(row, 2, element_list[row - 1].dest_name)\n sheet.write(row, 3, element_list[row - 1].dest_province)\n sheet.write(row, 4, element_list[row - 1].dest_city)\n sheet.write(row, 5, element_list[row - 1].dest_country)\n sheet.write(row, 6, element_list[row - 1].dest_addr)\n sheet.write(row, 7, element_list[row - 1].dest_phone_num)\n sheet.write(row, 8, element_list[row - 1].src_name)\n sheet.write(row, 9, element_list[row - 1].note)\n\n return work_book\n\n\ndef WriteListToXls(path, sheet_name, element_list):\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet(sheet_name)\n col = 0\n for index, item in enumerate(element_list) :\n if (index % (MAX_ROW_NUM -1) == 0 and index > 0) :\n col = col + 1\n sheet.write(index % (MAX_ROW_NUM - 1), col, item)\n\n workbook.save(path)\n log.info(\"finish WriteXls: %s, element numbers is: %s\", path, len(element_list))\n\ndef GetFileList(path):\n from os import listdir\n from os.path import isfile, join\n onlyfiles = [ join(path, f) for f in listdir(path) if isfile(join(path, f))]\n return onlyfiles\n\ndef PathLeaf(path):\n head, tail = ntpath.split(path)\n return tail or ntpath.basename(head)\n\n# read the xls files\n\ndef ParseSheetToList(sheet) :\n ret_list = []\n number_of_rows = sheet.nrows\n number_of_columns = sheet.ncols\n if (number_of_rows <= 0 or number_of_columns <= 0):\n log.error('can not get elem from sheet')\n return ret_list\n\n try:\n for col in range(number_of_columns):\n for row in range(number_of_rows):\n value = sheet.cell(row, col).value\n\n if (type(value) is float and value > 0):\n ret_list.append(\"%.0f\"%value)\n elif (type(value) is unicode and len(value) > 0):\n ret_list.append(value)\n\n\n except Exception:\n log.error(\"Got exception on ParseSheetToList:%s\", traceback.format_exc() )\n return ret_list\n\ndef ReadFinancialFile(path) :\n order_receive_list = []\n order_reject_list = []\n\n ret_dict = {\"receive_list\" : order_receive_list, \"reject_list\" : order_reject_list}\n\n file_list = GetFileList(path)\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n return ret_dict, len(file_list)\n\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n wb = open_workbook(file)\n for sheet in wb.sheets():\n\n if (sheet.name == u\"签收\"):\n order_receive_list.extend(ParseSheetToList(sheet))\n log.debug(\"order_receive_list.size:%d\", len(order_receive_list))\n elif (sheet.name == u\"退回\"):\n order_reject_list.extend(ParseSheetToList(sheet))\n log.debug(\"order_reject_list.size:%d\", len(order_reject_list))\n\n ret_dict[\"receive_list\"] = order_receive_list\n ret_dict[\"reject_list\"] = order_reject_list\n return ret_dict, len(file_list)\n\ndef GetWholeOrderSet(path):\n log.debug(\"GetWholeOrderSet, path:%s\", path)\n file_list = GetFileList(path)\n whole_receive_order_list = []\n whole_reject_order_list = []\n\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n return {}\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n if u'总签收' in file:\n wb = open_workbook(file)\n for sheet in wb.sheets():\n whole_receive_order_list.extend(ParseSheetToList(sheet))\n if u'总退回' in file:\n wb = open_workbook(file)\n for sheet in wb.sheets():\n whole_reject_order_list.extend(ParseSheetToList(sheet))\n\n ret_dict = {\"whole_receive_set\" : set(whole_receive_order_list), \"whole_reject_set\" : set(whole_reject_order_list)}\n log.info(\"whole_receive_order_list.size:%d\", len(set(whole_receive_order_list)))\n log.info(\"whole_reject_order_list.size:%d\", len(set(whole_reject_order_list)))\n return ret_dict\n\ndef WriteWholeReceiveOrderListToFile(path, receive_order_list) :\n log.info(\"GetWholeRejectOrderList, path:%s, receive_order_list.size:%d\", path, len(receive_order_list))\n WriteListToXls(path, u'总签收', receive_order_list)\n\ndef WriteWholeRejectOrderListToFile(path, reject_order_list) :\n log.info(\"GetWholeRejectOrderList, path:%s, reject_order_list.size:%d\", path, len(reject_order_list))\n WriteListToXls(path, u'总退回', reject_order_list)\n\ndef AddFinancialOrderToWholeOrderList(path = u\"单日签收退回from财务\"):\n finanical_order_dict, file_count = ReadFinancialFile(path)\n\n if (len(finanical_order_dict[\"receive_list\"]) == 0 and len(finanical_order_dict[\"reject_list\"]) == 0) :\n log.error(\"can not get order_list from financial path:%s\", path)\n return 0, file_count\n\n whole_order_dict = GetWholeOrderSet(u'签收退回总订单号')\n whole_order_dict[\"whole_receive_set\"] = whole_order_dict[\"whole_receive_set\"] | set(finanical_order_dict[\"receive_list\"])\n whole_order_dict[\"whole_reject_set\"] = whole_order_dict[\"whole_reject_set\"] | set(finanical_order_dict[\"reject_list\"])\n\n WriteListToXls(os.path.join(u'签收退回总订单号', u'总签收.xls'), u'总签收',\n sorted(list(whole_order_dict[\"whole_receive_set\"])))\n WriteListToXls(os.path.join(u'签收退回总订单号', u'总退回.xls'), u'总退回',\n sorted(list(whole_order_dict[\"whole_reject_set\"])))\n\n return len(finanical_order_dict[\"receive_list\"]) + len(finanical_order_dict[\"reject_list\"]), file_count\n\ndef ProcessRowBackOrderToBackOrder(path = u'待处理回单'):\n file_list = GetFileList(path)\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n return 0\n\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n rd_workbook = open_workbook(file)\n wt_workbook = xlwt.Workbook()\n head_list = [u\"快递单号\", u\"收件人姓名\", u\"收件人省\", u\"收件人市\", u\"收件人区\", u\"收件人地址\", u\"收件人电话\", u\"发件人姓名\", u\"备注\"]\n\n for rd_sheet in rd_workbook.sheets():\n\n number_of_rows = rd_sheet.nrows\n number_of_columns = rd_sheet.ncols\n\n rd_head_list = []\n\n if (number_of_rows <= 0 or number_of_columns <= 0):\n continue\n\n wt_sheet = wt_workbook.add_sheet(rd_sheet.name)\n\n for column in range(number_of_columns) :\n rd_head_list.append(rd_sheet.cell(0, column).value)\n\n for index, item in enumerate(head_list) :\n wt_sheet.write(0, index, item)\n\n for row in range(1, number_of_rows) :\n wt_sheet.write(row, head_list.index(u\"快递单号\"), rd_sheet.cell(row, rd_head_list.index(u\"快递单号\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人姓名\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人姓名\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人省\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人省\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人市\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人市\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人区\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人区\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人地址\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人地址\")).value)\n wt_sheet.write(row, head_list.index(u\"收件人电话\"), rd_sheet.cell(row, rd_head_list.index(u\"收件人电话\")).value)\n wt_sheet.write(row, head_list.index(u\"发件人姓名\"), rd_sheet.cell(row, rd_head_list.index(u\"发件人姓名\")).value)\n wt_sheet.write(row, head_list.index(u\"备注\"), rd_sheet.cell(row, rd_head_list.index(u\"备注\")).value)\n\n path = os.path.join(u'已处理回单', u'已处理回单_' + PathLeaf(file))\n wt_workbook.save(path)\n log.debug(\"write file: %s\", path)\n return len(file_list)\n\n\n\ndef ProcessRowBackOrderToRecordOrder(path = u'待处理回单'):\n file_list = GetFileList(path)\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n return 0\n\n elem_list = [u'小李', '17090152657', u'河南', u'信阳', u'浉河区', u'河南信阳市浉河区平西涵洞', u'张海霞', '15293143927', u'甘肃省', u'兰州市', u'榆中县', u'详情见面单', u'物品', 0, 0]\n\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n wt_workbook = xlwt.Workbook()\n wt_sheet = wt_workbook.add_sheet(\"sheet1\")\n\n rd_workbook = open_workbook(file)\n # head_list = [u\"快递单号\", u\"收件人姓名\", u\"收件人省\", u\"收件人市\", u\"收件人区\", u\"收件人地址\", u\"收件人电话\", u\"发件人姓名\", u\"备注\"]\n\n for rd_sheet in rd_workbook.sheets():\n\n number_of_rows = rd_sheet.nrows\n number_of_columns = rd_sheet.ncols\n\n if (number_of_rows <= 0 or number_of_columns <= 0):\n continue\n\n rd_head_list = []\n for column in range(number_of_columns) :\n rd_head_list.append(rd_sheet.cell(0, column).value)\n\n # for index, item in enumerate(head_list) :\n # wt_sheet.write(0, index, item)\n\n for row in range(1, number_of_rows) :\n wt_sheet.write(row, 0, rd_sheet.cell(row, rd_head_list.index(u\"快递单号\")).value)\n\n for idx, elem in enumerate(elem_list):\n wt_sheet.write(row, idx + 2, elem)\n\n wt_sheet.write(row, 17, rd_sheet.cell(row, rd_head_list.index(u\"代收货款\")).value)\n\n path = os.path.join(u'录单', u'录单_' + PathLeaf(file))\n wt_workbook.save(path)\n log.info(\"finish WriteXls: %s, element numbers is: %s\", path, number_of_rows)\n return len(file_list)\n\ndef ParseBackOrderToBill(path = u'已处理回单') :\n log.info(\"ParseBackOrderToBill, path:%s\", path)\n\n file_list = GetFileList(path)\n if len(file_list) == 0:\n log.error(\"can not find file in path:%s\", path)\n\n whole_order_dict = GetWholeOrderSet(u'签收退回总订单号')\n\n for file in file_list:\n log.info(\"open file: %s\", file)\n\n # get order book list\n order_list = []\n order_receive_list = []\n order_reject_list = []\n order_unknown_list = []\n rd_workbook = open_workbook(file)\n for sheet in rd_workbook.sheets():\n number_of_rows = sheet.nrows\n number_of_columns = sheet.ncols\n\n if (number_of_rows <= 0 or number_of_columns <= 0):\n continue\n\n for row in range(1, number_of_rows) :\n values = []\n\n for col in range(number_of_columns) :\n value = sheet.cell(row,col).value\n if (type(value) is unicode or type(value) is str):\n value = value.replace(u'\\xa0', \"\").replace(u\" \", \"\").replace(u'\\uff0c',\"\").replace(u\",\",\"\")\n values.append(value)\n\n order = Order(*values)\n order_list.append(order)\n\n if len(order_list) <= 0 :\n continue\n\n log.debug(\"get order_list number:%d\", len(order_list))\n\n for order in order_list:\n log.debug(order)\n break\n\n # check order status\n for order in order_list:\n if order.order_ID in whole_order_dict[\"whole_receive_set\"]:\n order_receive_list.append(order)\n elif order.order_ID in whole_order_dict[\"whole_reject_set\"]:\n order_reject_list.append(order)\n else:\n order_unknown_list.append(order)\n\n # write order to bill xls\n wt_workbook = xlwt.Workbook()\n\n sheet = wt_workbook.add_sheet(u'总汇')\n for index, item in enumerate([u'客户编码', u'发货日期', u'总发货量', u'签收件', u'退回件', u'无状态']) :\n sheet.write(0, index, item)\n\n sheet.write(1, 0, order_list[0].ID)\n sheet.write(1, 1, order_list[0].date)\n sheet.write(1, 2, len(order_list))\n sheet.write(1, 3, len(order_receive_list))\n sheet.write(1, 4, len(order_reject_list))\n sheet.write(1, 5, len(order_unknown_list))\n\n wt_workbook = WriteOrderToSheet(wt_workbook, u'签收件', order_receive_list)\n wt_workbook = WriteOrderToSheet(wt_workbook, u'退回件', order_reject_list)\n wt_workbook = WriteOrderToSheet(wt_workbook, u'无状态', order_unknown_list)\n\n # write bill file\n path = os.path.join(u'账单', u'账单_' + PathLeaf(file))\n wt_workbook.save(path)\n log.info(\"finish WriteXls: %s, row numbers: %d\", path, len(order_list))\n return len(file_list)\n\ndef TestWriteXLS(end_num):\n wt_workbook = xlwt.Workbook()\n wt_sheet = wt_workbook.add_sheet(\"test1\")\n\n for i, elem in enumerate(range(1, end_num)):\n wt_sheet.write(i, 1, elem)\n\n wt_workbook.save(\"test.xls\")\n\n\ndef Start() :\n while (True):\n log.info(\"\\n\\n\\n\")\n log.info(\"*******************************\")\n log.info(u\"1. 将财务订单号导入总订单号\")\n log.info(u\"2. 将系统导出回单处理成回单\")\n log.info(u\"3. 将回单处理成账单\")\n log.info(u\"4. 将回单处理成录单\")\n log.info(u\"5. 1->2->3->4 依次完成\")\n log.info(u\"6. 退出\")\n log.info(\"*******************************\")\n log.info(u\"输入你想选择的功能(1 ~ 6):\")\n\n try :\n choose_num = int(raw_input())\n log.info(\"\\n\\n\\n\")\n\n log.info(u'你的选择是: %d', choose_num)\n\n if (choose_num == 1):\n log.info(u\"1. 将财务订单号导入总订单号 开始.\")\n input_num, file_num = AddFinancialOrderToWholeOrderList()\n log.info(u\"1. 将财务订单号导入总订单号 完成, 导入数量: %d, 导入文件数: %d\", input_num, file_num)\n\n elif (choose_num == 2):\n log.info(u\"2. 将系统导出回单处理成回单 开始.\")\n file_num = ProcessRowBackOrderToBackOrder()\n log.info(u\"2. 将系统导出回单处理成回单 完成, 处理文件数:%d\", file_num)\n\n elif (choose_num == 3):\n log.info(u\"3. 将回单处理成账单 开始.\")\n file_num = ParseBackOrderToBill()\n log.info(u\"3. 将回单处理成账单 完成, 处理文件数:%d\", file_num)\n\n elif (choose_num == 4):\n log.info(u\"4. 将回单处理成录单 开始.\")\n file_num = ProcessRowBackOrderToRecordOrder()\n log.info(u\"4. 将回单处理成录单 完成, 处理文件数:%d\", file_num)\n\n elif (choose_num == 5):\n log.info(u\"1. 将财务订单号导入总订单号 开始.\")\n input_num, file_num = AddFinancialOrderToWholeOrderList()\n log.info(u\"1. 将财务订单号导入总订单号 完成, 导入数量: %d, 导入文件数: %d\", input_num, file_num)\n log.info(\"\\n\\n\")\n\n log.info(u\"2. 将系统导出回单处理成回单 开始.\")\n file_num = ProcessRowBackOrderToBackOrder()\n log.info(u\"2. 将系统导出回单处理成回单 完成, 处理文件数:%d\", file_num)\n log.info(\"\\n\\n\")\n\n log.info(u\"3. 将回单处理成账单 开始.\")\n file_num = ParseBackOrderToBill()\n log.info(u\"3. 将回单处理成账单 完成, 处理文件数:%d\", file_num)\n log.info(\"\\n\\n\")\n\n log.info(u\"4. 将回单处理成录单 开始.\")\n file_num = ProcessRowBackOrderToRecordOrder()\n log.info(u\"4. 将回单处理成录单 完成, 处理文件数:%d\", file_num)\n\n elif (choose_num == 6):\n break\n else:\n log.info(u'输入非法, 请输入数字: 1~6')\n continue\n except Exception:\n log.error(\"Got exception on ParseSheetToList:%s\", traceback.format_exc() )\n continue\n\n\nif __name__ == \"__main__\":\n Start()\n\n\n\n","sub_path":"order_analysis.py","file_name":"order_analysis.py","file_ext":"py","file_size_in_byte":20514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"542778805","text":"import typing\n\n\n\ndef le_bytes_to_int(as_bytes: bytes, signed: bool) -> int:\n \"\"\"Converts a little endian byte array to an integer.\n\n :param as_bytes: A little endian encoded byte array integer.\n :param signed: Flag indicating whether integer is signed.\n\n \"\"\"\n return int.from_bytes(as_bytes, byteorder='little', signed=signed) \n\n\ndef int_to_le_bytes(x: int, length: int, signed: bool) -> bytes:\n \"\"\"Converts an integer to a little endian byte array.\n\n :param x: An integer to be mapped.\n :param length: Length of mapping output.\n :param signed: Flag indicating whether integer is signed.\n\n \"\"\"\n if not isinstance(x, int):\n x = int(x)\n\n return bytes([i for i in x.to_bytes(length, 'little', signed=signed)])\n\n\ndef int_to_le_bytes_trimmed(x: int, length: int, signed: bool) -> bytes:\n \"\"\"Converts an integer to a little endian byte array with trailing zeros removed.\n\n :param x: An integer to be mapped.\n :param length: Length of mapping output.\n :param signed: Flag indicating whether integer is signed.\n\n \"\"\" \n value = int_to_le_bytes(x, length, signed)\n while value[-1] == 0:\n value = value[0:-1]\n \n return value or bytes([0])\n\n\ndef humanized_time_interval_to_milliseconds(interval: str) -> int: \n \"\"\"Converts a human readable time interval to milliseconds.\n\n :param interval: A human readable time interval. \n :returns: Time interval in milliseconds.\n\n \"\"\"\n interval = interval.lower()\n try:\n int(interval)\n except ValueError:\n ...\n else:\n return int(interval)\n\n if interval.endswith(\"ms\"):\n return int(interval[0:-2])\n if interval.endswith(\"s\"):\n return int(interval[0:-1]) * (1000)\n if interval.endswith(\"m\"):\n return int(interval[0:-1]) * (60 * 1000)\n print(\"TODO: convert m\")\n if interval.endswith(\"h\"):\n return int(interval[0:-1]) * (60 * 60 * 1000)\n print(\"TODO: convert h\")\n if interval.endswith(\"day\"):\n return int(interval[0:-3]) * (24 * 60 * 60 * 1000)\n\n raise ValueError(\"Unsupported humanized time interval\")\n\n\ndef milliseconds_to_humanized_time_interval(interval: int):\n \"\"\"Converts milliseconds to a human readable time interval.\n \n :param interval: Time interval in milliseconds. \n :returns: A human readable time interval.\n\n \"\"\"\n pass\n","sub_path":"pycspr/utils/conversion.py","file_name":"conversion.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"48189041","text":"import json\nimport requests\nfrom bs4 import BeautifulSoup as B\nfrom standardize_sets import Standardize\n\nstd = Standardize()\n\ndef get_scg_inventory():\n card_dict = {}\n page = 3600\n total_pages = 3800#448 * 200\n page_count = 1\n while page <= total_pages:\n try:\n url = 'http://www.starcitygames.com/results?&numpage=200&display=3&startnum=' + str(page)\n\n r = requests.get(url).content\n soup = B(r, 'html.parser')\n\n # Get table that contains buylist data and filter out results that == NOne\n table = soup.find('table', {'id': 'search_results_table'})\n table = table.find_all('tr')\n table = [i for i in table if i.get('class') != None]\n\n # While loop to loop over each row of card data\n count = 0\n while count < len(table):\n\n # Create card varaibles and filter out every other row which == None\n stock = table[count].find('td', {'class': 'deckdbbody search_results_8'})\n if stock != None:\n stock = table[count].find('td', {'class': 'deckdbbody search_results_8'}).text.strip()\n else:\n try:\n stock = table[count].find('td', {'class': 'deckdbbody2 search_results_8'}).text.strip()\n except AttributeError:\n pass\n price = table[count].find('td', {'class': 'deckdbbody search_results_9'})\n if price != None:\n price = table[count].find('td', {'class': 'deckdbbody search_results_9'}).text.strip()\n else:\n try:\n price = table[count].find('td', {'class': 'deckdbbody2 search_results_9'}).text.strip()\n except AttributeError:\n pass\n expansion = table[count].find('td', {'class': 'deckdbbody search_results_2'})\n if expansion != None:\n expansion = std.expansion(table[count].find('td', {'class': 'deckdbbody search_results_2'}).text.strip())\n\n else:\n try:\n expansion = std.expansion(table[count].find('td', {'class': 'deckdbbody2 search_results_2'}).text.strip())\n except AttributeError:\n pass\n\n\n\n # Create variable to check if key already in dictionary. If it's not, create it. Else, continue\n try:\n info = table[count].a.text.strip()\n if info not in ['PL', 'HP']:\n t = card_dict.get(expansion)\n if t == None:\n card_dict[expansion] = {}\n card_dict[expansion][info] = {\n 'nm': {'stock': 'Out of Stock', 'price': None},\n 'pl': {'stock': 'Out of Stock', 'price': None},\n }\n\n # Update dictionary ith price and stock\n card_dict[expansion][info]['nm']['stock'] = stock\n card_dict[expansion][info]['nm']['price'] = price\n\n\n else:\n try:\n if info == 'PL':\n e = table[count-1].find('td', {'class': 'deckdbbody search_results_2'})\n if e != None:\n e = table[count-1].find('td', {'class': 'deckdbbody search_results_2'}).text.strip()\n else:\n try:\n e = table[count-1].find('td', {'class': 'deckdbbody2 search_results_2'}).text.strip()\n except IndexError as error:\n print(error)\n except AttributeError as error:\n print(e, error)\n try:\n card_dict[e][table[count-1].a.text.strip()]['pl']['stock'] = stock\n card_dict[e][table[count-1].a.text.strip()]['pl']['price'] = price\n except KeyError as error:\n print(error)\n except IndexError as error:\n print(error)\n\n '''try:\n if info == 'HP':\n e = table[count-2].find('td', {'class': 'deckdbbody search_results_2'})\n if e != None:\n e = table[count-2].find('td', {'class': 'deckdbbody search_results_2'}).text.strip()\n else:\n try:\n e = table[count-2].find('td', {'class': 'deckdbbody2 search_results_2'}).text.strip()\n except IndexError as error:\n print(error)\n except AttributeError as error:\n print(e, error)\n try:\n card_dict[e][table[count-2].a.text.strip()]['pl']['stock'] = stock\n card_dict[e][table[count-2].a.text.strip()]['pl']['price'] = price\n except KeyError as error:\n print(error)\n except IndexError as error:\n print(error)'''\n except AttributeError as error:\n print(error)\n count += 1\n\n print(page_count)\n page_count += 1\n page += 200\n except AttributeError as error:\n page += 200\n\n for k,y in card_dict.items():\n print(k, y)\n json.dump(card_dict, open('scg_store.json', 'w'))\nget_scg_inventory()\n'''x = json.load(open('scg_store.json'))\nprint(x['Alpha']['Living Wall'])'''\n","sub_path":"starcity_store.py","file_name":"starcity_store.py","file_ext":"py","file_size_in_byte":6167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"237747711","text":"#Задание утеряно\r\n#Метод хорд\r\n\r\nimport math \r\nnow=0.5 \r\nprevious=1 \r\nx0=math.pi/2 \r\nepsilon=0.5*10**(-5) \r\nn=0 \r\ndef f(xn): \r\n return math.sin(xn)+0.1-2*xn**2 \r\nfx0=f(x0) \r\nwhile abs(now-previous)>epsilon: \r\n previous=now \r\n now=now-f(now)*(now-x0)/(f(now)-fx0) \r\n n+=1 \r\nprint (now) \r\nprint (n) ","sub_path":"Метод хорд.py","file_name":"Метод хорд.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"186176138","text":"from machine import Pin\nfrom time import sleep\n\nled = Pin(2, Pin.OUT)\nbp = Pin(25, Pin.IN)\n\ncompt = 0 \nwhile True : \n if bp.value() : compt = 20 \n led.value(compt > 0) # si compt > 0, cela fait led.value(True) \n sleep(0.1)\n compt -= (compt > 0) # raccourci pour : compt = compt - (compt > 0)","sub_path":"tempo-eclairage-optimise.py","file_name":"tempo-eclairage-optimise.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"588971758","text":"\n\nfrom xai.brain.wordbase.nouns._cannonball import _CANNONBALL\n\n#calss header\nclass _CANNONBALLS(_CANNONBALL, ):\n\tdef __init__(self,): \n\t\t_CANNONBALL.__init__(self)\n\t\tself.name = \"CANNONBALLS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"cannonball\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_cannonballs.py","file_name":"_cannonballs.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"31382852","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2018-2021, earthobservations developers.\n# Distributed under the MIT License. See LICENSE for more info.\nfrom enum import Enum\n\nDWD_SERVER = \"https://opendata.dwd.de\"\nDWD_CDC_PATH = \"climate_environment/CDC/\"\n\nDWD_MOSMIX_S_PATH = \"weather/local_forecasts/mos/MOSMIX_S/all_stations/kml/\"\nDWD_MOSMIX_L_PATH = \"weather/local_forecasts/mos/MOSMIX_L/all_stations/kml/\"\nDWD_MOSMIX_L_SINGLE_PATH = \"weather/local_forecasts/mos/MOSMIX_L/single_stations/\"\n\n\nclass DWDCDCBase(Enum):\n CLIMATE_OBSERVATIONS = \"observations_germany/climate/\"\n\n\nDWD_FOLDER_MAIN = \"./dwd_data\"\nDWD_FOLDER_STATION_DATA = \"station_data\"\nDWD_FILE_STATION_DATA = \"dwd_station_data\"\nSTATION_ID_REGEX = r\"(?\n'''\n\nfrom django.conf import settings\nfrom django.contrib.sessions.backends.base import SessionBase, CreateError\nfrom newcache import CacheClass\n\n\nclass Cache(CacheClass):\n\n def __init__(self, server, params):\n super(Cache, self).__init__('', params)\n self._servers = server\n\n\nclass SessionStore(SessionBase):\n '''A memcached-based session store. Useful if you wish to use memcached as\n the session backend, but another cache method for general caching.\n\n This backend requires `django-newcache`_, and one of the following\n memcache libraries:\n\n * `pylibmc`_ (recommended)\n * `python-memcached`_\n\n .. _django-newcache: http://github.com/ericflo/django-newcache\n .. _pylibmc: http://pypi.python.org/pypi/pylibmc\n .. _python-memcached: http://pypi.python.org/pypi/python-memcached\n\n To use:\n\n * Set ``SESSION_ENGINE`` in ``settings.py`` to\n ``baph.sessions.backends.memcache``.\n * Set ``SESSION_MEMCACHE_SERVERS`` in ``settings.py`` to a list of one or\n more memcache servers that will be used.\n * If necessary, set the ``SESSION_MEMCACHE_SETTINGS`` variable in\n ``settings.py``. This is a dictionary populated with settings such as\n ``max_entries``.\n '''\n\n def __init__(self, session_key=None):\n session_memcache_settings = getattr(settings,\n 'SESSION_MEMCACHE_SETTINGS',\n {})\n self._cache = Cache(settings.SESSION_MEMCACHE_SERVERS,\n session_memcache_settings)\n super(SessionStore, self).__init__(session_key)\n\n def load(self):\n session_data = self._cache.get(self.session_key)\n if session_data is not None:\n return session_data\n self.create()\n return {}\n\n def create(self):\n # Because a cache can fail silently (e.g. memcache), we don't know if\n # we are failing to create a new session because of a key collision or\n # because the cache is missing. So we try for a (large) number of times\n # and then raise an exception. That's the risk you shoulder if using\n # cache backing.\n for i in xrange(10000):\n self.session_key = self._get_new_session_key()\n try:\n self.save(must_create=True)\n except CreateError:\n continue\n self.modified = True\n return\n raise RuntimeError(\"Unable to create a new session key.\")\n\n def save(self, must_create=False):\n if must_create:\n func = self._cache.add\n else:\n func = self._cache.set\n result = func(self.session_key, self._get_session(no_load=must_create),\n self.get_expiry_age())\n if must_create and not result:\n raise CreateError\n\n def exists(self, session_key):\n return session_key in self._cache\n\n def delete(self, session_key=None):\n if session_key is None:\n if self._session_key is None:\n return\n session_key = self._session_key\n self._cache.delete(session_key)\n","sub_path":"baph/sessions/backends/memcache.py","file_name":"memcache.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"473763466","text":"from graphics import *\nimport math\n\n\ncolors = [\"black\", \"red\", \"blue\", \"green\", \"orange\", \"darkblue\", \"yellow\"]\n\nWIN_SIZE = 1000\n\n\ndef main():\n\n # FOR DEMO\n\n # rings = 2\n # size = 40\n\n win_center = Point(WIN_SIZE//2, WIN_SIZE//2)\n hex_size = 120\n hex_size_short = hex_size * math.sqrt(3) / 2\n\n # cir = Circle(win_center, hex_size) # circumscribed circle on center hex\n # cir.setFill(\"grey\")\n # cir.draw(win)\n done = Circle(Point(20, 20), 15)\n done.setOutline(\"red\")\n\n board = Board()\n board.place(win_center, hex_size)\n\n print()\n print(board)\n\n win = GraphWin(\"don't read this\", WIN_SIZE, WIN_SIZE, autoflush=False)\n done.draw(win)\n board.draw(win)\n win.update()\n win.autoflush = True\n\n click = win.getMouse()\n while not in_shape(done, click):\n board.get_vertex_click(click)\n board.get_hex_click(click)\n click = win.getMouse()\n\n win.close()\n\n\nclass Board:\n def __init__(self, rings=2):\n self.rings = rings\n hexes = [[None for i in range(rings*2+1)] for i in range(rings*2+1)]\n num = 0\n for q in range(-rings, rings+1):\n for r in range(max(-rings,-q-rings), min(rings, -q+rings)+1):\n hx_coord = Point(q, r)\n print(\"placing H {:2} in {:2} {:2}\".format(num, hx_coord.x, hx_coord.y), sep=\"\") # DEBUG\n if hexes[hx_coord.x][hx_coord.y] is not None: print(\"DUPLICATE\") # DEBUG\n hexes[hx_coord.x][hx_coord.y] = Hex(hx_coord)\n num += 1\n self.hexes = hexes\n\n print('\\n') # DEBUG\n\n rings *= 2\n vertices = [[None for i in range(rings*2+1)] for i in range(rings*2+1)]\n num = 0\n for q in range(-rings, rings+1):\n for r in range(max(-rings,-q-rings), min(rings, -q+rings)+1):\n vx_coord = Point(q, r)\n print(\"placing V {:2} in {:2} {:2}\".format(num, vx_coord.x, vx_coord.y), sep=\"\") # DEBUG\n if vertices[vx_coord.x][vx_coord.y] is not None: print(\"DUPLICATE\") # DEBUG\n vertices[vx_coord.x][vx_coord.y] = Vertex(vx_coord)\n num += 1\n\n self.vertices = vertices\n\n print(\"\\n\") # DEBUG\n\n def place(self, center, hex_size):\n self.hex_size = hex_size\n self.center = center\n self.hex_size_short = hex_size * math.sqrt(3) / 2\n # self.vertex_size = (hex_size-hex_size_short)*2 # 3\n\n for hex_row in self.hexes:\n for hex in hex_row:\n if hex is not None:\n hex.place(self.center, self.hex_size)\n for v_row in self.vertices:\n for v in v_row:\n if v is not None:\n v.place(self.center, self.hex_size)\n def replace(self, win, center, hex_size):\n self.undraw()\n self.place(center, hex_size)\n self.draw(win)\n\n def draw(self, win):\n for hex_row in self.hexes:\n for hex in hex_row:\n if hex is not None:\n # hex.setColor(\"light gray\")\n hex.draw(win)\n for v_row in self.vertices:\n for v in v_row:\n if v is not None:\n v.draw(win)\n def undraw(self):\n for hex_row in self.hexes:\n for hex in hex_row:\n if hex is not None:\n # hex.setColor(\"light gray\")\n hex.undraw()\n for v_row in self.vertices:\n for v in v_row:\n if v is not None:\n v.undraw()\n\n def get_hex_click(self, click):\n for h_row in self.hexes:\n for h in h_row:\n if h is not None and h.is_click_in(click):\n h.setColor(\"red\")\n time.sleep(.35)\n h.setColor(\"black\")\n # where = pixel_to_hex(self.center, self.hex_size, click.getX(), click.getY())\n # print('(',where.x, ', ', where.y, ')', sep=\"\", end=\" \") # DEBUG\n # print('(',click.x, ', ', click.y, ')', sep=\"\") # DEBUG\n # if self.hexes[where.x][where.y] is not None:\n # self.hexes[where.x][where.y].setColor(\"red\")\n # time.sleep(.35)\n # self.hexes[where.x][where.y].setColor()#\"light gray\")\n def get_vertex_click(self, click):\n for v_row in self.vertices:\n for v in v_row:\n if v is not None and v.is_click_in(click):\n v.setColor(\"red\")\n time.sleep(.35)\n v.setColor()\n # where = pixel_to_vertex(self.center, self.hex_size, click.getX(), click.getY())\n # print('(',where.x, ', ', where.y, ')', sep=\"\", end=\" \") # DEBUG\n # print('(',click.x, ', ', click.y, ')', sep=\"\") # DEBUG\n # if self.vertices[where.x][where.y] is not None:\n # self.vertices[where.x][where.y].setColor(\"red\")\n # time.sleep(.35)\n # self.vertices[where.x][where.y].setColor()#\"light gray\")\n\n def __str__(self):\n prt = \"\"\n for r in self.hexes:\n for q in r:\n if q is not None:\n prt += q.__str__() + \" \"\n else:\n prt += \" .. \"\n prt += '\\n'\n prt += '\\n\\n'\n for r in self.vertices:\n for q in r:\n if q is not None:\n prt += q.__str__() + \" \"\n else:\n prt += \" .. \"\n prt += '\\n'\n return prt\n\n\nclass Hex:\n def __init__(self, hx_coord, resource=None):\n self.resource = resource\n self.hx_coord = hx_coord\n self.text = str(hx_coord.x) + \", \" + str(hx_coord.y)\n self.center = None\n\n def __str__(self):\n return \"({:2},{:2})\".format(self.hx_coord.x, self.hx_coord.y)\n\n def place(self, grid_center, size, color=\"black\"):\n self.size = size\n self.size_short = size * math.sqrt(3) / 2\n\n self.center = hex_to_pixel(grid_center, size, self.hx_coord.x, self.hx_coord.y)\n self.poly = Polygon(jump_linear(self.center, 0, size),\n jump_linear(self.center, 60, size),\n jump_linear(self.center, 120, size),\n jump_linear(self.center, 180, size),\n jump_linear(self.center, 240, size),\n jump_linear(self.center, 300, size))\n self.cir = Circle(self.center, self.size_short)\n self.cir_big = Circle(self.center, self.size)\n self.txt = Text(self.center, self.text)\n self.txt.setSize(max(size//5, 5))\n\n def draw(self, win):\n if self.center is not None:\n self.poly.draw(win)\n self.cir.draw(win)\n self.txt.draw(win)\n # self.cir_big.draw(win)\n def undraw(self):\n if self.center is not None:\n self.poly.undraw()\n self.cir.undraw()\n self.txt.undraw()\n # self.cir_big.draw(win)\n\n def is_click_in(self, point):\n x, y = point.getX(), point.getY()\n cx, cy = self.center.getX(), self.center.getY()\n # if radius < distance\n if self.size_short**2 > (cx-x)**2 + (cy-y)**2:\n return True\n return False\n\n def setColor(self, color=\"black\"):\n if self.center is not None:\n self.cir.setOutline(color)\n self.poly.setOutline(color)\n self.txt.setTextColor(color)\n def setText(self, text):\n self.text = text\n self.txt.setText(text)\n\n\nclass Vertex:\n def __init__(self, vx_coord):\n self.vx_coord = vx_coord\n self.text = str(vx_coord.x) + \", \" + str(vx_coord.y)\n\n def __str__(self):\n return \"({:2},{:2})\".format(self.vx_coord.x, self.vx_coord.y)\n\n def place(self, grid_center, size):\n self.size = size\n self.size_short = size * math.sqrt(3) / 2\n self.vertex_size = size//4\n self.vertex_size_short = self.vertex_size * math.sqrt(3) / 2\n\n self.center = vertex_to_pixel(grid_center, self.size_short*2//3, self.vx_coord.x, self.vx_coord.y)\n # self.center = vertex_to_pixel(grid_center, self.size_short, self.vx_coord.x, self.vx_coord.y)\n self.poly = Polygon(jump_linear(self.center, 30, self.vertex_size),\n jump_linear(self.center, 90, self.vertex_size),\n jump_linear(self.center, 150, self.vertex_size),\n jump_linear(self.center, 210, self.vertex_size),\n jump_linear(self.center, 270, self.vertex_size),\n jump_linear(self.center, 330, self.vertex_size))\n self.cir_center = Circle(self.center, 3)\n self.cir = Circle(self.center, self.vertex_size_short)\n self.cir_big = Circle(self.center, self.size)\n self.txt = Text(self.center, self.text)\n self.txt.setSize(int(max(min(self.vertex_size//2, 32), 5)))\n \n def draw(self, win):\n # self.poly.draw(win)\n self.cir.draw(win)\n # self.txt.draw(win)\n self.cir_center.draw(win)\n # self.cir_big.draw(win)\n def undraw(self, ):\n # self.poly.undraw()\n self.cir.undraw()\n # self.txt.undraw()\n self.cir_center.undraw()\n # self.cir_big.undraw()\n\n def is_click_in(self, point):\n x, y = point.getX(), point.getY()\n cx, cy = self.center.getX(), self.center.getY()\n # if radius < distance\n if self.vertex_size_short**2 > (cx-x)**2 + (cy-y)**2:\n return True\n return False\n def setColor(self, color=\"black\"):\n self.cir.setOutline(color)\n self.poly.setOutline(color)\n def setText(self, text):\n self.text = text\n self.txt.setText(text)\n\n\n\ndef in_shape(cir, point):\n x, y = point.getX(), point.getY()\n cx, cy = cir.getCenter().getX(), cir.getCenter().getY()\n # if radius < distance\n if cir.getRadius()**2 > (cx-x)**2 + (cy-y)**2:\n return True\n return False\n\ndef jump_linear(point, angle, distance):\n # Calculates cartesian coordinates of destination,\n # given origin, angle to travel, and distance to travel\n x, y = point.getX(), point.getY()\n x += distance * math.cos(math.radians(angle))\n y -= distance * math.sin(math.radians(angle))\n return Point(x, y)\n\ndef jump_hex(point, size, r, q):\n # Calculates cartesian coordinates of destination,\n # given cartesian origin coordinates and a hexagonal travel vector\n x, y = point.getX(), point.getY()\n qr_x = r * size * 3 / 2\n qr_y = size * math.sqrt(3) * (q + r / 2)\n return Point(x + qr_x, y + qr_y)\n\n\ndef pixel_to_hex(center, size, x, y):\n # calculates axial coordinates, given x,y coordinates and coordinates\n # of the central hex\n cx, cy = center.getX(), center.getY()\n q = (x-cx) * 2/3 / size\n r = (-(x-cx) / 3 + math.sqrt(3)/3 * (y-cy)) / size\n q = math.floor(q+.5) if q > 0 else math.ceil(q-.5)\n r = math.floor(r+.5) if r > 0 else math.ceil(r-.5)\n return Point(q, r)\n\ndef pixel_to_vertex(center, size, x, y):\n # calculates axial coordinates, given x,y coordinates and coordinates\n # of the central hex\n cx, cy = center.getX(), center.getY()\n q = ((x-cx) * math.sqrt(3)/3 - (y-cy) / 3) / size\n r = (y-cy) * 2/3 / size\n q = math.floor(q+.5) if q > 0 else math.ceil(q-.5)\n r = math.floor(r+.5) if r > 0 else math.ceil(r-.5)\n return Point(q, r)\n\ndef hex_to_pixel(center, size, q, r):\n x = size * 3/2 * q\n y = size * math.sqrt(3) * (r + q/2)\n return Point(x + center.x, y + center.y)\n\ndef vertex_to_pixel(center, size, q, r):\n x = size * math.sqrt(3) * (q + r/2)\n y = size * 3/2 * r\n return Point(x + center.x, y + center.y)\n\n\n\nmain()","sub_path":"Python/CatanApr14.py","file_name":"CatanApr14.py","file_ext":"py","file_size_in_byte":11758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"54000396","text":"import random\n\n# 1. Создать функцию которая генерирует 10 чисел от 0 до 10 и выводит их.\ndef test():\n for i in range(0, 10):\n n = random.randint(1, 10)\n print(str(i + 1) + \". n = \" + str(n))\n\n# 2. Создать функцию которая принимает 3 параметра и выводит максимальное из них.\ndef test2(a, b, c):\n if a > b and a > c:\n return a\n elif b > a and b > c:\n return b\n elif c > a and c > b:\n return c\n\n#test()\n\n'''\nprint(test2(4, 40, 30))\nprint(test2(4, 30, 60))\nprint(test2(70, 15, 40))\n'''\n\n_ = 2\n__ = 3\n___=4\nmy_age = 150\n\n#vars with correct names\n\nmy_name = 1\n_ = 3\n\n#vars with incorrect names\n'''\n- = 2\n. = 3 \n^!%^ = 2\n*^_=3\n'''\n#print(_+__+___+my_age) # 2+3+4 = 9\n\n\n'''\naaa = 2+\n. = 3 -\na2a = 3 +\na22 = 5 +\n2a2 = 3 -\n_a = 5 +\na_ = 6 +\na 2 = 7 -\na-a = 8 -\n'''\n\nage = 8\naGe = 10\nAGE = 12\nAge = 13\nagE = 14\nAgE = 15\nAGe = 16\naGE = 17\nprint (age+aGe+AGE)\n\nx, y, z, w= \"Orange\", \"Banana\", \"Cherry\", \"Apple\"\nprint(x)\nprint(y)\nprint(z)\nprint(w)\n\n","sub_path":"june/11.06.py","file_name":"11.06.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"651169744","text":"import load\n \npath = r\"Z:\\Favorites\\SCL17 (Small Business Energy Solutions)\\6 Data Exchange\\SCL\\Data Examples\"\nfilename = r'\\SCL Customer List_250kW SMB.xlsx'\nfilepath = path + filename\n# sfitem = open(filepath)\n\nconnsettings = {\n 'host': 'localhost',\n 'port': 5432,\n 'user': 'postgres',\n 'password': 'RangeBreak99.',\n 'db': 'scl_eda',\n } \n\nreturn_value = load.SQL_load_to_postgre(\n file_obj=filepath,\n sheet_name='Unique',\n header_row=1,\n field_type_row=-1,\n field_names={},\n field_types={},\n primary_key_fields=[''],\n join_fields=[],\n index_fields=[''], \n date_fields=[],\n null_values={},\n table_name = 'scl_eda.accounts', \n conn_settings = connsettings, \n table_action=load.load_type.OVERWRITE)\n\nprint(return_value)\n","sub_path":"code/analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"639973182","text":"import xml.etree.ElementTree as ET\r\n\r\ntree = ET.parse('Africa.xml')\r\n\r\ndata_dict = {}\r\n\r\ndef count_words(the_list):\r\n for word in the_list:\r\n if len(word) > 6:\r\n if word not in data_dict.keys():\r\n data_dict[word] = 1\r\n else:\r\n data_dict[word] += 1\r\n\r\ndef count_top_10(the_dict):\r\n keys_list = []\r\n values_list = sorted(the_dict.values())[-1:-11:-1]\r\n for value in values_list:\r\n for key, val in the_dict.items():\r\n if val == value:\r\n keys_list.append(key)\r\n the_dict[key] = 0\r\n if len(keys_list) == 10:\r\n break\r\n print('TОП 10:\\n')\r\n for i in range(10):\r\n print(f'\\\"{keys_list[i]}\\\" - {values_list[i]} раз')\r\n\r\nthe_news = tree.findall('channel/item/description')\r\n\r\nfor new in the_news:\r\n new_string = new.text\r\n words_list = new_string.lower().split()\r\n count_words(words_list)\r\n\r\ncount_top_10(data_dict)\r\n","sub_path":"file_2.py","file_name":"file_2.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"305570903","text":"from __future__ import absolute_import, unicode_literals\nimport logging\nfrom celery.task import task\nfrom .builder import direct\n\n\n@task(name=\"DailyGooseBuilder\")\ndef build_goose(delta):\n db_logger = logging.getLogger('aprp')\n\n logger_extra = {\n 'type_code': 'LOT-gooses',\n }\n try:\n result = direct(delta=delta)\n if result.success:\n logger_extra['duration'] = result.duration\n db_logger.info('Successfully process trans: %s - %s' % (result.start_date, result.end_date), extra=logger_extra)\n except Exception as e:\n db_logger.exception(e, extra=logger_extra)\n","sub_path":"src/apps/gooses/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"553914299","text":"from collections import *\n\n\ndef unikati(s):\n s2 = []\n for e in s:\n if e not in s2:\n s2.append(e)\n return(s2)\n\n\ndef avtor(tvit):\n ts = tvit.split(\":\")\n return ts[0]\n\n\ndef vsi_avtorji(tviti):\n s = []\n for t in tviti:\n a = avtor(t)\n s.append(a)\n return unikati(s)\n\n\ndef izloci_besedo(beseda):\n bes = beseda\n a = bes.isalnum()\n while not a:\n b = bes[0].isalnum()\n c = bes[-1].isalnum()\n if not b:\n bes = bes[1:]\n if not c:\n bes = bes[:-1]\n if b and c:\n break\n return bes\n\n\n\ndef se_zacne_z(tvit, c):\n t = tvit.split()\n s = []\n for e in t:\n if e[0] == c:\n e = izloci_besedo(e)\n s.append(e)\n return s\n\n# Napišite funkcijo zberi_se_zacne_z(tviti, c), ki je podobna prejšnji, vendar prejme seznam tvitov in\n# vrne vse besede, ki se pojavijo v njih in se začnejo s podano črko. Poleg tega naj se vsaka beseda\n# pojavi le enkrat. Če pokličemo zberi_se_zacne_z(tviti, \"@\") (kjer so tviti gornji tviti), vrne\n# ['sandra', 'berta', 'cilka', 'dani', 'benjamin', 'ana']. Vrstni red besed v seznamu je enak vrstnemu\n# redu njihovih pojavitev v tvitih.\n\ndef zberi_se_zacne_z(tviti, c):\n s = []\n for tvit in tviti:\n a = se_zacne_z(tvit, c)\n if a != []:\n s.extend(a)\n return unikati(s)\n\n# Napišite funkcijo vse_afne(tviti), ki vrne vse besede v tvitih, ki se začnejo z @.\n# Če ji podamo gornje tvite, mora vrniti ['sandra', 'berta', 'cilka', 'dani', 'benjamin', 'ana'].\n\ndef vse_afne(tviti):\n return zberi_se_zacne_z(tviti, \"@\")\n\n#Napišite funkcijo vsi_hashtagi(tviti). Za gornje tvite vrne\n#['dougcajt', 'programiranje1', 'krneki', 'luft', 'zalosten', 'split'].\n\ndef vsi_hashtagi(tviti):\n return zberi_se_zacne_z(tviti, \"#\")\n\n#Napišite funkcijo vse_osebe(tviti), ki vrne po abecedi urejen seznam vseh oseb,\n# ki nastopajo v tvitih - bodisi kot avtorji, bodisi so omenjene v tvitih.\n# Vsaka oseba naj se pojavi le enkrat. Za gornje tvite funkcija vrne\n# ['ana', 'benjamin', 'berta', 'cilka', 'dani', 'ema', 'sandra'].\n\ndef vse_osebe(tviti):\n a = vsi_avtorji(tviti)\n b = vse_afne(tviti)\n b.extend(a)\n b.sort()\n return unikati(b)\n\n # Obvezne naloge\n\n#Funkcija besedilo(tvit) prejme tvit in vrne besedilo - torej vse, kar sledi prvemu dvopičju.\n # Klic besedilo(\"ana: kdo so te: @berta, @cilka, @dani?\") vrne \"kdo so te: @berta, @cilka, @dani?.\n\ndef besedilo(tvit):\n tvit = tvit.split(\": \", 1)\n a = tvit[0]\n b = tvit[1]\n return b\n\n\n#Funkcija zadnji_tvit(tviti) prejme seznam tvitov in vrne slovar, katerega ključi so avtorji tvitov,\n # vrednosti pa njihovi tviti. Če je en in isti avtor napisal več tvitov, naj bo v slovarju njegov\n # zadnji tvit. Rezultat je lahko, recimo\n\n#{\"berta\": \"@sandra Delaj domačo za #programiranje1\",\n# \"sandra\": \"@berta Ne maram #programiranje1 #krneki\",\n# \"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\"}\n#če so to edini trije avtorji in so to njihovi (zadnji) tviti.\n\ndef zadnji_tvit(tviti):\n s = {}\n for tvit in tviti:\n a = avtor(tvit)\n b = besedilo(tvit)\n s[a] = b\n return s\n\n#Funkcija prvi_tvit(tviti) je jako podobna, le da v primeru, da je ista oseba napisala več tvitov,\n# obdrži njen prvi tvit.\n\ndef prvi_tvit(tviti):\n s = {}\n for tvit in tviti:\n a = avtor(tvit)\n b = besedilo(tvit)\n if a not in s:\n s[a] = b\n return s\n\n#Funkcija prestej_tvite(tviti) vrne slovar, katerega ključi so (spet) avtorji, pripadajoče vrednosti\n # pa število tvitov, ki so jih napisali, na primer {\"sandra\": 2, \"berta\": 1, \"ana\": 1, \"cilka\": 4, \"benjamin\": 1}\n\ndef prestej_tvite(tviti):\n s = defaultdict(int)\n for tvit in tviti:\n a = avtor(tvit)\n b = besedilo(tvit)\n s[a] += 1\n return s\n\n\n#Funkcija omembe(tviti) vrne slovar, katerega ključi so avtorji tvitov, vrednosti pa seznami oseb,\n # ki so jih ti avtorji omenjali v svojih tvitih. Vrstni red oseb mora biti enak vrstnemu redu omenjanj.\n # Funkcija lahko vrne, recimo\n#{\"sandra\": [\"berta\", \"benjamin\", \"ana\"],\n#\"benjamin\": [],\n#\"cilka\": [],\n#\"berta\": [\"sandra\"],\n#\"ana\": [\"berta\", \"cilka\", \"dani\"]}\ndef omembe(tviti):\n s = defaultdict(list)\n for tvit in tviti:\n a = avtor(tvit)\n b = se_zacne_z(tvit, \"@\")\n if b != []:\n s[a] += b\n else: s[a] += []\n return s\n\n\n\n#Funkcija neomembe(ime, omembe) prejme ime neke osebe in takšen slovar, kakršnega vrne gornja funkcija.\n# Vrniti mora seznam vseh ljudi, ki so avtorji kakega tvita, podana oseba (ime) pa jih ni omenjala.\n# Če funkciji kot argument podamo ime \"Ana\" in gornji slovar, mora vrniti [\"sandra\", \"benjamin],\n# saj Ana ni omenjala Sandre in Benjamina, Cilko in Berto pa je. Iz seznama naj bo seveda izključena\n# oseba sama (v tem primeru Ana). Vrstni red oseb v seznamu je lahko poljuben.\n\ndef neomembe(ime, omembe):\n avtorji = omembe.keys() #vsi avtorji\n s = []\n for avtor, om in omembe.items():\n if avtor == ime:\n for a in avtorji:\n if a != ime and a not in om:\n s.append(a)\n return s\n\n\n\n\n#Dodatna naloga\n\n#Napišite funkcijo se_poznata(ime1, ime2, omembe), ki je podobna kot v prejšnji domači nalogi,\n# le da kot argument namesto tvitov dobi gornji slovar. Povedati mora, ali je prva oseba kdaj\n# omenila drugo (ali obratno) ali ne. Funkcija vrne True ali False.\n\ndef se_poznata(ime1, ime2, omembe):\n s1 = []\n s2 = []\n for av, om in omembe.items():\n if av == ime1:\n s1 = om\n if av == ime2:\n s2 = om\n if ime1 in s2 or ime2 in s1:\n return True\n else: return False\n\n #custva(tviti, hashtagi), ki prejme seznam tvitov in seznam hashtagov (brez začetnega #).\n # Vrne naj vse avtorje, ki so uporabili vsaj enega od naštetih tagov. Avtorji naj bodo\n # urejeni po abecedi in vsak naj se pojavi le enkrat. Klic custva(tviti, [\"dougcajt\",\n # \"krneki\"]) vrne [\"ana\", \"sandra\"].\n\n#def custva(tviti, hashtagi):\n # avtorji = []\n # for tvit in tviti:\n # if neprazen_presek(se_zacne_z(tvit, \"#\"), hashtagi):\n # avtorji.append(avtor(tvit))\n # avtorji.sort()\n # return unikati(avtorji)\n\n\ndef custva(tviti, hashtagi):\n return unikati(sorted(avtor(tvit) for tvit in tviti if set(hashtagi) & set(se_zacne_z(tvit, \"#\"))))\n\n\n#Napišite funkcijo hashtagi(tviti), ki prejme seznam tvitov in vrne slovar, katerega ključi so\n# hashtagi (brez znaka #), pripadajoče vrednosti pa seznami avtorjev, ki so uporabili ta hashtagi.\n# Avtorji naj bodo urejeni po abecedi.\n\ndef hashtagi(tviti):\n s = {}\n for h in vsi_hashtagi(tviti):\n s[h] = custva(tviti, [h])\n return s\n\n\n\n\n\n\n\n\n\n\n\n\n\nimport unittest\n\nclass TestObvezna(unittest.TestCase):\n maxDiff = 10000\n\n def test_1_besedilo(self):\n self.assertEqual(besedilo(\"sandra: Spet ta dež. #dougcajt\"),\n \"Spet ta dež. #dougcajt\")\n self.assertEqual(besedilo(\"ana: kdo so te: @berta, @cilka, @dani? #krneki\"),\n \"kdo so te: @berta, @cilka, @dani? #krneki\")\n\n def test_2_zadnji_tvit(self):\n self.assertDictEqual(\n zadnji_tvit([\n \"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"cilka: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"berta\": \"@sandra Delaj domačo za #programiranje1\",\n \"sandra\": \"@berta Ne maram #programiranje1 #krneki\",\n \"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\",\n \"benjamin\": \"pogrešam ano #zalosten\",\n \"cilka\": \"@benjamin @ana #split? po dvopičju, za začetek?\"})\n\n self.assertDictEqual(\n zadnji_tvit([\n \"sandra: Spet ta dež. #dougcajt\",\n \"sandra: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"sandra: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"sandra: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\",\n \"benjamin\": \"pogrešam ano #zalosten\",\n \"sandra\": \"@benjamin @ana #split? po dvopičju, za začetek?\"})\n\n self.assertDictEqual(\n zadnji_tvit([\"ana: kdo so te: @berta, @cilka, @dani? #krneki\"]),\n {\"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\"})\n\n self.assertEqual(zadnji_tvit([]), {})\n\n\n def test_3_prvi_tvit(self):\n self.assertDictEqual(\n prvi_tvit([\n \"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"cilka: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": \"Spet ta dež. #dougcajt\",\n \"berta\": \"@sandra Delaj domačo za #programiranje1\",\n \"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka\": \"jst sm pa #luft\",\n \"benjamin\": \"pogrešam ano #zalosten\"})\n\n self.assertDictEqual(\n prvi_tvit([\n \"sandra: Spet ta dež. #dougcajt\",\n \"sandra: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"sandra: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"sandra: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": \"Spet ta dež. #dougcajt\",\n \"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\",\n \"benjamin\": \"pogrešam ano #zalosten\"})\n\n self.assertDictEqual(\n prvi_tvit([\"ana: kdo so te: @berta, @cilka, @dani? #krneki\"]),\n {\"ana\": \"kdo so te: @berta, @cilka, @dani? #krneki\"})\n\n self.assertEqual(prvi_tvit([]), {})\n\n def test_4_prestej_tvite(self):\n self.assertDictEqual(\n prestej_tvite([\n \"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"cilka: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": 2, \"berta\": 1, \"ana\": 1, \"cilka\": 2, \"benjamin\": 1})\n\n self.assertDictEqual(\n prestej_tvite([\n \"sandra: Spet ta dež. #dougcajt\",\n \"sandra: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"sandra: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"sandra: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": 5, \"ana\": 1, \"benjamin\": 1})\n\n self.assertDictEqual(\n prestej_tvite([\"ana: kdo so te: @berta, @cilka, @dani? #krneki\"]),\n {\"ana\": 1})\n\n self.assertEqual(prestej_tvite([]), {})\n\n def test_5_omembe(self):\n self.assertDictEqual(\n omembe([\"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te: @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"sandra: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {\"sandra\": [\"berta\", \"benjamin\", \"ana\"],\n \"benjamin\": [],\n \"cilka\": [],\n \"berta\": [\"sandra\"],\n \"ana\": [\"berta\", \"cilka\", \"dani\"]}\n )\n\n def test_6_neomembe(self):\n omembe = {\"sandra\": [\"berta\", \"benjamin\", \"ana\"],\n \"benjamin\": [],\n \"cilka\": [],\n \"berta\": [\"sandra\"],\n \"ana\": [\"berta\", \"cilka\", \"dani\", \"benjamin\", \"sandra\"]}\n\n self.assertEqual(neomembe(\"sandra\", omembe), [\"cilka\"])\n self.assertEqual(neomembe(\"ana\", omembe), [])\n self.assertEqual(set(neomembe(\"benjamin\", omembe)), set(omembe) - {\"benjamin\"})\n\nclass TestDodatna(unittest.TestCase):\n def test_1_se_poznata(self):\n omembe = {\"sandra\": [\"berta\", \"benjamin\", \"ana\"],\n \"benjamin\": [],\n \"cilka\": [],\n \"berta\": [\"sandra\"],\n \"ana\": [\"berta\", \"cilka\", \"dani\"]}\n\n self.assertTrue(se_poznata(\"ana\", \"berta\", omembe))\n self.assertTrue(se_poznata(\"berta\", \"ana\", omembe))\n self.assertTrue(se_poznata(\"sandra\", \"benjamin\", omembe))\n self.assertTrue(se_poznata(\"benjamin\", \"sandra\", omembe))\n\n self.assertFalse(se_poznata(\"benjamin\", \"ana\", omembe))\n self.assertFalse(se_poznata(\"ana\", \"benjamin\", omembe))\n\n self.assertFalse(se_poznata(\"cilka\", \"dani\", omembe))\n self.assertFalse(se_poznata(\"pavel\", \"peter\", omembe))\n\n def test_2_hashtagi(self):\n self.assertDictEqual(\n hashtagi([\"sandra: Spet ta dež. #dougcajt\",\n \"berta: @sandra Delaj domačo za #programiranje1\",\n \"sandra: @berta Ne maram #programiranje1 #krneki\",\n \"ana: kdo so te @berta, @cilka, @dani? #krneki\",\n \"cilka: jst sm pa #luft\",\n \"benjamin: pogrešam ano #zalosten\",\n \"ema: @benjamin @ana #split? po dvopičju, za začetek?\"]),\n {'dougcajt': ['sandra'],\n 'krneki': ['ana', 'sandra'],\n 'luft': ['cilka'],\n 'programiranje1': ['berta', 'sandra'],\n 'split': ['ema'],\n 'zalosten': ['benjamin']})\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n\n","sub_path":"code/batch-2/dn6 - spet tviti/M-17187-2630.py","file_name":"M-17187-2630.py","file_ext":"py","file_size_in_byte":14670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"268616801","text":"from uuid import uuid4\nfrom django.db import models\nfrom application.models import Application, AdultInHome\nfrom datetime import date\n\n\nclass AdultInHomeAddress(models.Model):\n \"\"\"\n Model for ADULT_IN_HOME_ADDRESS table\n \"\"\"\n\n adult_in_home_address_id = models.UUIDField(primary_key=True,\n default=uuid4)\n adult_id = models.OneToOneField(AdultInHome,\n on_delete=models.CASCADE,\n db_column=\"adult_id\")\n application_id = models.ForeignKey(\n Application, on_delete=models.CASCADE, db_column=\"application_id\"\n )\n adult_in_home_address = models.IntegerField(blank=True, null=True)\n street_line1 = models.CharField(max_length=100, blank=True)\n street_line2 = models.CharField(max_length=100, blank=True)\n town = models.CharField(max_length=100, blank=True)\n county = models.CharField(max_length=100, blank=True)\n country = models.CharField(max_length=100, blank=True)\n postcode = models.CharField(max_length=8, blank=True)\n\n moved_in_day = models.IntegerField(blank=True, null=True)\n moved_in_month = models.IntegerField(blank=True, null=True)\n moved_in_year = models.IntegerField(blank=True, null=True)\n\n @property\n def timelog_fields(self):\n \"\"\"\n Specify which fields to track in this model once application is returned.\n\n Used for signals only. Check base.py for available signals.\n This is used for logging fields which gonna be updated by applicant\n once application status changed to \"FURTHER_INFORMATION\" on the arc side\n\n Returns:\n tuple of fields which needs update tracking when application is returned\n \"\"\"\n\n return (\n \"adult_in_home_address\",\n \"street_line1\",\n \"street_line2\",\n \"town\",\n \"county\",\n \"country\",\n \"postcode\",\n \"moved_in_day\",\n \"moved_in_month\",\n \"moved_in_year\",\n )\n\n class Meta:\n db_table = \"ADULT_IN_HOME_ADDRESS\"\n\n def get_moved_in_date(self):\n if not all((self.moved_in_year, self.moved_in_month, self.moved_in_day)):\n return None\n return date(self.moved_in_year, self.moved_in_month, self.moved_in_day)\n\n def set_moved_in_date(self, moved_in_date):\n self.moved_in_year = moved_in_date.year\n self.moved_in_month = moved_in_date.month\n self.moved_in_day = moved_in_date.day\n\n @classmethod\n def get_id(cls, app_id):\n adult_id = AdultInHome.get_id(app_id)\n return cls.objects.get(adult_id=adult_id)\n\n def get_full_adress(self):\n return [\n self.street_line1,\n self.street_line2,\n self.town,\n self.county,\n self.country,\n self.postcode,\n ]\n","sub_path":"application/models/adult_in_home_address.py","file_name":"adult_in_home_address.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"577002759","text":"from typing import *\nimport logging\n\ntry:\n import coloredlogs\nexcept ImportError:\n coloredlogs = None\n\nl: logging.Logger = logging.getLogger(__name__)\n\n\ndef init_logging(logging_cfg: Dict[str, Any]):\n loggers_cfg = logging_cfg[\"Loggers\"]\n for logger_name in loggers_cfg:\n if logger_name == \"root\":\n log: logging.Logger = logging.root\n else:\n log: logging.Logger = logging.getLogger(logger_name)\n log.setLevel(loggers_cfg[logger_name])\n\n stream_handler = logging.StreamHandler()\n if coloredlogs is not None:\n stream_handler.formatter = coloredlogs.ColoredFormatter(logging_cfg[\"log_format\"], style=\"{\")\n else:\n stream_handler.formatter = logging.Formatter(logging_cfg[\"log_format\"], style=\"{\")\n if len(logging.root.handlers) < 1:\n logging.root.addHandler(stream_handler)\n\n l.debug(\"Logging: ready\")\n","sub_path":"royalnet/utils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"559568176","text":"import tensorflow as tf\nimport numpy as np\nclass SegmentionModel:\n def __init__(self):\n self.sess = None\n self.graph = None\n self.input = None\n self.output = None\n self.saver=None\n self.class_num=None\n self.var_file=None\n self.graph_file=None\n\n def predict(self, input_data):\n test_data = input_data.reshape(self.input_shape)\n batch_size=test_data.shape[0]\n out_shape=[batch_size]\n out_shape+=self.output_shape[1:]\n tmp_output=np.zeros(shape=out_shape)\n op_input=self.input\n op_output=self.output\n result=self.sess.run(op_output,feed_dict={op_input:test_data})\n output=result\n return output\n \n def init_model(self,input_op_name=None,output_op_name=None):\n if input_op_name is None:\n input_op_name='Input/x:0'\n if output_op_name is None:\n output_op_name='Output/Reshape:0'\n\n keys=self.graph.get_operations()\n op_names=list(map(lambda k: k.name, keys))\n\n\n self.input=[]\n op_name,op_index=input_op_name.split(':')\n if op_name in op_names:\n self.input=self.graph.get_operation_by_name(op_name).outputs[int(op_index)]\n else:\n raise IndexError('In model:%s No Op named as input_op_name:%s'%(m_dir,input_op_name))\n self.output=None\n op_name,op_index=output_op_name.split(':')\n if op_name in op_names:\n self.output=self.graph.get_operation_by_name(op_name).outputs[int(op_index)]\n else:\n raise IndexError('In model:%s No Op named as output_op_name:%s'%(m_dir,output_op_name))\n #初始化输入输出参数\n self.input_shape=[-1]\n self.output_shape=[-1]\n self.input_shape+=self.input.shape[1:].as_list()\n self.output_shape+=self.output.shape[1:].as_list()\n\n\n def load_from_files(self,meta_file,var_file):\n self.var_file=var_file\n self.meta_file=meta_file\n self.graph=tf.Graph()\n with self.graph.as_default():\n self.saver=tf.train.import_meta_graph(meta_file)\n\n self.sess=tf.Session(graph=self.graph)\n with self.sess.as_default() as s_d:\n with self.graph.as_default() as g_d:\n self.saver.restore(s_d,var_file)\n\n def load_from_checkpoint_dir(self,checkpoint_dir):\n ckpoint=tf.train.latest_checkpoint(checkpoint_dir)\n var_file=ckpoint\n meta_file=ckpoint+'.meta'\n self.load_from_files(meta_file,var_file)\n\n\n def __del__(self):\n if self.sess:\n self.sess.close()\n self.sess=None\n\nclass ClassifyModel:\n def __init__(self,args):\n if args.model_type!='model_detection.classify_model':\n return\n\n self.sesses = {}\n self.graphs = {}\n self.inputs = {}\n self.outputs = {}\n self.savers={}\n self.class_num=args.class_num\n self.xgb_model_file=args.xgb_model_file\n self.xgb_model=ic.integrated_classifier(self.xgb_model_file)\n\n for i in range(len(args.model_dirs)):\n m_dir=args.model_dirs\n g=tf.Graph()\n meta_file=m_dir+'.meta'\n var_file=m_dir\n if args.input_op_names:\n input_op_name=args.input_op_names\n else:\n input_op_name='Input/x'\n if args.output_op_names:\n output_op_name=args.output_op_names\n else:\n output_op_name='Output/Reshape'\n \n with g.as_default():\n self.savers=tf.train.import_meta_graph(meta_file)\n\n self.sesses=tf.Session(graph=g)\n with self.sesses.as_default() as s_d:\n with g.as_default() as g_d:\n self.savers.restore(s_d,var_file)\n self.graphs=g_d\n\n keys=self.graphs.get_operations()\n op_names=list(map(lambda k: k.name, keys))\n if input_op_name in op_names:\n self.inputs=self.graphs.get_operation_by_name(input_op_name).outputs[0]\n else:\n raise IndexError('In model:%s No Op named as input_op_name:%s'%(m_dir,input_op_name))\n if output_op_name in op_names:\n self.outputs=self.graphs.get_operation_by_name(output_op_name).outputs[0]\n # self.graphs.get_operation_by_name('Output/Layer_Dense/MatMul').inputs[0]\n # print(self.outputs)\n else:\n raise IndexError('In model:%s No Op named as output_op_name:%s'%(m_dir,output_op_name))\n #初始化输入输出参数\n self.input_shape=0\n self.output_shape=0\n for key in self.inputs:\n self.input_shape+=self.inputs.shape[-1].value\n self.output_shape+=self.outputs.shape[-1].value\n\n\n def classify(self, input_data):\n '''\n 作用:\n 输入patches数据,输入训练好的网络模型获得patches分类后的标签\n 参数:\n input_data: 输入的patches数据\n '''\n test_data = input_data.reshape([-1, 32, 32, self.input_shape]).astype(np.float32)\n input_index=0\n output_index=0\n tmp_output=np.zeros(shape=[test_data.shape[0],self.output_shape])\n for key in self.inputs:\n op_input=self.inputs\n op_output=self.outputs\n tmp_input=test_data[:,:,:,input_index:input_index+op_input.shape[-1].value]\n input_index+=op_input.shape[-1].value\n result=self.sesses.run(op_output,feed_dict={op_input:tmp_input})\n tmp_output[:,output_index:output_index+op_output.shape[-1].value]=result[0]\n output_index +=op_output.shape[-1].value\n \n # xgboost classify\n # print(tmp_output)\n f_result,f_probability =self.xgb_model.classifier(tmp_output)\n\n # print(f_result)\n return f_result,f_probability\n\n\n def __del__(self):\n if self.sesses:\n self.sesses.close()\n self.sesses=None\n","sub_path":"model/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"244264664","text":"#!/usr/bin/python\n\n\ndef outlierCleaner(predictions, ages, net_worths):\n \"\"\"\n Clean away the 10% of points that have the largest\n residual errors (difference between the prediction\n and the actual net worth).\n\n Return a list of tuples named cleaned_data where\n each tuple is of the form (age, net_worth, error).\n \"\"\"\n\n cleaned_data = []\n\n ### your code goes here\n clean_percent = 10\n total = len(net_worths)\n cleaned_total = int(total * (1 - 1./clean_percent))\n\n data_list = []\n errors_list = []\n for i in range(total):\n # Calculate error\n error = abs(net_worths[i] - predictions[i])\n # Create data\n age, net_worth = ages[i], net_worths[i]\n data_list.append( (age, net_worth, error) )\n # Create error list\n errors_list.append(error)\n\n sorted_data = [data for _,data in sorted(zip(errors_list, data_list))]\n cleaned_data = [sorted_data[i] for i in range(cleaned_total)]\n\n return cleaned_data\n","sub_path":"outliers/outlier_cleaner.py","file_name":"outlier_cleaner.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"320859162","text":"from ..base import MLClassifierBase\nimport numpy as np\nimport copy, random\nfrom scipy import sparse\n\nclass RandomOrderedClassifierChain(MLClassifierBase):\n \"\"\"Classifier Chains multi-label classifier.\"\"\"\n BRIEFNAME = \"CC\"\n \n def __init__(self, classifier = None):\n super(RandomOrderedClassifierChain, self).__init__(classifier)\n self.ordering = None\n\n def draw_ordering(self):\n self.ordering = random.sample(xrange(self.label_count), self.label_count)\n\n def fit(self, X, y):\n # fit L = len(y[0]) BR classifiers h_i\n # on X + y[:i] as input space and y[i+1] as output\n # \n self.predictions = y\n self.num_instances = y.shape[0]\n self.label_count = y.shape[1]\n self.classifiers = [None for x in xrange(self.label_count)]\n self.draw_ordering()\n\n for label in xrange(self.label_count):\n classifier = copy.deepcopy(self.classifier)\n y_tolearn = self.generate_data_subset(y, self.ordering[label], axis = 1)\n y_toinput = self.generate_data_subset(y, self.ordering[:label], axis = 1)\n\n X_extended = np.append(X, y_toinput, axis = 1)\n classifier.fit(X_extended, y_tolearn)\n self.classifiers[self.ordering[label]] = classifier\n\n return self\n\n def predict(self, X):\n result = np.zeros((X.shape[0], self.label_count), dtype='i8')\n for instance in xrange(X.shape[0]):\n predictions = []\n for label in self.ordering:\n prediction = self.classifiers[label].predict(np.append(X[instance], predictions))\n predictions.append(prediction)\n result[instance][label] = prediction\n return result\n\nclass EnsembleClassifierChains(MLClassifierBase):\n \"\"\"docstring for EnsembleClassifierChains\"\"\"\n def __init__(self, \n classifier = None, \n model_count = None, \n training_sample_percentage = None,\n threshold = None):\n super(EnsembleClassifierChains, self).__init__(classifier)\n self.model_count = model_count\n self.threshold = threshold\n self.percentage = training_sample_percentage\n self.models = None\n\n\n def generate_partition(self, X, y):\n self.partition = range(y.shape[1])\n self.model_count = y.shape[1]\n\n def fit(self, X, y):\n X = self.ensure_input_format(X, sparse_format = 'csr', enforce_sparse = True)\n y = self.ensure_output_format(y, sparse_format = 'csc', enforce_sparse = True)\n\n self.generate_partition(X, y)\n self.models = []\n self.label_count = y.shape[1]\n for model in xrange(self.model_count):\n classifier = copy.deepcopy(self.classifier)\n sampled_rows = self.generate_data_subset(X, self.partition[model], axis = 0)\n sampled_y = self.generate_data_subset(y, self.partition[model], axis = 0)\n classifier.fit(self.ensure_input_format(sampled_rows), self.ensure_output_format(sampled_y))\n self.models.append(classifier)\n return self\n\n def predict(self, X):\n results = np.zeros((X.shape[0], self.label_count), dtype='i8')\n for model in self.models:\n prediction = model.predict(X)\n for row in xrange(X.shape[0]):\n for label in xrange(self.label_count):\n results[model.ordering[label]] += prediction[row][label]\n\n sums = np.zeros(self.label_count, dtype='float')\n for row in results:\n sums += row\n\n for row in xrange(len(X)):\n for label in xrange(self.label_count):\n results[row][label] = int(results[row][label]/float(sums[label]) > self.threshold)\n\n return results\n ","sub_path":"skmultilearn/problem_transform/transformations.py","file_name":"transformations.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"124247875","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author: yu.yang1@yitu-inc.com\n\n# https://blog.csdn.net/u012328159/article/details/79240652\n# https://blog.csdn.net/Nyte2018/article/details/88835890\n\nimport matplotlib\n \nmatplotlib.use('TkAgg') #或者PDF, SVG或PS\n \nimport matplotlib.pyplot as plt\n\nimport json\nimport os\n\nimport sys\n\nplt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签\nplt.rcParams['axes.unicode_minus'] = False #用来正常显示负号\n\n#plt.figure(1) # 创建图表1\n#plt.figure(2) # 创建图表2\n#x1 = plt.subplot(211) # 在图表2中创建子图1\n#x2 = plt.subplot(212) # 在图表2中创建子图2\n\n# https://blog.csdn.net/qq_32867925/article/details/103270531?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&dist_request_id=&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control\n\nfile_name = sys.argv[1]\njpg_file = file_name.replace(\".json\", \".jpg\")\n\ndump_data = json.load(open(file_name))\nwith open(file_name, \"r\") as ouf:\n '''\n xt = [i for i in range(0, len(dump_data[\"ABC\"]['time']))]\n plt.subplot(122)\n #plt.figure(1) # 创建图表1\n if \"ABC\" in dump_data:\n time1 = dump_data[\"ABC\"]['time']\n #time1 = [x/10 for x in time1]\n plt.plot(xt,time1,'-',color = 'r',label=\"ABC\")\n if \"EABC\" in dump_data:\n time2 = dump_data[\"EABC\"]['time']\n #time2 = [x/10 for x in time1]\n plt.plot(xt,time2,'-',color = 'g',label=\"EABC\")\n if \"LSABC\" in dump_data:\n time3 = dump_data[\"LSABC\"]['time']\n #time3 = [x/10 for x in time1]\n plt.plot(xt,time3,'-.',color = 'y',label=\"LSABC\")\n if \"DEABC\" in dump_data:\n time4 = dump_data[\"DEABC\"]['time']\n #time4 = [x/10 for x in time1]\n plt.plot(xt,time4,':',color = 'b',label=\"DEABC\")\n if \"HSABC\" in dump_data:\n time5 = dump_data[\"HSABC\"]['time']\n #time5 = [x/10 for x in time1]\n plt.plot(xt,time5,':',color = 'k',label=\"HSABC\")\n if \"IEABC\" in dump_data:\n time6 = dump_data[\"IEABC\"]['time']\n #time6 = [x/10 for x in time1]\n plt.plot(xt,time6,'--',color = 'c',label=\"IEABC\")\n if \"SFLA\" in dump_data:\n time7 = dump_data[\"SFLA\"]['time']\n #time7 = [x/10 for x in time1]\n plt.plot(xt,time7,'--',color = 'm',label=\"SFLA\")\n plt.xlabel(u\"迭代次数\") #横坐标名字\n plt.ylabel(u\"累计时间(微妙)\") #纵坐标名字\n plt.legend(loc = \"best\") #图例\n '''\n\n xf = [i for i in range(0, len(dump_data[\"ABC\"]['fitness']))]\n plt.subplot(111)\n #plt.figure(2)# 创建图表1\n if \"ABC\" in dump_data:\n fitness1 = dump_data[\"ABC\"]['fitness']\n plt.plot(xf,fitness1,',',color = 'k',label=\"ABC\")\n\n if \"EABC\" in dump_data:\n fitness2 = dump_data[\"EABC\"]['fitness']\n plt.plot(xf,fitness2,'-.',color = 'g',label=\"EABC\")\n\n '''\n if \"IEABC\" in dump_data:\n fitness6 = dump_data[\"IEABC\"]['fitness']\n plt.plot(xf,fitness6,'--',color = 'c',label=\"IEABC\")\n '''\n\n if \"LSABC\" in dump_data:\n fitness3 = dump_data[\"LSABC\"]['fitness']\n plt.plot(xf,fitness3,'--',color = 'y',label=\"LSABC\")\n\n if \"DEABC\" in dump_data:\n fitness4 = dump_data[\"DEABC\"]['fitness']\n plt.plot(xf,fitness4,':',color = 'b',label=\"DEABC\")\n\n if \"HSABC\" in dump_data:\n fitness5 = dump_data[\"HSABC\"]['fitness']\n plt.plot(xf,fitness5,':',color = 'r',label=\"HSABC\")\n\n if \"SFLA\" in dump_data:\n fitness7 = dump_data[\"SFLA\"]['fitness']\n plt.plot(xf,fitness7,'-',color = 'm',label=\"SFLA\")\n\n #解决中文显示问题\n #plt.rcParams['font.sans-serif']=['FangSong']\n #plt.rcParams['axes.unicode_minus'] = False\n plt.xlabel(u\"迭代次数\") #横坐标名字\n plt.ylabel(u\"适应度值\") #纵坐标名字\n plt.legend(loc = \"best\") #图例\n\n plt.savefig(jpg_file)\n\n #plt.show()\n","sub_path":"my1/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"223649412","text":"import pygame\nfrom pygame.locals import *\n\npygame.font.init()\ntitlefont = pygame.font.SysFont('Arial', 60)\nmenufont = pygame.font.SysFont('Arial', 30)\n\n# Checks whether the given player has 3 pieces in a row on the given board\ndef is_win(grid, player):\n\t# Check if won by 3 in a row\n\tfor row in range(3):\n\t\tif grid[row] == [player,player,player]:\n\t\t\treturn True\n\t# Check if won by 3 in a column\n\tfor column in range(3):\n\t\tthreeinarow = True\n\t\tfor row in range(3):\n\t\t\tif grid[row][column] != player:\n\t\t\t\tthreeinarow = False\n\t\tif threeinarow:\n\t\t\treturn True\n\t# Check the diagonals\n\tif grid[0][0] == player and grid[1][1] == player and grid[2][2] == player:\n\t\treturn True\n\tif grid[0][2] == player and grid[1][1] == player and grid[2][0] == player:\n\t\treturn True\n\treturn False\n\n# Checks whether the grid is a tie due to having no more spaces left\ndef is_tie(grid):\n\tfor row in range(3):\n\t\tfor column in range(3):\n\t\t\tif grid[row][column] == \"\":\n\t\t\t\treturn False\n\treturn True\n\n# Returns all possible grids that could happen after one move from the given player\ndef get_successors(grid, player):\n\tsuccessors = []\n\tfor row in range(3):\n\t\tfor column in range(3):\n\t\t\t# If a spot is empty, it's a potential move, so create a successor for it\n\t\t\tif grid[row][column] == \"\":\n\t\t\t\tcopy = [row.copy() for row in grid]\n\t\t\t\tcopy[row][column] = player\n\t\t\t\tsuccessors.append(copy)\n\treturn successors\n\n# Evaluate how good a grid is. 1 = x wins, 0 = o wins, .5 = tie/not over yet\ndef evaluation_function(grid):\n\tif is_win(grid, \"x\"):\n\t\treturn 1\n\tif is_win(grid, \"o\"):\n\t\treturn 0\n\treturn 0.5\n\ndef custom_evaluation_function(grid):\n\t# With a smarter evaluation function even the non-impossible AI can be nearly unstoppable.\n\t# Try assigning a score based on custom features like having the middle square or 2 in a row\n\traise NotImplementedError()\n\n# Utility function to return the opposing player\ndef other(player):\n\tif player == \"x\":\n\t\treturn \"o\"\n\telse:\n\t\treturn \"x\"\n\n# Defines that x wishes to maximize the score while o wishes to minimize it. Optional to use this variable\nplayer_functions = {'x': max, 'o': min}\n\n# Recursively calculates the value of a particular grid\ndef value(grid, player, depth, maxdepth):\n\t# Terminal conditions - stop recursing and return a value\n\tif is_win(grid, player) or is_win(grid, other(player)) or is_tie(grid) or depth >= maxdepth:\n\t\treturn evaluation_function(grid)\n\t# Recursively get the value of each child\n\tchildren = get_successors(grid, player)\n\tchild_values = []\n\tfor i in range(len(children)):\n\t\tchild_values.append(value(children[i], other(player), depth+1, maxdepth))\n\t# Choose the best score for this player\n\tcomparison = player_functions[player]\n\treturn comparison(child_values)\n\n# Uses value() to get the score for each of grid's children then chooses the best child\ndef minimax(grid, player, maxdepth):\n\t# Terminal conditions - stop recursing and return a value\n\tif is_win(grid, player) or is_win(grid, other(player)) or is_tie(grid):\n\t\traise ValueError(\"Cannot choose next best move when game has terminated\")\n\t# Recursively get the value of each child\n\tchildren = get_successors(grid, player)\n\tchild_values = []\n\tfor i in range(len(children)):\n\t\tchild_values.append(value(children[i], other(player), 0, maxdepth))\n\t# Choose the best child for this player\n\tcomparison = player_functions[player]\n\tbestvalue = comparison(child_values)\n\treturn children[child_values.index(bestvalue)]\t\n\n# Used to reset the grid after the game ends\ndef empty_grid():\n\treturn [[\"\",\"\",\"\"],[\"\",\"\",\"\"],[\"\",\"\",\"\"]]\n\n# The main class which runs the game\nclass App:\n\tdef __init__(self):\n\t\tself._running = True\n\t\tself.screen = None\n\t\tself.size = self.width, self.height = 600, 600\n\t\t\n\t\t# Variables for the player, AI difficulty, and grid of pieces\n\t\tself.grid = empty_grid()\n\t\tself.player = \"x\"\n\t\tself.difficulty = 1\n\t\t\n\t\t# Helper variables for making the menu and game over screens work properly\n\t\tself.menu = True\n\t\tself.gameover = False\n\t\tself.waitcounter = 0\n\t\tself.clock = pygame.time.Clock()\n\t\tself.message = None\n\n\t# Set up the screen\n\tdef on_init(self):\n\t\tpygame.init()\n\t\tself.screen = pygame.display.set_mode(self.size, pygame.HWSURFACE | pygame.DOUBLEBUF)\n\t\tself._running = True\n\n\t# Whenever a key is pressed or the screen is clicked, handle the event\n\tdef on_event(self, event):\n\t\tif event.type == pygame.QUIT:\n\t\t\tself._running = False\n\t\tif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n\t\t\tx,y = pygame.mouse.get_pos()\n\t\t\t# On the menu, handle each of the 4 buttons\n\t\t\tif self.menu:\n\t\t\t\tif x > 225 and x < 375:\n\t\t\t\t\tif y > 100 and y < 175:\n\t\t\t\t\t\tself.menu = False\n\t\t\t\t\t\tif self.player == \"o\":\n\t\t\t\t\t\t\tself.grid = minimax(self.grid, other(self.player), self.difficulty)\n\t\t\t\t\tif y > 450 and y < 525:\n\t\t\t\t\t\tself._running = False\n\t\t\t\tif x > 125 and x < 275:\n\t\t\t\t\tif y > 250 and y < 325:\n\t\t\t\t\t\tself.difficulty = 1\n\t\t\t\t\tif y > 350 and y < 425:\n\t\t\t\t\t\tself.player = \"x\"\n\t\t\t\tif x > 325 and x < 475:\n\t\t\t\t\tif y > 250 and y < 325:\n\t\t\t\t\t\tself.difficulty = 4\n\t\t\t\t\tif y > 250 and y < 425:\n\t\t\t\t\t\tself.player = \"o\"\n\n\t\t\t# Outside of the menu, determine where the player clicked and try to move there\n\t\t\telse:\n\t\t\t\tif not self.gameover:\n\t\t\t\t\tx,y = pygame.mouse.get_pos()\n\t\t\t\t\ti,j = 0,0\n\t\t\t\t\tif x < 200:\n\t\t\t\t\t\tj = 0\n\t\t\t\t\telif x > 400:\n\t\t\t\t\t\tj = 2\n\t\t\t\t\telse:\n\t\t\t\t\t\tj = 1\n\t\t\t\t\tif y < 200:\n\t\t\t\t\t\ti = 0\n\t\t\t\t\telif y > 400:\n\t\t\t\t\t\ti = 2\n\t\t\t\t\telse:\n\t\t\t\t\t\ti = 1\n\t\t\t\t\tif self.grid[i][j] == \"\":\n\t\t\t\t\t\tself.grid[i][j] = self.player\n\t\t\t\t\t\t# Check whether the game should now end due to a win or tie\n\t\t\t\t\t\tif is_win(self.grid, self.player):\n\t\t\t\t\t\t\tself.message = \"You Win!\"\n\t\t\t\t\t\t\tself.gameover=True\n\t\t\t\t\t\t\tself.grid = empty_grid()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tif is_tie(self.grid):\n\t\t\t\t\t\t\tself.message = \"Cat's game\"\n\t\t\t\t\t\t\tself.gameover=True\n\t\t\t\t\t\t\tself.grid = empty_grid()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\t# Let the AI move if the game isn't over\n\t\t\t\t\t\tself.grid = minimax(self.grid, other(self.player), self.difficulty)\n\t\t\t\t\t\t# Check whether the game should now end due to a loss or tie\n\t\t\t\t\t\tif is_win(self.grid, other(self.player)):\n\t\t\t\t\t\t\tself.message = \"You Lose!\"\n\t\t\t\t\t\t\tself.gameover=True\n\t\t\t\t\t\t\tself.grid = empty_grid()\n\t\t\t\t\t\t\treturn\n\t\t\t\t\t\tif is_tie(self.grid):\n\t\t\t\t\t\t\tself.message = \"Cat's game\"\n\t\t\t\t\t\t\tself.gameover=True\n\t\t\t\t\t\t\tself.grid = empty_grid()\n\t\t\t\t\t\t\treturn\n\n\t# Counts loops to wait 4 seconds after game over before returning to menu\n\tdef on_loop(self):\n\t\tself.clock.tick(60)\n\t\tif self.gameover:\n\t\t\tself.waitcounter += 1\n\t\t\tif self.waitcounter == 60 * 4:\n\t\t\t\tself.waitcounter = 0\n\t\t\t\tself.gameover = False\n\t\t\t\tself.menu = True\n\t\t\t\tself.message = None\n\n\t# Draws all graphics\n\tdef on_render(self):\n\t\tself.screen.fill((255,255,255))\n\t\t# Draws either the current game or the end game message\n\t\tif not self.menu:\n\t\t\tif self.message:\n\t\t\t\tmessagesurface = titlefont.render(self.message, False, (0,0,0))\n\t\t\t\tself.screen.blit(messagesurface, (self.width//2 - messagesurface.get_width()//2, self.height//2 - messagesurface.get_height()//2))\n\t\t\telse:\n\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (200,0), (200,600))\n\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (400,0), (400,600))\n\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (0,200), (600,200))\n\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (0,400), (600,400))\n\t\t\t\tfor row in range(3):\n\t\t\t\t\tfor col in range(3):\n\t\t\t\t\t\tif self.grid[row][col] == \"o\":\n\t\t\t\t\t\t\tpygame.draw.circle(self.screen, (0,0,0), (col*200+100, row*200+100), 75, 1)\n\t\t\t\t\t\tif self.grid[row][col] == \"x\":\n\t\t\t\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (col*200-53+100, row*200-53+100), (col*200+53+100,row*200+53+100))\n\t\t\t\t\t\t\tpygame.draw.line(self.screen, (0,0,0), (col*200+53+100, row*200-53+100), (col*200-53+100,row*200+53+100))\n\t\t# Draws the menu buttons and captions\n\t\telse:\n\t\t\ttitlesurface = titlefont.render(\"Tic Tac Toe\", False, (0,0,0))\n\t\t\tself.screen.blit(titlesurface, (180, 10))\n\t\t\t# Play button\n\t\t\tpygame.draw.rect(self.screen, (200,200,200), (225, 100, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Play\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (280,120))\n\t\t\t# Regular difficulty\n\t\t\tpygame.draw.rect(self.screen, (100,200,100), (125, 250, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Regular\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (150,270))\n\t\t\t# Impossible difficulty\n\t\t\tpygame.draw.rect(self.screen, (200,100,100), (325, 250, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Impossible\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (350,270))\n\t\t\t# Play as X\n\t\t\tpygame.draw.rect(self.screen, (200,200,200), (125, 350, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Play as X\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (150,370))\n\t\t\t# Play as O\n\t\t\tpygame.draw.rect(self.screen, (200,200,200), (325, 350, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Play as O\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (350,370))\n\t\t\t# Quit button\n\t\t\tpygame.draw.rect(self.screen, (200,200,200), (225, 450, 150, 75))\n\t\t\ttextsurface = menufont.render(\"Quit\", False, (0,0,0))\n\t\t\tself.screen.blit(textsurface, (280,470))\n\t\tpygame.display.update()\n\t\n\tdef on_cleanup(self):\n\t\tpygame.quit()\n \n \t# Calls the other functions in the correct order and fetches events\n\tdef on_execute(self):\n\t\tif self.on_init() == False:\n\t\t\tself._running = False\n \n\t\twhile( self._running ):\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tself.on_event(event)\n\t\t\tself.on_loop()\n\t\t\tself.on_render()\n\t\tself.on_cleanup()\n \nif __name__ == \"__main__\" :\n\ttheApp = App()\n\ttheApp.on_execute()","sub_path":"TCSB-Rise-of-the-Machines/TicTacToe/Solutions/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":9356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"147216767","text":"import unittest\nimport HTMLTestRunner\nimport os\ncurrent_path=os.path.dirname(os.path.realpath(__file__))\nreporter_path=os.path.join(current_path,\"report\")\nif not os.path.exists(reporter_path):os.mkdir(reporter_path)\ntest_dir='./'\nsuite=unittest.TestLoader().discover(test_dir,pattern=\"*test.py\")\nif __name__==\"__main__\":\n html_report=reporter_path+r\"\\result.html\"\n fp=open(html_report,\"wb\")\n runner=HTMLTestRunner.HTMLTestRunner(stream=fp,verbosity=2,title=\"单元测试报告\",description=\"用例执行情况\")\n runner.run(suite)\n\n\n\n","sub_path":"Test/discover.py","file_name":"discover.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"6126232","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 21 10:23:32 2020\n\n@author: ombretta\n\"\"\"\n\n'''Arguments IN 3D ResNets PyTorch'''\n\nimport os \n\nsubmit_on_cluster = True\npretrained = False\ncontinue_training = True\n\ntext = ''\n\nif submit_on_cluster:\n text = '#!/bin/sh\\n'+\\\n '#SBATCH --partition=general\\n'+\\\n '#SBATCH --qos=long\\n'+\\\n '#SBATCH --time=168:00:00\\n'+\\\n '#SBATCH --ntasks=1\\n'+\\\n '#SBATCH --mail-type=END\\n'+\\\n '#SBATCH --cpus-per-task=4\\n'+\\\n '#SBATCH --mem=16000\\n'+\\\n '#SBATCH --gres=gpu:8\\n'+\\\n 'module use /opt/insy/modulefiles\\n'+\\\n 'module load cuda/10.0 cudnn/10.0-7.6.0.64\\n'+\\\n 'srun '\n \n'''List of arguments from the repository:'''\n# Root directory path\n#root_path = '/tudelft.net/staff-bulk/ewi/insy/VisionLab/ombrettastraff/'\nroot_path = '/tudelft.net/staff-bulk/ewi/insy/'\n# Directory path of videos\n#video_path = 'CV-DataSets/kinetics400/jpg'\nvideo_path = 'CV-DataSets/kinetics400/'\n# Annotation file path\nannotation_path = 'CV-DataSets/kinetics400/kinetics400.json'\n# Used dataset (activitynet | kinetics | ucf101 | hmdb51)\ndataset = 'kinetics'\n# Number of classes (activitynet: 200, kinetics: 400 or 600, ucf101: 101, hmdb51: 51)\nn_classes = 400\n# Number of classes of pretraining task. When using --pretrain_path, this must be set.\nn_pretrain_classes = 400\n# Pretrained model path (.pth).\n#pretrain_path = \"VisionLab/ombrettastraff/3D-ResNets-PyTorch/pretrained_models/r3d50_K_200ep.pth\"\npretrain_path = \"VisionLab/ombrettastraff/3D-ResNets-PyTorch/results/kinetics_vidbagnet_tem_9_48frames_bs128_0/save_13.pth\"\n# Module name of beginning of fine-tuning (conv1, layer1, fc, denseblock1, classifier, ...). The default means all layers are fine-tuned.\nft_begin_module = ''\n# Height and width of inputs\nsample_size = 64\n# Temporal duration of inputs\nsample_duration = 48\n# If larger than 1, input frames are subsampled with the stride.\nsample_t_stride = 1\n# Spatial cropping method in training. random is uniform. corner is selection from 4 corners and 1 center. random | corner | center)\ntrain_crop = 'random'\n# Min scale for random cropping in training\ntrain_crop_min_scale = 0.25\n# Min scale for random cropping in training\ntrain_crop_min_ratio = 0.75\n# If true holizontal flipping is not performed.\nno_hflip = False\n# If true colorjitter is performed.\ncolorjitter = False\n# Temporal cropping method in training. random is uniform. (random | center)\ntrain_t_crop = 'center'\n# Initial learning rate (divided by 10 while training by lr scheduler)\nlearning_rate = 0.01\n# Momentum\nmomentum = 0.9\n# dampening of SGD\ndampening = 0.0\n# Weight Decay\nweight_decay = 1e-3\n# dataset for mean values of mean subtraction (activitynet | kinetics | 0.5)\nmean_dataset = 'kinetics'\n# If true, inputs are not normalized by mean.\nno_mean_norm = False\n# If true, inputs are not normalized by standard deviation.\nno_std_norm = False\n# If 1, range of inputs is [0-1]. If 255, range of inputs is [0-255].\nvalue_scale = 255\n# Nesterov momentum\nnesterov = False\n# Currently only support SGD\noptimizer = 'sgd'\n# Type of LR scheduler (multistep | plateau)\nlr_scheduler = 'multistep'\n# Milestones of LR scheduler. See documentation of MultistepLR.\nmultistep_milestones = \"30 60 90\"\n# If true, overwriting multistep_milestones when resuming training.\noverwrite_milestones = False\n# Patience of LR scheduler. See documentation of ReduceLROnPlateau.\nplateau_patience = 10\n# Batch Size\nbatch_size = 128\n# Batch Size for inference. 0 means this is the same as batch_size.\ninference_batch_size = 0\n# If true, SyncBatchNorm is used instead of BatchNorm.\nbatchnorm_sync = False\n# Number of total epochs to run\nn_epochs = 100\n# Number of validation samples for each activity\nn_val_samples = 3\n# Save data (.pth) of previous training\nresume_path = None\n# If true, training is not performed.\nno_train = False\n# If true, validation is not performed.\nno_val = False\n# If true, inference is performed.\ninference = False\n# Used subset in inference (train | val | test)\ninference_subset = 'val'\n# Stride of sliding window in inference.\ninference_stride = 16\n# Cropping method in inference. (center | nocrop). When nocrop, fully convolutional inference is performed, and mini-batch consists of clips of one video.\ninference_crop = 'center'\n# If true, outputs for segments in a video are not averaged.\ninference_no_average = False\n# If true, cuda is not used.\nno_cuda = False\n# Number of threads for multi-thread loading\nn_threads = 8\n# Trained model is saved at every this epochs.\ncheckpoint = 1\n# (resnet | resnet2p1d | preresnet | wideresnet | resnext | densenet | vidbagnet |\nmodel = 'vidbagnet_tem'\n# Depth of resnet (10 | 18 | 34 | 50 | 101)\nmodel_depth = 50\n# Depth of resnet (9 | 17 | 33)\nreceptive_size = 9\n# Kernel size in t dim of conv1.\nconv1_t_size = 7\n# Stride in t dim of conv1.\nconv1_t_stride = 1\n# If true, the max pooling after conv1 is removed. \nno_max_pool = False\n# Shortcut type of resnet (A | B)\nresnet_shortcut = 'B'\n# The number of feature maps of resnet is multiplied by this value\nresnet_widen_factor = 1.0\n# Wide resnet k\nwide_resnet_k = 2\n# ResNeXt cardinality\nresnext_cardinality = 32\n# (rgb | flow)\ninput_type = 'rgb'\n# Manually set random seed\nmanual_seed = 10\n# If true, accimage is used to load images.\naccimage = False\n# Top-k scores are saved in json file.\noutput_topk = 5\n# (jpg | hdf5)\nfile_type = 'hdf5'\n# If true, output tensorboard log file.\ntensorboard = True\n# Use multi-processing distributed training to launch N processes per node, which has N GPUs.\ndistributed = False\n# url used to set up distributed training\ndist_url = 'tcp://127.0.0.1:23456'\n# number of nodes for distributed training\nworld_size = 1\n\ntext += \"python main.py \"\n\nif root_path: text += \" --root_path=\" + root_path\ntext += \" --video_path=\" + video_path\ntext += \" --annotation_path=\" + annotation_path\ntext += \" --dataset=\" + dataset\ntext += \" --n_classes=\" + str(n_classes)\ntext += \" --sample_size=\" + str(sample_size)\ntext += \" --sample_duration=\" + str(sample_duration)\ntext += \" --sample_t_stride=\" + str(sample_t_stride)\ntext += \" --train_crop=\" + train_crop\ntext += \" --train_crop_min_scale=\" + str(train_crop_min_scale)\ntext += \" --train_crop_min_ratio=\" + str(train_crop_min_ratio)\nif colorjitter: text += \" --colorjitter\"\ntext += \" --train_t_crop=\" + str(train_t_crop)\ntext += \" --learning_rate=\" + str(learning_rate)\ntext += \" --momentum=\" + str(momentum)\ntext += \" --dampening=\" + str(dampening)\ntext += \" --weight_decay=\" + str(weight_decay)\ntext += \" --mean_dataset=\" + mean_dataset\nif no_mean_norm: text += \" --no_mean_norm\"\nif no_std_norm: text += \" --no_std_norm\"\ntext += \" --value_scale=\" + str(value_scale)\nif nesterov: text += \" --nesterov\"\ntext += \" --optimizer=\" + optimizer\ntext += \" --lr_scheduler=\" + lr_scheduler\ntext += \" --multistep_milestones \" + str(multistep_milestones)\nif overwrite_milestones: text += \" --overwrite_milestones\"\ntext += \" --plateau_patience=\" + str(plateau_patience)\ntext += \" --inference_batch_size=\" + str(inference_batch_size)\nif batchnorm_sync: text += \" --batchnorm_sync\"\nif resume_path: text += \" --resume_path\"\nif no_train: text += \" --no_train\"\nif no_val: text += \" --no_val\"\nif inference: text += \" --inference\"\ntext += \" --inference_subset=\" + inference_subset\ntext += \" --inference_stride=\" + str(inference_stride)\ntext += \" --inference_crop=\" + inference_crop\nif no_cuda: text += \" --no_cuda\"\nif no_hflip: text += \" --no_hflip\"\nif no_mean_norm: text += \" --no_mean_norm\"\nif no_std_norm: text += \" --no_std_norm\"\ntext += \" --batch_size=\" + str(batch_size)\ntext += \" --inference_batch_size=\" + str(inference_batch_size)\ntext += \" --n_val_samples=\" + str(n_val_samples)\ntext += \" --n_epochs=\" + str(n_epochs)\nif inference_no_average: text += \" --inference_no_average\"\ntext += \" --n_threads=\" + str(n_threads)\ntext += \" --checkpoint=\" + str(checkpoint)\ntext += \" --model=\" + model\ntext += \" --model_depth=\" + str(model_depth)\ntext += \" --receptive_size=\" + str(receptive_size)\ntext += \" --conv1_t_size=\" + str(conv1_t_size)\ntext += \" --conv1_t_stride=\" + str(conv1_t_stride)\nif no_max_pool: text += \" --no_max_pool\"\ntext += \" --resnet_shortcut=\" + resnet_shortcut\ntext += \" --resnet_widen_factor=\" + str(resnet_widen_factor)\ntext += \" --wide_resnet_k=\" + str(wide_resnet_k)\ntext += \" --resnext_cardinality=\" + str(resnext_cardinality)\ntext += \" --input_type=\" + input_type\ntext += \" --manual_seed=\" + str(manual_seed)\nif accimage: text += \" --accimage\"\ntext += \" --output_topk=\" + str(output_topk)\nif file_type: text += \" --file_type=\" + file_type\nif tensorboard: text += \" --tensorboard\"\nif distributed: text += \" --distributed\"\ntext += \" --ft_begin_module=\"+ft_begin_module\n\n#last\n# Result directory path\nresults_root = 'VisionLab/ombrettastraff/3D-ResNets-PyTorch/results/'\nresult_path = dataset + \"_\" + model\nif model == 'resnet':\n result_path += \"_\" + str(model_depth)\nelse:\n result_path += \"_\" + str(receptive_size)\n#result_path += \"_TESTwithfirst64frames\"\nresult_path += \"_\" + str(sample_duration) + \"frames\"\nif sample_t_stride != 1:\n result_path += \"_\" + str(sample_t_stride) + \"tstride\"\nif sample_size != 64:\n result_path += \"_\" + str(sample_size) + \"size\"\nresult_path += \"_bs\" + str(batch_size)\n\nif pretrained:\n result_path += \"_kinetics_pretrained\"\n text += \" --pretrain_path=\" + pretrain_path\n text += \" --n_pretrain_classes=\" + str(n_pretrain_classes)\n \nindex = len([f for f in os.listdir(root_path+results_root) if result_path in f])\nif not os.path.exists(root_path+results_root+result_path+\"_\"+str(index)):\n os.mkdir(root_path+results_root+result_path+\"_\"+str(index))\n\ntext += \" --result_path=\" + results_root + result_path + \"_\" + str(index)\n\nprint(result_path, index)\nif continue_training:\n text += \" --n_pretrain_classes=\" + str(n_classes)\n pretrain_path = root_path+results_root+result_path+\"_\"+str(max(0, index-1))\n if os.path.exists(pretrain_path):\n print(pretrain_path)\n trained_models = [int(f.split(\"_\")[1].split(\".\")[0]) for f in os.listdir(pretrain_path) if \"save_\" in f]\n last_model_index = max(trained_models)\n pretrain_path += \"/save_\"+str(last_model_index)+\".pth\" \n text += \" --pretrain_path=\" + pretrain_path\n\nprint(text)\n\nif submit_on_cluster:\n with open(result_path+\"_\"+str(index)+\".sbatch\", \"w\") as file:\n file.write(text)\n os.system(\"sbatch \"+result_path+\"_\"+str(index)+\".sbatch\") \nelse:\n os.system(text)\n\n","sub_path":"kinetics_train.py","file_name":"kinetics_train.py","file_ext":"py","file_size_in_byte":10436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"455229537","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ntests.py\n----------------------------------\n\nTests for `cached-property` module.\n\"\"\"\n\nfrom time import sleep\nfrom threading import Lock, Thread\nimport unittest\nfrom freezegun import freeze_time\n\nfrom cached_property import cached_property\n\n\nclass TestCachedProperty(unittest.TestCase):\n\n def test_cached_property(self):\n\n class Check(object):\n\n def __init__(self):\n self.total1 = 0\n self.total2 = 0\n\n @property\n def add_control(self):\n self.total1 += 1\n return self.total1\n\n @cached_property\n def add_cached(self):\n self.total2 += 1\n return self.total2\n\n c = Check()\n\n # The control shows that we can continue to add 1.\n self.assertEqual(c.add_control, 1)\n self.assertEqual(c.add_control, 2)\n\n # The cached version demonstrates how nothing new is added\n self.assertEqual(c.add_cached, 1)\n self.assertEqual(c.add_cached, 1)\n\n # Cannot expire the cache.\n with freeze_time(\"9999-01-01\"):\n self.assertEqual(c.add_cached, 1)\n\n # It's customary for descriptors to return themselves if accessed\n # though the class, rather than through an instance.\n self.assertTrue(isinstance(Check.add_cached, cached_property))\n\n def test_reset_cached_property(self):\n\n class Check(object):\n\n def __init__(self):\n self.total = 0\n\n @cached_property\n def add_cached(self):\n self.total += 1\n return self.total\n\n c = Check()\n\n # Run standard cache assertion\n self.assertEqual(c.add_cached, 1)\n self.assertEqual(c.add_cached, 1)\n\n # Reset the cache.\n del c._cache['add_cached']\n self.assertEqual(c.add_cached, 2)\n self.assertEqual(c.add_cached, 2)\n\n def test_none_cached_property(self):\n\n class Check(object):\n\n def __init__(self):\n self.total = None\n\n @cached_property\n def add_cached(self):\n return self.total\n\n c = Check()\n\n # Run standard cache assertion\n self.assertEqual(c.add_cached, None)\n\n\nclass TestThreadingIssues(unittest.TestCase):\n\n def test_threads(self):\n \"\"\" How well does the standard cached_property implementation work with threads?\n Short answer: It doesn't! Use threaded_cached_property instead!\n \"\"\" # noqa\n\n class Check(object):\n\n def __init__(self):\n self.total = 0\n self.lock = Lock()\n\n @cached_property\n def add_cached(self):\n sleep(1)\n # Need to guard this since += isn't atomic.\n with self.lock:\n self.total += 1\n return self.total\n\n c = Check()\n threads = []\n num_threads = 10\n for x in range(num_threads):\n thread = Thread(target=lambda: c.add_cached)\n thread.start()\n threads.append(thread)\n\n for thread in threads:\n thread.join()\n\n # Threads means that caching is bypassed.\n self.assertNotEqual(c.add_cached, 1)\n\n # This assertion hinges on the fact the system executing the test can\n # spawn and start running num_threads threads within the sleep period\n # (defined in the Check class as 1 second). If num_threads were to be\n # massively increased (try 10000), the actual value returned would be\n # between 1 and num_threads, depending on thread scheduling and\n # preemption.\n self.assertEqual(c.add_cached, num_threads)\n\n\nclass TestCachedPropertyWithTTL(unittest.TestCase):\n\n def test_ttl_expiry(self):\n\n class Check(object):\n\n def __init__(self):\n self.total = 0\n\n @cached_property(ttl=100000)\n def add_cached(self):\n self.total += 1\n return self.total\n\n c = Check()\n\n # Run standard cache assertion\n self.assertEqual(c.add_cached, 1)\n self.assertEqual(c.add_cached, 1)\n\n # Expire the cache.\n with freeze_time(\"9999-01-01\"):\n self.assertEqual(c.add_cached, 2)\n self.assertEqual(c.add_cached, 2)\n","sub_path":"tests/test_cached_property.py","file_name":"test_cached_property.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"566882328","text":"# -*- coding: utf-8 -*-\nimport csv\nimport json\nimport os\nimport re\n\nimport scrapy\nfrom urllib.parse import urlencode\n\nimport sys\n\nfrom scrapy.http import Response\n\nfrom ..items import CfdaItem\n\n\nclass CdfacrawlerSpider(scrapy.Spider):\n name = 'cdfacrawler'\n allowed_domains = ['appcfda.drugwebcn.com']\n start_urls = ['http://appcfda.drugwebcn.com/']\n\n def __init__(self):\n self.pagenum = 33177\n self.current = 0\n self.page_args = {\n 'tableId': 41,\n 'searchF': 'Quick Search',\n 'searchK': '',\n 'pageSize': 15\n }\n self.errorpage = []\n\n def start_requests(self):\n for i in range(0,self.pagenum):\n self.current = i+1\n self.page_args['pageIndex'] = self.current\n args = urlencode(self.page_args)\n yield scrapy.Request(url='http://appcfda.drugwebcn.com/datasearch/QueryList?'+args, callback=self.parse,meta={'page':self.current})\n\n def parse(self, response: Response):\n try:\n datas = json.loads(response.body)\n pattern = '\\.(?P.*)\\s\\((?P.*)\\)'\n for data in datas:\n\n item = CfdaItem()\n item['id'] = data.get(\"ID\")\n content = data.get('CONTENT') #type:str\n item['content'] = content\n try:\n r = re.search(pattern,content)\n item['name'] = r.group('name')\n item['license'] = r.group('license')\n except Exception:\n pass\n finally:\n yield item\n except Exception as e:\n self.errorpage.append(response.meta['page'])\n\n\n def close(spider, reason):\n errorpages = spider.errorpage\n with open('/Users/wangshaohu/Desktop/cdfaerror.csv','w') as f:\n writer = csv.writer(f)\n writer.writerows(errorpages)","sub_path":"cfda/cfda/spiders/cdfacrawler.py","file_name":"cdfacrawler.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"414873355","text":"import pdb\nimport numpy as np\nimport pickle\nimport datetime, json, os, argparse\n\nimport envs\nimport pyInfoGathering as IGL\n\nparser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\nparser.add_argument('--seed', help='RNG seed', type=int, default=0)\nparser.add_argument('--render', help='render', type=int, default=0)\nparser.add_argument('--record', help='record', type=int, default=0)\nparser.add_argument('--map', type=str, default=\"empty\")\nparser.add_argument('--env', help='environment ID', default='TargetTracking-info0')\nparser.add_argument('--ros', type=int, default=0)\nparser.add_argument('--log_dir', type=str, default='.')\nparser.add_argument('--nb_targets', type=int, default=1)\nparser.add_argument('--repeat', type=int, default=1)\n\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n # Initialize Planner\n n_controls = 5\n T = 12\n delta = 3\n eps = np.infty\n arvi_time = 1\n range_limit = np.infty\n debug = 1\n directory = os.path.join(args.log_dir, '_'.join([args.env, datetime.datetime.now().strftime(\"%m%d%H%M\")]))\n if not os.path.exists(directory):\n os.makedirs(directory)\n else:\n ValueError(\"The directory already exists...\", directory)\n json.dump(vars(args), open(os.path.join(directory, 'learning_prop.json'), 'w'))\n\n env = envs.make(args.env, \n render = bool(args.render), \n record = bool(args.record), \n ros = bool(args.ros), \n dirname=directory, \n map_name=args.map,\n num_targets=args.nb_targets,\n is_training=False\n )\n timelimit_env = env\n while( not hasattr(timelimit_env, '_elapsed_steps')):\n timelimit_env = timelimit_env.env \n\n ep_nlogdetdov = []\n for episode in range(args.repeat):\n planner = IGL.InfoPlanner()\n np.random.seed(args.seed + episode)\n \n # Save Planner Output\n plannerOutputs = [0] * 1\n\n # Main Loop\n nlogdetcov = []\n done = False\n obs = env.reset()\n t = 0\n while(not done):\n print('Timestep ', t)\n\n # Plan for individual Robots (Every n_controls steps)\n if t % n_controls == 0:\n plannerOutputs[0] = planner.planARVI(timelimit_env.env.agent.agent, T, delta, eps, arvi_time, debug, 0)\n\n # Apply Control\n obs, reward, done, info = env.step(plannerOutputs[0].action_idx[-1])\n if args.render:\n env.render()\n nlogdetcov.append(info['test_reward'])\n # Pop off last Action manually (UGLY)\n plannerOutputs[0].action_idx = plannerOutputs[0].action_idx[:-1]\n t += 1\n obs = env.reset()\n ep_nlogdetdov.append(np.sum(nlogdetcov))\n print(\"Ep.%d Cumulative Rewards = %.2f\"%(episode, ep_nlogdetdov[-1]))\n\n if args.repeat > 1:\n f = open(os.path.join(directory,'reward_batch_%d'%args.repeat + '.pkl'),'wb')\n pickle.dump(ep_nlogdetdov, f)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"python/ray/rllib/RL/DeepADFQ/run_anytime_planner.py","file_name":"run_anytime_planner.py","file_ext":"py","file_size_in_byte":3092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"443898244","text":"#!/usr/bin/env python3\n\nimport finplot as fplt\nimport pandas as pd\nimport requests\nfrom io import StringIO\nfrom time import time\n\n\n# load data and convert date\nend_t = int(time()) \nstart_t = end_t - 12*30*24*60*60 # twelve months\nsymbol = 'SPY'\ninterval = '1d'\nurl = 'https://query1.finance.yahoo.com/v7/finance/download/%s?period1=%s&period2=%s&interval=%s&events=history' % (symbol, start_t, end_t, interval)\nr = requests.get(url)\ndf = pd.read_csv(StringIO(r.text))\ndf['Date'] = pd.to_datetime(df['Date'])\n\n# plot candles\nax,ax2 = fplt.create_plot('S&P 500 MACD', rows=2)\nfplt.candlestick_ochl(df[['Date','Open','Close','High','Low']], ax=ax)\naxo = ax.overlay()\nfplt.volume_ocv(df[['Date','Open','Close','Volume']], ax=axo)\nfplt.plot(df.Volume.ewm(span=24).mean(), ax=axo, color=1)\n\n# plot macd\nmacd = df.Close.ewm(span=12).mean() - df.Close.ewm(span=26).mean()\nsignal = macd.ewm(span=9).mean()\ndf['macd_diff'] = macd - signal\nfplt.volume_ocv(df[['Date','Open','Close','macd_diff']], ax=ax2, colorfunc=fplt.strength_colorfilter)\nfplt.plot(macd, ax=ax2, legend='MACD')\nfplt.plot(signal, ax=ax2, legend='Signal')\n\nfplt.show()\n","sub_path":"finplot/example-snp500.py","file_name":"example-snp500.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"450071777","text":"#!/usr/bin/env python3\n\n#from aws_cdk import core as cdk\n\n# For consistency with TypeScript code, `cdk` is the preferred import name for\n# the CDK's core module. The following line also imports it as `core` for use\n# with examples from the CDK Developer's Guide, which are in the process of\n# being updated to use `cdk`. You may delete this import if you don't need it.\nfrom aws_cdk import core\n\nfrom cdk.cdk_stack import CdkStack\nimport aws_cdk.aws_s3 as s3\n\nclass S3(core.Stack):\n def S3Stack(self):\n s3.Bucket(\n bucket_name=\"alphaiocloudskillstestbucket24032021\"\n )\n\n\napp = core.App()\nS3(app, \"cdk\")\n#CdkStack(app, \"CdkStack\")\n\napp.synth()\n","sub_path":"Week-2-Automation-and-Development/CDK/cdk/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"69215404","text":"# import modules for handling files\nimport csv\nfrom pathlib import Path\nfrom sys import argv\n\n# import third-party packages\nimport numpy as np\nimport tifffile as tiff\nfrom skimage import img_as_ubyte\nfrom skimage.morphology import binary_opening\n#from scipy.ndimage import generate_binary_structure\n\n# import utility functions\nfrom .utility import mask_cell\n\n# %%\ndef batch_mask(path, pattern='GFP', mask_channel=None,\n camera_bits=16, r=10, method='triangle', mask_open=True,\n save_values=False, save_summary=False, save_mask=False):\n \"\"\"\n Read all .tif images with a keyword and apply a 3D masking procedure\n based on a median-filtered image.\n\n Returns\n -------\n dict\n Key is the image name, value is a flat array of all intensities in the masked image.\n\n Parameters\n ----------\n\n path: str\n A path to folder with images to be processed. Must contain images in TIFF format.\n pattern: str, optional\n A pattern within filenames to be processed.\n mask_channel: str, optional\n If specified, the mask is created based on another image. \n Both images have to have the same name, except *mask_channel* is substituted for *pattern*.\n camera_bits: int, optional\n Ignore images with saturated pixels, based on the camera digitizer bit-depth.\n r: int, optional\n Radius for the median filtering function.\n method: str, optional\n Which thresholding method to use. See .utility.treshold().\n mask_open: bool, optional\n If True, perform a binary opening of the mask with the default selem (3D cross).\n save_values: bool, optional\n If True, write one .txt file per image with all pixel values.\n save_summary: bool, optional\n If True, write one .csv file per image with summary statistics (mean, median, sd).\n save_mask: bool, optional\n If True, save masks as 8-bit .tif files.\n \"\"\"\n # path handling through Pathlib: make output folder within current path\n path_in = Path(path)\n # initialise a dictionary to store results\n pixels = {}\n\n # output: prepare folder to keep masks\n if save_mask:\n path_out = path_in.joinpath('masks') # prepare output path\n path_out.mkdir(parents=True, exist_ok=True)\n \n # actual function: loop over each file with pattern, mask and convert to array\n for i in sorted(path_in.glob('*' + pattern + '*')):\n im = tiff.imread(str(i))\n \n # filter out saturated images\n if 2 ** camera_bits - 1 in im:\n continue\n\n # generate and apply mask\n if mask_channel:\n im_alt = tiff.imread(str(i).replace(pattern, mask_channel))\n im_mask = mask_cell(im_alt, radius=r, method=method)\n if mask_open:\n im_mask = binary_opening(im_mask)\n im_values = im[im_mask] # mask and select values\n else: \n im_mask = mask_cell(im, radius=r, method=method)\n if mask_open:\n im_mask = binary_opening(im_mask)\n im_values = im[im_mask] # mask and select values\n\n # add dictionary entry with name (no extension) and pixel values\n pixels[i.name.replace('.tif', '')] = im_values\n\n # output: save masks in a subfolder\n if save_mask:\n # substitute channel and / or annotate mask in filename\n if mask_channel:\n mask_out = path_out.joinpath(i.name.replace(\n pattern, mask_channel).replace('.tif', '_mask.tif'))\n else:\n mask_out = path_out.joinpath(\n i.name.replace('.tif', '_mask.tif'))\n tiff.imsave(mask_out, img_as_ubyte(im_mask))\n # very useful for assessing the algorithm but ultimately waste of space\n tiff.imsave(path_out.joinpath(i.name.replace('.tif', '_masked.tif')),\n im * im_mask)\n\n # output: save each dictionary entry as separate file in a subfolder\n if save_values:\n path_out = path_in.joinpath('masked_arrays') # prepare output path\n f = '%i' # not quite necessary but the default 18-digit precision means relatively huge files\n path_out.mkdir(parents=True, exist_ok=True)\n # save array\n for key, value in pixels.items():\n np.savetxt(str(path_out.joinpath(key))+'.txt', value, fmt=f)\n\n # output: save a csv file with mean intensity for each cell\n if save_summary:\n path_out = path_in.joinpath(\"summary.csv\")\n with path_out.open('w', newline='') as f: # initialize a csv file for writing\n # initialize csv writer and write headers\n writer = csv.writer(f, dialect='excel')\n writer.writerow(['cell', 'mean', 'median', 'sd'])\n for key, value in pixels.items():\n writer.writerow([key, round(np.mean(value), 3),\n np.median(value), round(np.std(value), 3)])\n\n # output: return dictionary of masked pixels\n return(pixels)\n\n\n# get the path from command line and run counting function\nif __name__ == \"__main__\": # only executed if ran as script\n path = argv[1]\n batch_mask(path, save_summary=True)\n","sub_path":"mkimage/mkimage/cell_values.py","file_name":"cell_values.py","file_ext":"py","file_size_in_byte":5213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"71410676","text":"import base64\nimport unittest\nfrom io import BytesIO\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom os import path\n\nfrom PIL import Image\n\nfrom src.handler import evaluate\n\n\nclass WordCloudBaseTest(unittest.TestCase):\n\n @staticmethod\n def test_wordcloud():\n mask = Image.open(\"wordcloud_logo.png\")\n buf = BytesIO()\n mask.save(buf, format=\"png\")\n buf.seek(0)\n mask_b64 = base64.b64encode(buf.read()).decode('utf-8')\n\n with open('documentation.txt', 'rb') as file:\n text_bytes = BytesIO(file.read())\n text_b64 = base64.b64encode(text_bytes.read()).decode('utf-8')\n\n url = \"https://en.wikipedia.org/wiki/Artificial_intelligence\"\n response = evaluate({\"text\": text_b64,\n \"mask\": mask_b64,\n \"url\": url,\n \"config\": '{\"max_words\": 100, \"max_font_size\": 123, \"height\": 500, \"width\": 500}'},\n {})\n\n # show word cloud image\n image_input = base64.b64decode(response[\"image\"].encode('utf-8'))\n input_buf = BytesIO()\n input_buf.write(image_input)\n input_buf.seek(0)\n im = Image.open(input_buf)\n im.show()\n input_buf.close()\n im1 = im.save(\"wordcloud.jpg\")\n\n @staticmethod\n @unittest.skip(reason=\"currently not needed\")\n def test_wordcloud_mask_standalone():\n text = \"Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et \" \\\n \"justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, \" \\\n \"sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd \" \\\n \"gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.\"\n mask = np.array(Image.open(\"wordcloud_logo.png\"))\n\n wordcloud = WordCloud(background_color=\"white\", max_words=100, mask=mask).generate(text)\n plt.figure()\n plt.imshow(wordcloud, interpolation=\"bilinear\")\n plt.axis(\"off\")\n plt.show()\n\n if __name__ == '__main__':\n unittest.main()\n","sub_path":"src/tests/wordcloud_test.py","file_name":"wordcloud_test.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"321239707","text":"\n\nfrom xai.brain.wordbase.nouns._pro import _PRO\n\n#calss header\nclass _PROS(_PRO, ):\n\tdef __init__(self,): \n\t\t_PRO.__init__(self)\n\t\tself.name = \"PROS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"pro\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_pros.py","file_name":"_pros.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"273667645","text":"class Node:\n def __init__(self, v, l=None, r=None):\n self.left = l\n self.right = r\n self.val = v\n\ndef dfs_iter(root):\n current = root\n s = []\n while True:\n if current is not None:\n s.append(current)\n current = current.left\n else:\n if len(s) > 0:\n current = s.pop()\n print(current.val)\n current = current.right\n else:\n break\n\n\ndef dfs_recur(nd):\n if nd.left:\n dfs_recur(nd.left)\n print(' ', nd.val)\n if nd.right:\n dfs_recur(nd.right)\n\n\ninps = [Node(5, Node(3, Node(2), Node(4)), Node(7, None, Node(8)))]\n\nfor inp in inps:\n print(f\"Running iter: \")\n dfs_iter(inp)\n\n print(f\"Running recur: \")\n dfs_recur(inp)\n","sub_path":"python/data_structs_and_algos/dfs_iter.py","file_name":"dfs_iter.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"218343761","text":"import os\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom core.models import predict\nfrom utils.Loss import *\n\n\n\n\nclass Model(object):\n def __init__(self, configs):\n self.configs = configs\n self.num_hidden = [int(x) for x in configs.num_hidden.split(',')]\n self.num_layers = len(self.num_hidden)\n networks_map = {\n 'rst':predict.RST_LSTM,\n 'rst_h':predict.RST_LSTM_H,\n 'rst_m':predict.RST_LSTM_M,\n 'rst_x':predict.RST_LSTM_X,\n 'predrnn': predict.PredRNN,\n 'convlstm':predict.ConvLSTM,\n # 'gru':predict.ConvGRU,\n # 'trajgru':predict.TrajGRU,\n\n # 'rrst':predict.RRST_LSTM\n # 'rpnet_h':predict.RH_PNet,\n # 'rpnet_x':predict.RX_PNet,\n # 'rpnet_m':predict.RM_PNet,\n }\n\n if configs.model_name in networks_map:\n\n Network = networks_map[configs.model_name]\n # self.network = Network(self.num_layers, self.num_hidden, configs).to(configs.device)\n self.network = Network(self.num_layers, self.num_hidden, configs).cuda()\n else:\n raise ValueError('Name of network unknown %s' % configs.model_name)\n\n self.optimizer = Adam(self.network.parameters(), lr=configs.lr)\n self.MSE_criterion = nn.MSELoss(size_average=True)\n self.MAE_criterion = nn.L1Loss(size_average=True)\n self.SSIM_criterion = SSIM(size_average=True)\n\n def save(self,ite = None):\n stats = {}\n stats['net_param'] = self.network.state_dict()\n if ite == None:\n checkpoint_path = os.path.join(self.configs.save_dir, 'model.ckpt')\n else:\n checkpoint_path = os.path.join(self.configs.save_dir, 'model_'+str(ite)+'.ckpt')\n torch.save(stats, checkpoint_path)\n print(\"save model to %s\" % checkpoint_path)\n\n def load(self):\n checkpoint_path = os.path.join(self.configs.save_dir, 'model.ckpt')\n stats = torch.load(checkpoint_path)\n self.network.load_state_dict(stats['net_param'])\n print('model has been loaded in',checkpoint_path)\n\n def train(self, frames, mask):\n\n # frames_tensor = torch.FloatTensor(frames).to(self.configs.device)\n # mask_tensor = torch.FloatTensor(mask).to(self.configs.device)\n\n frames_tensor = torch.FloatTensor(frames).cuda()\n mask_tensor = torch.FloatTensor(mask).cuda()\n self.optimizer.zero_grad()\n next_frames = self.network(frames_tensor, mask_tensor)\n loss = self.MSE_criterion(next_frames, frames_tensor[:, 1:])\n # self.MAE_criterion(next_frames, frames_tensor[:, 1:])\n # 0.02*self.SSIM_criterion(next_frames, frames_tensor[:, 1:])\n loss.backward()\n self.optimizer.step()\n return loss.detach().cpu().numpy()\n\n def test(self, frames, mask):\n frames_tensor = torch.FloatTensor(frames).cuda()\n mask_tensor = torch.FloatTensor(mask).cuda()\n next_frames = self.network(frames_tensor, mask_tensor)\n loss = self.MSE_criterion(next_frames, frames_tensor[:, 1:])\n # self.MAE_criterion(next_frames,frames_tensor[:,1:])\n # + 0.02 * self.SSIM_criterion(next_frames, frames_tensor[:, 1:])\n\n return next_frames.detach().cpu().numpy(),loss.detach().cpu().numpy()","sub_path":"core/models/model_factory.py","file_name":"model_factory.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"143030980","text":"import commands\nimport os\nimport logging\n\nfrom error import AuditError\nauditError = AuditError()\n# Import JSON\ntry:\n import json\nexcept ImportError:\n import simplejson as json\n\ndef env():\n COMMAND = '/usr/bin/env'\n return commands.getoutput(COMMAND)\n\ndef envToJson(stats):\n lines = str(stats).split(\"\\n\")\n env = {}\n for line in lines:\n env[line.split(\"=\")[0]] = line.split(\"=\")[1]\n return env\n\ndef main(path, C=None, name='env'):\n auditError.init(name, path)\n data = env()\n # Only valid with python > 2.5 ...... Dammit\n # with open('data.txt', 'w') as outfile:\n # json.dump(data, outfile)\n dataJson = open(os.path.join(path, name +'.json'), 'w')\n dataRaw = open(os.path.join(path, name +'.txt'), 'w')\n try:\n json.dump(envToJson(data), dataJson, indent=4)\n dataRaw.write(data)\n finally:\n dataJson.close()\n dataRaw.close()\n\nif __name__ == \"__main__\":\n main('.')\n","sub_path":"modules/env/env.py","file_name":"env.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"603294845","text":"\n\n#calss header\nclass _ROUTINE():\n\tdef __init__(self,): \n\t\tself.name = \"ROUTINE\"\n\t\tself.definitions = [u'a usual or fixed way of doing things: ', u'a regular series of movements, jokes, or similar things used in a performance: ', u'a part of a computer program that does a particular operation']\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/_routine.py","file_name":"_routine.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"421224568","text":"import math\nimport pylab\nimport numpy\n\n\ndef sinc(x):\n if x != 0:\n return math.sin(x) / x\n else:\n return 1\n\n\ndef plot_sinc():\n # Compute Xs using range or numpy.arange\n # Compute Ys using a loop\n # Call plot\n # Call show\n # remove the next line\n \n X = range(-10, 10)\n Y = []\n for each in X:\n Y.append(sinc(X))\n\nplot_sinc()\n","sub_path":"labs/lab2/plot_lab.py","file_name":"plot_lab.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"513679538","text":"from eemeter.config.yaml_parser import load\n\nfrom eemeter.meter import DataCollection\nfrom eemeter.models import BaseloadHeatingModelParameterType\n\nfrom numpy.testing import assert_allclose\nimport numpy as np\n\nRTOL = 1e-2\nATOL = 1e-2\n\nimport pytest\n\ndef test_cvrmse():\n meter_yaml = \"\"\"\n !obj:eemeter.meter.CVRMSE {\n input_mapping: { \"y\": {}, \"y_hat\": {}, \"params\": {}},\n output_mapping: { \"cvrmse\": {}}\n }\n \"\"\"\n meter = load(meter_yaml)\n\n data_collection = DataCollection(\n y=np.array([12,13,414,12,23,12,32,np.nan]),\n y_hat=np.array([32,12,322,21,22,41,32,np.nan]),\n params=BaseloadHeatingModelParameterType([1,3,4]))\n result = meter.evaluate(data_collection)\n\n assert_allclose(result.get_data(\"cvrmse\").value, 59.79,\n rtol=RTOL, atol=ATOL)\n\ndef test_rmse():\n meter_yaml = \"\"\"\n !obj:eemeter.meter.RMSE {\n input_mapping: { \"y\": {}, \"y_hat\": {} },\n output_mapping: { \"rmse\": {}}\n }\n \"\"\"\n meter = load(meter_yaml)\n\n data_collection = DataCollection(\n y=np.array([12,13,414,12,23,12,32,np.nan]),\n y_hat=np.array([32,12,322,21,22,41,32,np.nan]))\n result = meter.evaluate(data_collection)\n\n assert_allclose(result.get_data(\"rmse\").value, 34.97,\n rtol=RTOL, atol=ATOL)\n\ndef test_r_squared():\n meter_yaml = \"\"\"\n !obj:eemeter.meter.RSquared {\n input_mapping: { \"y\": {}, \"y_hat\": {}},\n output_mapping: { \"r_squared\": {}}\n }\n \"\"\"\n meter = load(meter_yaml)\n\n data_collection = DataCollection(\n y=np.array([12,13,414,12,23,12,32,np.nan]),\n y_hat=np.array([32,12,322,21,22,41,32,np.nan]))\n result = meter.evaluate(data_collection)\n\n assert_allclose(result.get_data(\"r_squared\").value, 0.9276,\n rtol=RTOL, atol=ATOL)\n","sub_path":"tests/test_meter_fitness.py","file_name":"test_meter_fitness.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"554233287","text":"import csv\nimport datetime\nimport json\nimport logging\nimport tempfile\nfrom abc import ABC\n\nimport requests\n\nfrom zoltpy.cdc_io import YYYY_MM_DD_DATE_FORMAT, _parse_value\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef _basic_str(obj):\n \"\"\"\n Handy for writing quick and dirty __str__() implementations.\n \"\"\"\n return obj.__class__.__name__ + ': ' + obj.__repr__()\n\n\nclass ZoltarConnection:\n \"\"\"\n Represents a connection to a Zoltar server. This is an object-oriented interface that may be best suited to zoltpy\n developers. See the `util` module for a name-based non-OOP interface.\n\n A note on URLs: We require a trailing slash ('/') on all URLs. The only exception is the host arg passed to this\n class's constructor. This convention matches Django REST framework one, which is what Zoltar is written in.\n\n Notes:\n - This implementation uses the simple approach of caching the JSON response for resource URLs, but doesn't\n automatically handle their becoming stale, hence the need to call ZoltarResource.refresh().\n \"\"\"\n\n\n def __init__(self, host='https://zoltardata.com'):\n \"\"\"\n :param host: URL of the Zoltar host. should *not* have a trailing '/'\n \"\"\"\n self.host = host\n self.username, self.password = None, None\n self.session = None\n\n\n def __repr__(self):\n return str((self.host, self.session))\n\n\n def __str__(self): # todo\n return _basic_str(self)\n\n\n def authenticate(self, username, password):\n self.username, self.password = username, password\n self.session = ZoltarSession(self)\n\n\n def re_authenticate_if_necessary(self):\n if self.session.is_token_expired():\n logger.debug(f\"re_authenticate_if_necessary(): re-authenticating expired token. host={self.host}\")\n self.authenticate(self.username, self.password)\n\n\n @property\n def projects(self):\n \"\"\"\n The entry point into ZoltarResources.\n\n Returns a list of Projects. NB: A property, but hits the API.\n \"\"\"\n projects_json_list = self.json_for_uri(self.host + '/api/projects/')\n return [Project(self, project_json['url'], project_json) for project_json in projects_json_list]\n\n\n def json_for_uri(self, uri, is_return_json=True, accept='application/json; indent=4'):\n logger.debug(f\"json_for_uri(): {uri!r}\")\n if not self.session:\n raise RuntimeError(\"json_for_uri(): no session. uri={uri}\")\n\n response = requests.get(uri, headers={'Accept': accept,\n 'Authorization': 'JWT {}'.format(self.session.token)})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"json_for_uri(): status code was not 200. uri={uri},\"\n f\"status_code={response.status_code}. text={response.text}\")\n\n return response.json() if is_return_json else response\n\n\nclass ZoltarSession: # internal use\n\n def __init__(self, zoltar_connection):\n super().__init__()\n self.zoltar_connection = zoltar_connection\n self.token = self._get_token()\n\n\n def _get_token(self):\n response = requests.post(self.zoltar_connection.host + '/api-token-auth/',\n {'username': self.zoltar_connection.username,\n 'password': self.zoltar_connection.password})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"get_token(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n return response.json()['token']\n\n\n def is_token_expired(self):\n \"\"\"\n :return: True if my token is expired, and False o/w\n \"\"\"\n # see zoltr: is_token_expired(), token_expiration_date()\n return True # todo fix!\n\n\nclass ZoltarResource(ABC):\n \"\"\"\n An abstract proxy for a Zoltar object at a particular URI including its JSON. All it does is cache JSON from a URI.\n Notes:\n\n - This class and its subclasses are not meant to be directly instantiated by users. Instead the user enters through\n ZoltarConnection.projects and then drills down.\n - Because the JSON is cached, it will become stale after the source object in the server changes, such as when a new\n model is created or a forecast uploaded. This it's the user's responsibility to call `refresh()` as needed.\n - Newly-created instances do *not* refresh by default, for efficiency.\n \"\"\"\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n \"\"\"\n :param zoltar_connection:\n :param uri:\n :param initial_json: optional param that's passed if caller already has JSON from server\n \"\"\"\n self.zoltar_connection = zoltar_connection\n self.uri = uri # *does* include trailing slash\n self._json = initial_json # cached JSON is None if not yet touched. can become stale\n # NB: no self.refresh() call!\n\n\n def __repr__(self):\n \"\"\"\n A default __repr__() that does not hit the API unless my _json has been cached, in which case my _repr_keys\n class var is used to determine which properties to return.\n \"\"\"\n repr_keys = getattr(self, '_repr_keys', None)\n repr_list = [self.__class__.__name__, self.uri, self.id]\n if repr_keys and self._json:\n repr_list.extend([self._json[repr_key] for repr_key in repr_keys\n if repr_key in self._json and self._json[repr_key]])\n return str(tuple(repr_list))\n\n\n @property\n def id(self): # todo rename to not conflict with `id` builtin\n return ZoltarResource.id_for_uri(self.uri)\n\n\n @classmethod\n def id_for_uri(cls, uri):\n \"\"\"\n :return: the trailing integer id from a url structured like: \"http://example.com/api/forecast/71/\" -> 71L\n \"\"\"\n url_split = [split for split in uri.split('/') if split] # drop any empty components, mainly from end\n return int(url_split[-1])\n\n\n @property\n def json(self):\n \"\"\"\n :return: my json as a dict, refreshing if none cached yet\n \"\"\"\n return self._json if self._json else self.refresh()\n\n\n def refresh(self):\n self._json = self.zoltar_connection.json_for_uri(self.uri)\n return self._json\n\n\n def delete(self):\n response = requests.delete(self.uri, headers={'Accept': 'application/json; indent=4',\n 'Authorization': f'JWT {self.zoltar_connection.session.token}'})\n if (response.status_code != 200) and (response.status_code != 204): # HTTP_200_OK, HTTP_204_NO_CONTENT\n raise RuntimeError(f'delete_resource(): status code was not 204: {response.status_code}. {response.text}')\n\n return response\n\n\nclass Project(ZoltarResource):\n \"\"\"\n Represents a Zoltar project, and is the entry point for getting its list of Models.\n \"\"\"\n\n _repr_keys = ('name', 'is_public')\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def name(self):\n return self.json['name']\n\n\n @property\n def models(self):\n \"\"\"\n :return: a list of the Project's Models\n \"\"\"\n models_json_list = self.zoltar_connection.json_for_uri(self.uri + 'models/')\n return [Model(self.zoltar_connection, model_json['url'], model_json) for model_json in models_json_list]\n\n\n @property\n def units(self):\n \"\"\"\n :return: a list of the Project's Units\n \"\"\"\n units_json_list = self.zoltar_connection.json_for_uri(self.uri + 'units/')\n return [Unit(self.zoltar_connection, unit_json['url'], unit_json) for unit_json in units_json_list]\n\n\n @property\n def targets(self):\n \"\"\"\n :return: a list of the Project's Targets\n \"\"\"\n targets_json_list = self.zoltar_connection.json_for_uri(self.uri + 'targets/')\n return [Target(self.zoltar_connection, target_json['url'], target_json) for target_json in targets_json_list]\n\n\n @property\n def timezeros(self):\n \"\"\"\n :return: a list of the Project's TimeZeros\n \"\"\"\n timezeros_json_list = self.zoltar_connection.json_for_uri(self.uri + 'timezeros/')\n return [TimeZero(self.zoltar_connection, timezero_json['url'], timezero_json)\n for timezero_json in timezeros_json_list]\n\n\n @property\n def truth_csv_filename(self):\n \"\"\"\n :return: the Project's truth_csv_filename\n \"\"\"\n # recall the json contains these keys: 'id', 'url', 'project', 'truth_csv_filename', 'truth_updated_at,\n # 'truth_data'\n return self.zoltar_connection.json_for_uri(self.uri + 'truth/')['truth_csv_filename']\n\n\n @property\n def truth_updated_at(self):\n \"\"\"\n :return: the Project's truth_updated_at\n \"\"\"\n # recall the json contains these keys: 'id', 'url', 'project', 'truth_csv_filename', 'truth_updated_at,\n # 'truth_data'\n return self.zoltar_connection.json_for_uri(self.uri + 'truth/')['truth_updated_at']\n\n\n def truth_data(self):\n \"\"\"\n :return: the Project's truth data downloaded as CSV rows with these columns: `timezero`, `unit`, `target`,\n `value`. the header row is included\n \"\"\"\n truth_data_url = self.zoltar_connection.json_for_uri(self.uri + 'truth/')['truth_data']\n truth_data_response = self.zoltar_connection.json_for_uri(truth_data_url, False, 'text/csv')\n decoded_content = truth_data_response.content.decode('utf-8')\n csv_reader = csv.reader(decoded_content.splitlines(), delimiter=',')\n return list(csv_reader)\n\n\n def upload_truth_data(self, truth_csv_fp):\n \"\"\"\n Uploads truth data to this project, deleting existing truth if any.\n\n :param truth_csv_fp: an open truth csv file-like object. the truth CSV file format is documented at\n https://docs.zoltardata.com/\n :return: a Job to use to track the upload\n \"\"\"\n response = requests.post(self.uri + 'truth/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n files={'data_file': truth_csv_fp})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"upload_truth_data(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n job_json = response.json()\n return Job(self.zoltar_connection, job_json['url'])\n\n\n def score_data(self):\n \"\"\"\n :return: the Project's score data as CSV rows with these columns:\n `model`, `timezero`, `season`, `unit`, `target`, plus a column for each score. the header row is included\n \"\"\"\n score_data_url = self.json['score_data']\n score_data_response = self.zoltar_connection.json_for_uri(score_data_url, False, 'text/csv')\n decoded_content = score_data_response.content.decode('utf-8')\n csv_reader = csv.reader(decoded_content.splitlines(), delimiter=',')\n return list(csv_reader)\n\n\n def create_model(self, model_config):\n \"\"\"\n Creates a forecast Model with the passed configuration.\n\n :param model_config: a dict used to initialize the new model. it must contain these fields: ['name',\n 'abbreviation', 'team_name', 'description', 'contributors', 'license', 'notes', 'citation', 'methods',\n 'home_url', 'aux_data_url']\n :return: a Model\n \"\"\"\n # validate model_config\n actual_keys = set(model_config.keys())\n expected_keys = {'name', 'abbreviation', 'team_name', 'description', 'home_url', 'aux_data_url'}\n if actual_keys != expected_keys:\n raise RuntimeError(f\"Wrong keys in 'model_config'. expected={expected_keys}, actual={actual_keys}\")\n\n response = requests.post(f'{self.uri}models/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n json={'model_config': model_config})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"status_code was not 200. status_code={response.status_code}, text={response.text}\")\n\n new_model_json = response.json()\n return Model(self.zoltar_connection, new_model_json['url'], new_model_json)\n\n\n def create_timezero(self, timezero_date, data_version_date=None, is_season_start=False, season_name=''):\n \"\"\"\n Creates a timezero in me with the passed parameters.\n\n :param timezero_date: YYYY-MM-DD DATE FORMAT, e.g., '2018-12-03'\n :param data_version_date: optional. same format as timezero_date\n :param is_season_start: optional boolean indicating season start\n :param season_name: optional season name. required if is_season_start\n :return: the new TimeZero\n \"\"\"\n # validate args\n if not isinstance(_parse_value(timezero_date), datetime.date): # returns a date if valid\n raise RuntimeError(f\"invalid timezero_date={timezero_date}. \"\n f\"was not in the format {YYYY_MM_DD_DATE_FORMAT}\")\n elif data_version_date and (not isinstance(_parse_value(data_version_date), datetime.date)):\n raise RuntimeError(f\"invalid data_version_date={data_version_date}. \"\n f\"was not in the format {YYYY_MM_DD_DATE_FORMAT}\")\n elif is_season_start and not season_name:\n raise RuntimeError(f\"season_name not found but is required when is_season_start is passed\")\n elif not is_season_start and season_name:\n raise RuntimeError(f\"season_name was found but is_season_start was not True\")\n\n # POST. 'timezero_config' args:\n # - required: 'timezero_date', 'data_version_date', 'is_season_start'\n # - optional: 'season_name'\n timezero_config = {'timezero_date': timezero_date,\n 'data_version_date': data_version_date,\n 'is_season_start': is_season_start}\n if is_season_start:\n timezero_config['season_name'] = season_name\n response = requests.post(f'{self.uri}timezeros/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n json={'timezero_config': timezero_config})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"status_code was not 200. status_code={response.status_code}, text={response.text}\")\n\n new_timezero_json = response.json()\n return TimeZero(self.zoltar_connection, new_timezero_json['url'], new_timezero_json)\n\n\n def submit_query(self, query):\n \"\"\"\n Submits a request for the execution of a query of forecasts in this Project.\n\n :param query: a dict as documented at https://docs.zoltardata.com/ . NB: this is a \"raw\" query in that it\n contains IDs and not strings for objects. use utility methods to convert from strings to IDs\n :return: a Job for the query\n \"\"\"\n response = requests.post(self.uri + 'forecast_queries/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n json={'query': query})\n job_json = response.json()\n if response.status_code != 200:\n raise RuntimeError(f\"error submitting query: {job_json['error']}\")\n\n return Job(self.zoltar_connection, job_json['url'])\n\n\n def query_with_ids(self, query):\n \"\"\"\n A convenience function that prepares a query for `submit_query()` in this project by replacing strings with\n database IDs. Replaces these strings:\n\n - \"models\": model_name -> ID\n - \"units\": unit_name -> ID\n - \"targets\": target_name -> ID\n - \"timezeros\" timezero_date in YYYY_MM_DD_DATE_FORMAT-> ID\n\n :param query: as passed to `submit_query()`, but which contains strings and not IDs (ints)\n :return: a copy of `query` that has IDs substituted for strings\n :raises RuntimeError: if any names or timezeros could not be found in this project\n \"\"\"\n new_query = {} # return value. set next\n if 'models' in query:\n query_model_names = query['models']\n models = self.models\n project_model_names = {model.name for model in models}\n project_model_abbrevs = {model.abbreviation for model in models}\n if (not set(query_model_names) <= project_model_names) and \\\n (not set(query_model_names) <= project_model_abbrevs):\n raise RuntimeError(f\"one or more model names or abbreviations were not found in project. \"\n f\"query_model_names={query_model_names}, \"\n f\"project_model_names={project_model_names}, \"\n f\"project_model_abbrevs={project_model_abbrevs}\")\n\n model_ids = [model.id for model in models if model.name in query_model_names\n or model.abbreviation in project_model_abbrevs]\n new_query['models'] = model_ids\n if 'units' in query:\n query_unit_names = query['units']\n units = self.units\n project_unit_names = {unit.name for unit in units}\n if not set(query_unit_names) <= project_unit_names:\n raise RuntimeError(f\"one or more unit names were not found in project. \"\n f\"query_unit_names={query_unit_names}, project_unit_names={project_unit_names}\")\n\n unit_ids = [unit.id for unit in units if unit.name in query_unit_names]\n new_query['units'] = unit_ids\n if 'targets' in query:\n query_target_names = query['targets']\n targets = self.targets\n project_target_names = {target.name for target in targets}\n if not set(query_target_names) <= project_target_names:\n raise RuntimeError(f\"one or more unit names were not found in project. \"\n f\"query_target_names={query_target_names}, \"\n f\"project_target_names={project_target_names}\")\n\n target_ids = [target.id for target in targets if target.name in query_target_names]\n new_query['targets'] = target_ids\n if 'timezeros' in query:\n query_tz_names = query['timezeros']\n timezeros = self.timezeros\n project_tz_names = {timezero.timezero_date for timezero in timezeros}\n if not set(query_tz_names) <= project_tz_names:\n raise RuntimeError(f\"one or more unit names were not found in project. \"\n f\"query_tz_names={query_tz_names}, project_tz_names={project_tz_names}\")\n\n timezero_ids = [timezero.id for timezero in timezeros if timezero.timezero_date in query_tz_names]\n new_query['timezeros'] = timezero_ids\n if 'types' in query:\n new_query['types'] = query['types']\n return new_query\n\n\nclass Model(ZoltarResource):\n \"\"\"\n Represents a Zoltar forecast model, and is the entry point for getting its Forecasts as well as uploading them.\n \"\"\"\n\n _repr_keys = ('name',)\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def name(self):\n return self.json['name']\n\n\n @property\n def abbreviation(self):\n return self.json['abbreviation']\n\n\n @property\n def team_name(self):\n return self.json['team_name']\n\n\n @property\n def description(self):\n return self.json['description']\n\n\n @property\n def contributors(self):\n return self.json['contributors']\n\n\n @property\n def license(self):\n return self.json['license']\n\n\n @property\n def notes(self):\n return self.json['notes']\n\n\n @property\n def citation(self):\n return self.json['citation']\n\n\n @property\n def methods(self):\n return self.json['methods']\n\n\n @property\n def home_url(self):\n return self.json['home_url']\n\n\n @property\n def aux_data_url(self):\n return self.json['aux_data_url']\n\n\n @property\n def forecasts(self):\n \"\"\"\n :return: a list of this Model's Forecasts\n \"\"\"\n forecasts_json_list = self.zoltar_connection.json_for_uri(self.uri + 'forecasts/')\n return [Forecast(self.zoltar_connection, forecast_json['url'], forecast_json)\n for forecast_json in forecasts_json_list]\n\n\n def edit(self, model_config):\n \"\"\"\n Edits this model to have the passed values\n\n :param model_config: a dict used to edit this model. it must contain these fields: ['name',\n 'abbreviation', 'team_name', 'description', 'contributors', 'license', 'notes', 'citation', 'methods',\n 'home_url', 'aux_data_url']\n \"\"\"\n response = requests.put(self.uri,\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n json={'model_config': model_config})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"edit(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n\n def upload_forecast(self, forecast_json, source, timezero_date, notes=''):\n \"\"\"\n Uploads forecast data to this connection.\n\n :param forecast_json: \"JSON IO dict\" to upload. format as documented at https://docs.zoltardata.com/\n :param timezero_date: timezero to upload to YYYY-MM-DD DATE FORMAT\n :param source: source to associate with the uploaded data\n :param notes: optional user notes for the new forecast\n :return: a Job to use to track the upload\n \"\"\"\n self.zoltar_connection.re_authenticate_if_necessary()\n with tempfile.TemporaryFile(\"r+\") as forecast_json_fp:\n json.dump(forecast_json, forecast_json_fp)\n forecast_json_fp.seek(0)\n response = requests.post(self.uri + 'forecasts/',\n headers={'Authorization': f'JWT {self.zoltar_connection.session.token}'},\n data={'timezero_date': timezero_date, 'notes': notes},\n files={'data_file': (source, forecast_json_fp, 'application/json')})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"upload_forecast(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n job_json = response.json()\n return Job(self.zoltar_connection, job_json['url'])\n\n\nclass Forecast(ZoltarResource):\n _repr_keys = ('source', 'created_at', 'notes')\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n def delete(self):\n \"\"\"\n Does the usual delete, but returns a Job for it. (Deleting a forecasts is an enqueued operation.)\n \"\"\"\n response = super().delete()\n job_json = response.json()\n return Job(self.zoltar_connection, job_json['url'], job_json)\n\n\n @property\n def timezero(self):\n return TimeZero(self.zoltar_connection, self.json['time_zero']['url'], self.json['time_zero'])\n\n\n @property\n def source(self):\n return self.json['source']\n\n\n @property\n def created_at(self):\n return self.json['created_at']\n\n\n @property\n def notes(self):\n return self.json['notes']\n\n\n def data(self):\n \"\"\"\n :return: this forecast's data as a dict in the \"JSON IO dict\" format accepted by\n utils.forecast.load_predictions_from_json_io_dict()\n \"\"\"\n data_uri = self.json['forecast_data']\n response = requests.get(data_uri,\n headers={'Authorization': 'JWT {}'.format(self.zoltar_connection.session.token)})\n if response.status_code != 200: # HTTP_200_OK\n raise RuntimeError(f\"data(): status code was not 200. status_code={response.status_code}. \"\n f\"text={response.text}\")\n\n return json.loads(response.content.decode('utf-8'))\n\n\nclass Unit(ZoltarResource):\n _repr_keys = ('name',)\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def name(self):\n return self.json['name']\n\n\nclass Target(ZoltarResource):\n _repr_keys = ('name', 'type', 'is_step_ahead', 'step_ahead_increment', 'unit')\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def name(self):\n return self.json['name']\n\n\n @property\n def type(self):\n return self.json['type']\n\n\n @property\n def is_step_ahead(self):\n return self.json['is_step_ahead']\n\n\n @property\n def step_ahead_increment(self):\n return self.json['step_ahead_increment']\n\n\n @property\n def unit(self):\n return self.json['unit']\n\n\nclass TimeZero(ZoltarResource):\n _repr_keys = ('timezero_date', 'data_version_date', 'is_season_start', 'season_name')\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n @property\n def timezero_date(self):\n return self.json['timezero_date']\n\n\n @property\n def data_version_date(self):\n return self.json['data_version_date']\n\n\n @property\n def is_season_start(self):\n return self.json['is_season_start']\n\n\n @property\n def season_name(self):\n return self.json['season_name']\n\n\nclass Job(ZoltarResource):\n STATUS_ID_TO_STR = {\n 0: 'PENDING',\n 1: 'CLOUD_FILE_UPLOADED',\n 2: 'QUEUED',\n 3: 'CLOUD_FILE_DOWNLOADED',\n 4: 'SUCCESS',\n 5: 'FAILED',\n }\n\n\n def __init__(self, zoltar_connection, uri, initial_json=None):\n super().__init__(zoltar_connection, uri, initial_json)\n\n\n def __repr__(self):\n return str((self.__class__.__name__, self.uri, self.id, self.status_as_str)) if self._json \\\n else super().__repr__()\n\n\n @property\n def input_json(self):\n return self.json['input_json']\n\n\n @property\n def output_json(self):\n return self.json['output_json']\n\n\n @property\n def status_as_str(self):\n status_int = self.json['status']\n return Job.STATUS_ID_TO_STR[status_int]\n\n\n def created_forecast(self):\n \"\"\"\n A helper function that returns the newly-uploaded Forecast. Should only be called on Jobs that are the results\n of an uploaded forecast via `Model.upload_forecast()`.\n\n :return: the new Forecast that this uploaded created, or None if the Job was for a non-forecast\n upload.\n \"\"\"\n if 'forecast_pk' not in self.output_json:\n return None\n\n forecast_pk = self.output_json['forecast_pk']\n forecast_uri = self.zoltar_connection.host + f'/api/forecast/{forecast_pk}/'\n return Forecast(self.zoltar_connection, forecast_uri)\n\n\n def download_data(self):\n \"\"\"\n :return: the Job's data as CSV rows with columns matching that of `csv_rows_from_json_io_dict()`. Should only be\n called on Jobs that are the results of a project forecast query via `Project.submit_query()`.\n See docs at https://docs.zoltardata.com/ .\n \"\"\"\n job_data_url = f\"{self.uri}data/\"\n score_data_response = self.zoltar_connection.json_for_uri(job_data_url, False, 'text/csv')\n decoded_content = score_data_response.content.decode('utf-8')\n csv_reader = csv.reader(decoded_content.splitlines(), delimiter=',')\n return list(csv_reader)\n","sub_path":"zoltpy/connection.py","file_name":"connection.py","file_ext":"py","file_size_in_byte":28352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"441337355","text":"import textwrap\n\nimport dengraph.graphs.graph_io\nimport dengraph.distance\n\nfrom dengraph_unittests.utility import unittest\n\nfrom dengraph.distances.delta_distance import DeltaDistance, IncrementalDeltaDistance\nfrom dengraph.graphs.distance_graph import DistanceGraph\nfrom dengraph.dengraphvio import DenGraphVIO\n\n\nclass TestDenGraphVIO(unittest.TestCase):\n def test_creation(self):\n io_graph = DenGraphVIO(\n base_graph=DistanceGraph(\n nodes=[1, 2, 3, 4, 5, 6],\n distance=DeltaDistance(),\n symmetric=True\n ),\n cluster_distance=5,\n core_neighbours=5\n )\n self.assertIsNotNone(io_graph)\n\n literal = textwrap.dedent(\"\"\"\n 1,2,3,4,5,6\n 0,1,1,1,1,1\n 1,0,1,1,1,1\n 1,1,0,1,1,1\n 1,1,1,0,1,1\n 1,1,1,1,0,1\n 1,1,1,1,1,0\n \"\"\".strip())\n with self.assertRaises(dengraph.distance.NoDistanceSupport):\n io_graph = DenGraphVIO(\n base_graph=dengraph.graphs.graph_io.csv_graph_reader(literal.splitlines(), symmetric=True),\n cluster_distance=5,\n core_neighbours=5\n )\n\n def test_simple(self):\n io_graph = DenGraphVIO(\n base_graph=DistanceGraph(\n nodes=[1, 2, 3, 4, 5, 6],\n distance=DeltaDistance(),\n symmetric=True\n ),\n cluster_distance=5,\n core_neighbours=5\n )\n _, distance = next(io_graph.probe(1))\n self.assertEqual(2.5, distance)\n io_graph[7] = {}\n _, distance = next(io_graph.probe(1))\n self.assertEqual(3.0, distance)\n\n def test_simple_incremental(self):\n io_graph = DenGraphVIO(\n base_graph=DistanceGraph(\n nodes=[1, 2, 3, 4, 5, 6],\n distance=IncrementalDeltaDistance(),\n symmetric=True\n ),\n cluster_distance=5,\n core_neighbours=5\n )\n cluster, base_distance = next(io_graph.probe(1))\n for i in range(1, 4):\n cluster, current_distance = next(io_graph.probe(1+i))\n self.assertEqual(current_distance, io_graph.update_probe(1, base_distance, cluster))\n base_distance = current_distance\n","sub_path":"dengraph_unittests/test_dengraphvio.py","file_name":"test_dengraphvio.py","file_ext":"py","file_size_in_byte":2308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"63764934","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nVoid = [0,0,0] # gray\nGrass = [245,230,15] # yellow\nDecidous = [225,27,27] # red\nConifers = [60,200,60] # green\nNo_Forest = [30,90,215] # blue\n\nDSET_MEAN = [0.41189489566336, 0.4251328133025, 0.4326707089857]\nDSET_STD = [0.27413549931506, 0.28506257482912, 0.28284674400252]\n\nlabel_colours = np.array([Void, Grass, Decidous, Conifers, No_Forest])\n\n\ndef view_annotated(tensor, plot=True):\n temp = tensor.numpy()\n r = temp.copy()\n g = temp.copy()\n b = temp.copy()\n for l in range(0,11):\n r[temp==l]=label_colours[l,0]\n g[temp==l]=label_colours[l,1]\n b[temp==l]=label_colours[l,2]\n\n rgb = np.zeros((temp.shape[0], temp.shape[1], 3))\n rgb[:,:,0] = (r/255.0)#[:,:,0]\n rgb[:,:,1] = (g/255.0)#[:,:,1]\n rgb[:,:,2] = (b/255.0)#[:,:,2]\n if plot:\n plt.imshow(rgb)\n plt.show()\n else:\n return rgb\n\ndef decode_image(tensor):\n inp = tensor.numpy().transpose((1, 2, 0))\n #mean = np.array(DSET_MEAN)\n #std = np.array(DSET_STD)\n #inp = std * inp + mean\n return inp\n\ndef view_image(tensor):\n inp = decode_image(tensor)\n inp = np.clip(inp, 0, 1)\n plt.imshow(inp)\n plt.show()\n","sub_path":"deep_learing/fc_densenet/utils/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"123108826","text":"from zoundry.appframework.constants import IZAppServiceIDs\r\nfrom zoundry.appframework.global_services import getApplicationModel\r\nfrom zoundry.appframework.messages import _extstr\r\nfrom zoundry.appframework.ui.dialogs.bgtaskprogressdialog import ZBackgroundTaskProgressDialog\r\nfrom zoundry.appframework.ui.dialogs.feedbackdialog import ZFeedbackDialog\r\nimport wx\r\n\r\n# ------------------------------------------------------------------------------\r\n# Feedback utility class - used to share code between various places that need\r\n# show the send feedback dialog.\r\n# ------------------------------------------------------------------------------\r\nclass ZFeedbackUtil:\r\n\r\n def doFeedback(self, parent, subject = None, details = None):\r\n feedback = None\r\n\r\n # Open the feedback dialog\r\n dialog = ZFeedbackDialog(parent)\r\n if subject is not None:\r\n dialog.setSubject(subject)\r\n if details is not None:\r\n dialog.setDetails(details)\r\n if dialog.ShowModal() == wx.ID_OK:\r\n feedback = dialog.getFeedback()\r\n dialog.Destroy()\r\n\r\n # If the resulting feedback is not None, then initiate the\r\n # feedback (hit the Zoundry endpoint) and display the result\r\n # as a background task in the bg task dialog.\r\n if feedback is not None:\r\n feedbackService = getApplicationModel().getService(IZAppServiceIDs.FEEDBACK_SERVICE_ID)\r\n bgTask = feedbackService.sendFeedback(feedback)\r\n if bgTask is not None:\r\n title = _extstr(u\"feedbackutil.SendingFeedback\") #$NON-NLS-1$\r\n description = _extstr(u\"feedbackutil.SendingFeedbackMsg\") #$NON-NLS-1$\r\n imagePath = u\"images/dialogs/bgtask/header_image.png\" #$NON-NLS-1$\r\n dialog = ZBackgroundTaskProgressDialog(parent, bgTask, title, description, imagePath)\r\n dialog.ShowModal()\r\n dialog.Destroy()\r\n # end doFeedback()\r\n\r\n# end ZFeedbackUtil\r\n","sub_path":"src/python/zoundry/appframework/ui/util/feedbackutil.py","file_name":"feedbackutil.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"510711569","text":"import zmq\r\n\r\ncontext = zmq.Context()\r\nsocket = context.socket(zmq.REP)\r\n\r\nsocket.bind(\"tcp://127.0.0.1:5555\")\r\n\r\nwhile True:\r\n message = socket.recv()\r\n socket.send(message)\r\n\r\n if message == b'q':\r\n break\r\n\r\n","sub_path":"pyzmq/client_server_speed_test/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"36123313","text":"\n# este es un helper que creé para tomar los records de sql que vienen en una lista y convertirlos en\n# un diccionario\n# tambien funciona lara lista de records\n\n\ndef record_to_py(sql_record, keys_array, ignoreID=True):\n if ignoreID:\n sql_record = sql_record[1:]\n\n dictionary = {}\n\n for i, k in enumerate(keys_array):\n dictionary[k] = sql_record[i]\n\n return dictionary\n\n\ndef records_to_py(sql_record_arr, keys_array, ignoreID=True):\n my_list = []\n for record in sql_record_arr:\n my_list.append(record_to_py(record, keys_array, ignoreID))\n\n return my_list\n","sub_path":"app/api/helpers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"446014556","text":"import cv2\nimport numpy as np\nimport json\nimport matplotlib.image as mpimg\n\nfrom pyforms import BaseWidget\nfrom pyforms.Controls import ControlButton\nfrom pyforms.Controls import ControlSlider\nfrom pyforms.Controls import ControlImage\nfrom utils import abs_sobel_thresh, mag_thresh, dir_threshold, create_binary_image\n\nimport pyforms\n\n\nclass ThresholdingParameter(BaseWidget):\n def __init__(self):\n super(ThresholdingParameter, self).__init__('Thresholding tool')\n\n with open('parameters.json', 'r') as f:\n params_values = json.load(f)\n\n self._params_values = params_values\n\n params = params_values['adjusted']\n\n # Definition of the forms fields\n self.sobel_kernel = ControlSlider('sobel_kernel', minimum=1, maximum=15, default=int(params['sobel_kernel']))\n\n self.sobel_x_thresh_min = ControlSlider('sobel_x_thresh_min', minimum=1, maximum=255, default=int(params['sobel_x_thresh_min']))\n self.sobel_x_thresh_max = ControlSlider('sobel_x_thresh_max', minimum=1, maximum=255, default=int(params['sobel_x_thresh_max']))\n self.sobel_y_thresh_min = ControlSlider('sobel_y_thresh_min', minimum=1, maximum=255, default=int(params['sobel_y_thresh_min']))\n self.sobel_y_thresh_max = ControlSlider('sobel_y_thresh_max', minimum=1, maximum=255, default=int(params['sobel_y_thresh_max']))\n\n self.mag_kernel = ControlSlider('mag_kernel', minimum=1, maximum=15, default=int(params['mag_kernel']))\n self.mag_thresh_min = ControlSlider('mag_thresh_min', minimum=1, maximum=255, default=int(params['mag_thresh_min']))\n self.mag_thresh_max = ControlSlider('mag_thresh_max', minimum=1, maximum=255, default=int(params['mag_thresh_max']))\n\n self.dir_kernel = ControlSlider('dir_kernel', minimum=1, maximum=15, default=int(params['dir_kernel']))\n self.dir_thresh_min = ControlSlider('dir_thresh_min', minimum=0, maximum=int((np.pi / 2) * 10),\n default=int(float(params['dir_thresh_min']) * 10))\n self.dir_thresh_max = ControlSlider('dir_thresh_max', minimum=1, maximum=int((np.pi / 2) * 10),\n default=int(float(params['dir_thresh_max']) * 10))\n\n self.sat_thresh_min = ControlSlider('sat_thresh_min', minimum=1, maximum=255, default=int(params['sat_thresh_min']))\n self.sat_thresh_max = ControlSlider('sat_thresh_max', minimum=1, maximum=255, default=int(params['sat_thresh_max']))\n\n self._image = ControlImage()\n self._runbutton = ControlButton('Run')\n\n # Define the function that will be called when a file is selected\n self.sobel_kernel.changed_event = self.__sobel_kernelEvent\n self.sobel_x_thresh_min.changed_event = self.__sobel_x_thresh_minEvent\n self.sobel_x_thresh_max.changed_event = self.__sobel_x_thresh_maxEvent\n self.sobel_y_thresh_min.changed_event = self.__sobel_y_thresh_minEvent\n self.sobel_y_thresh_max.changed_event = self.__sobel_y_thresh_maxEvent\n self.mag_kernel.changed_event = self.__mag_kernelEvent\n self.mag_thresh_min.changed_event = self.__mag_thresh_minEvent\n self.mag_thresh_max.changed_event = self.__mag_thresh_maxEvent\n self.dir_kernel.changed_event = self.__dir_kernelEvent\n self.dir_thresh_min.changed_event = self.__dir_thresh_minEvent\n self.dir_thresh_max.changed_event = self.__dir_thresh_maxEvent\n self.sat_thresh_min.changed_event = self.__sat_thresh_minEvent\n self.sat_thresh_max.changed_event = self.__sat_thresh_maxEvent\n\n # Define the event that will be called when the run button is processed\n self._runbutton.value = self.__runEvent\n\n self.input_image = cv2.imread('test_images/test1.jpg')\n self.input_image = cv2.cvtColor(self.input_image, cv2.COLOR_BGR2RGB)\n\n cv2.imwrite(\"a.jpg\", self.input_image)\n\n self._binary = None\n\n # Define the event called before showing the image in the player\n # self._player.processFrame = self.__processFrame\n\n # Define the organization of the Form Controls\n self.formset = [\n ('sobel_kernel',\n 'sobel_x_thresh_min',\n 'sobel_x_thresh_max'),\n ('sobel_y_thresh_min',\n 'sobel_y_thresh_max',\n 'mag_kernel'),\n ('mag_thresh_min',\n 'mag_thresh_max',\n 'dir_kernel'),\n ('dir_thresh_min',\n 'dir_thresh_max',\n 'sat_thresh_min',\n 'sat_thresh_max'), '_image',\n ('_runbutton')\n ]\n\n def init_form(self, parse=True):\n super(ThresholdingParameter, self).init_form()\n\n self.process_video()\n\n def __sobel_kernelEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n if self.sobel_kernel.value % 2 == 1:\n self.process_video()\n\n def __sobel_x_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sobel_x_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sobel_y_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sobel_y_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __mag_kernelEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n if self.mag_kernel.value % 2 == 1:\n self.process_video()\n\n def __mag_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __mag_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __dir_kernelEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n if self.dir_kernel.value % 2 == 1:\n self.process_video()\n\n def __dir_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __dir_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sat_thresh_minEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def __sat_thresh_maxEvent(self):\n \"\"\"\n When the videofile is selected instanciate the video in the player\n \"\"\"\n self.process_video()\n\n def _write_image(self, img):\n mpimg.imsave('out.jpg', img)\n\n def process_video(self):\n test_image = self.input_image\n\n sobel_kernel = self.sobel_kernel.value\n sobel_x_thresh_min = self.sobel_x_thresh_min.value\n sobel_x_thresh_max = self.sobel_x_thresh_max.value\n sobel_y_thresh_min = self.sobel_y_thresh_min.value\n sobel_y_thresh_max = self.sobel_y_thresh_max.value\n\n mag_kernel = self.mag_kernel.value\n mag_thresh_min = self.mag_thresh_min.value\n mag_thresh_max = self.mag_thresh_max.value\n dir_kernel = self.dir_kernel.value\n dir_thresh_min = self.dir_thresh_min.value / 10\n dir_thresh_max = self.dir_thresh_max.value / 10\n sat_thresh_min = self.sat_thresh_min.value\n sat_thresh_max = self.sat_thresh_max.value\n\n # gradient_threshold = threshold_image(test_image, ksize=sobel_kernel,\n # gradx_thresh=(sobel_x_thresh_min, sobel_x_thresh_max),\n # grady_thresh=(sobel_y_thresh_min, sobel_y_thresh_max),\n # magnitude_thresh=(mag_thresh_min, mag_thresh_max),\n # dir_thresh=(dir_thresh_min, dir_thresh_max))\n\n ksize = sobel_kernel\n\n # Apply each of the thresholding functions\n gradx = abs_sobel_thresh(test_image, orient='x', sobel_kernel=ksize, thresh=(sobel_x_thresh_min, sobel_x_thresh_max))\n grady = abs_sobel_thresh(test_image, orient='y', sobel_kernel=ksize, thresh=(sobel_y_thresh_min, sobel_y_thresh_max))\n mag_binary = mag_thresh(test_image, sobel_kernel=ksize, thresh=(mag_thresh_min, mag_thresh_max))\n dir_binary = dir_threshold(test_image, sobel_kernel=ksize, thresh=(dir_thresh_min, dir_thresh_max))\n\n gradient_threshold = np.zeros_like(dir_binary)\n # gradient_threshold[(gradx == 1)] = 1\n gradient_threshold[((gradx == 1) & (grady == 1)) | ((dir_binary == 1) & (mag_binary == 1))] = 1\n\n image_hsl = cv2.cvtColor(test_image, cv2.COLOR_RGB2HLS)\n s_channel = image_hsl[:, :, 2]\n color_threshold = np.zeros_like(s_channel)\n color_threshold[(s_channel >= sat_thresh_min) & (s_channel <= sat_thresh_max)] = 1\n\n color_threshold = create_binary_image(test_image)\n binary = np.zeros_like(gradient_threshold)\n binary[(color_threshold == 1) | (gradient_threshold == 1)] = 1\n\n # binary = np.zeros_like(gradient_threshold)\n # binary[(color_threshold == 1) | (gradient_threshold == 1)] = 1\n # binary[(gradient_threshold == 1)] = 1\n\n self._write_image(binary)\n\n self._binary = cv2.imread('out.jpg', 0)\n\n print('Created image')\n\n self._image.value = self._binary\n self._image.repaint()\n\n def __runEvent(self):\n \"\"\"\n After setting the best parameters run the full algorithm\n \"\"\"\n sobel_kernel = self.sobel_kernel.value\n sobel_x_thresh_min = self.sobel_x_thresh_min.value\n sobel_x_thresh_max = self.sobel_x_thresh_max.value\n sobel_y_thresh_min = self.sobel_y_thresh_min.value\n sobel_y_thresh_max = self.sobel_y_thresh_max.value\n\n mag_kernel = self.mag_kernel.value\n mag_thresh_min = self.mag_thresh_min.value\n mag_thresh_max = self.mag_thresh_max.value\n dir_kernel = self.dir_kernel.value\n dir_thresh_min = self.dir_thresh_min.value / 10\n dir_thresh_max = self.dir_thresh_max.value / 10\n sat_thresh_min = self.sat_thresh_min.value\n sat_thresh_max = self.sat_thresh_max.value\n\n values = self._params_values\n values['adjusted'] = {\n \"sobel_kernel\": sobel_kernel,\n \"mag_kernel\": mag_kernel,\n \"dir_kernel\": dir_kernel,\n \"sobel_x_thresh_min\": sobel_x_thresh_min,\n \"sobel_x_thresh_max\": sobel_x_thresh_max,\n \"sobel_y_thresh_min\": sobel_y_thresh_min,\n \"sobel_y_thresh_max\": sobel_y_thresh_max,\n \"mag_thresh_min\": mag_thresh_min,\n \"mag_thresh_max\": mag_thresh_max,\n \"dir_thresh_min\": dir_thresh_min,\n \"dir_thresh_max\": dir_thresh_max,\n \"sat_thresh_min\": sat_thresh_min,\n \"sat_thresh_max\": sat_thresh_max\n }\n\n with open('parameters.json', 'w') as f:\n json.dump(values, f)\n\n self._params_values = values\n\n if self._binary is not None:\n cv2.imwrite('binary.jpg', self._binary)\n\n\nif __name__ == \"__main__\":\t pyforms.start_app(ThresholdingParameter)","sub_path":"ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":11637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"436510726","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom .functions import send_message,view_message,check_active_livechat\n\nfrom django.core.exceptions import PermissionDenied\nfrom django.contrib import messages\nimport pytchat \n\ndef enter_url(request):\n if request.user.is_authenticated:\n return render(request, \"enter_url.html\")\n else:\n raise PermissionDenied()\n\ndef retrieveURL(request):\n if request.user.is_authenticated:\n title = \"\"\n context = {}\n if request.method == \"POST\":\n title = str(request.POST.get('URL'))\n if title == '':\n messages.warning(request, 'Please enter url !')\n return render(request, 'enter_url.html')\n print(title)\n print(isinstance(title, str))\n livechatstatus = check_active_livechat(title,request)\n videoDetails = {'title':title}\n context = {'title':title,'livechatstatus':livechatstatus}\n return render(request, \"viewsend.html\", context)\n else:\n raise PermissionDenied()\n \n","sub_path":"final_proto/final_proto_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"413727249","text":"#!/usr/bin/env python\nimport argparse as ap\nimport networkx as nx\nimport matplotlib.pyplot as plt\n\nparser = ap.ArgumentParser()\nparser.add_argument('-i', '--input', type=str)\nparser.add_argument('-o', '--output', type=str)\nparser.add_argument('--solid-dash', action='store_true')\nargs = parser.parse_args()\n\nG = nx.read_edgelist(args.input)\npos = nx.spring_layout(G)\nnx.draw_networkx_nodes(G, pos, G.nodes(), node_color='royalblue')\nif args.solid_dash:\n tree_edge = [\n (v, str(min(map(int, G.neighbors(v)))))\n for v in G.nodes_iter() if v > 1\n ]\n cycle_edge = list(set(G.edges()).difference(set(tree_edge)))\n nx.draw_networkx_edges(G, pos, tree_edge, style='solid')\n nx.draw_networkx_edges(G, pos, cycle_edge, style='dashed')\nelse:\n nx.draw_networkx_edges(G, pos, G.edges(), style='solid')\nnx.draw_networkx_labels(G, pos, dict(zip(G.nodes(), G.nodes())))\nplt.axis('off')\nplt.savefig(args.output, bbox_inches='tight')\n\n","sub_path":"docs/res/graph/elist2svg.py","file_name":"elist2svg.py","file_ext":"py","file_size_in_byte":950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"17739412","text":"#!/usr/bin/env python\n\nimport sys, os, subprocess, string, re\nfrom ROOT import *\nfrom array import array\n\n\ngROOT.SetBatch(kTRUE);\ngStyle.SetOptStat(0)\ngStyle.SetOptTitle(0)\ngStyle.SetTitleFont(42, \"XYZ\")\ngStyle.SetTitleSize(0.06, \"XYZ\")\ngStyle.SetLabelFont(42, \"XYZ\")\ngStyle.SetLabelSize(0.05, \"XYZ\")\ngStyle.SetCanvasBorderMode(0)\ngStyle.SetFrameBorderMode(0)\ngStyle.SetCanvasColor(kWhite)\ngStyle.SetPadTickX(1)\ngStyle.SetPadTickY(1)\ngStyle.SetPadLeftMargin(0.15)\ngStyle.SetPadRightMargin(0.05)\ngStyle.SetPadTopMargin(0.05)\ngStyle.SetPadBottomMargin(0.15)\ngROOT.ForceStyle()\n\nmasses = array('d')\nxs_obs_limits = array('d')\nxs_exp_limits = array('d')\nmasses_exp = array('d')\nxs_exp_limits_1sigma = array('d')\nxs_exp_limits_1sigma_up = array('d')\nxs_exp_limits_2sigma = array('d')\nxs_exp_limits_2sigma_up = array('d')\n\nmass_start = 300\nmass_step = 100\nsteps = 7\n\nplot_exp = True\n\n########################################################\n## Uncomment this part if running the limit code\n\n\n#### for running the limit code\n##for i in range(0,steps+1):\n\n ##mass = mass_start + float(i)*mass_step\n\n ##masses.append(mass)\n ##masses_exp.append(mass)\n\n ##cmd = \"./stats \" + str(mass)\n ##print \"Running: \" + cmd\n ##proc = subprocess.Popen( cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT )\n ##output = proc.communicate()[0]\n ##if proc.returncode != 0:\n ##print output\n ##sys.exit(1)\n ###print output\n\n ##outputlines = output.split(\"\\n\")\n\n ##for line in outputlines:\n ##if re.search(\"observed bound =\", line):\n ##xs_obs_limits.append(float(line.split()[6]))\n ##if plot_exp:\n ##if re.search(\"median:\", line):\n ##xs_exp_limits.append(float(line.split()[1]))\n ##if re.search(\"1 sigma band:\", line):\n ##xs_exp_limits_1sigma.append(float(line.split()[4]))\n ##xs_exp_limits_1sigma_up.append(float(line.split()[6]))\n ##if re.search(\"2 sigma band:\", line):\n ##xs_exp_limits_2sigma.append(float(line.split()[4]))\n ##xs_exp_limits_2sigma_up.append(float(line.split()[6]))\n\n### for reading the limit code log files\n#for i in range(0,steps+1):\n\n #mass = mass_start + i*mass_step\n\n #masses.append(float(mass))\n #masses_exp.append(float(mass))\n\n #log_dir = ('logs_obs_exp' if plot_exp else 'logs_obs')\n\n #log_file = open(log_dir + \"/stats_\" + str(int(mass)) + \".log\",'r')\n #outputlines = log_file.readlines()\n #log_file.close()\n\n #for line in outputlines:\n #if re.search(\"observed bound =\", line):\n #xs_obs_limits.append(float(line.split()[6]))\n #if plot_exp:\n #if re.search(\"median:\", line):\n #xs_exp_limits.append(float(line.split()[1]))\n #if re.search(\"1 sigma band:\", line):\n #xs_exp_limits_1sigma.append(float(line.split()[4]))\n #xs_exp_limits_1sigma_up.append(float(line.split()[6]))\n #if re.search(\"2 sigma band:\", line):\n #xs_exp_limits_2sigma.append(float(line.split()[4]))\n #xs_exp_limits_2sigma_up.append(float(line.split()[6]))\n\n#if plot_exp:\n #for i in range(0,len(masses)):\n #masses_exp.append( masses[len(masses)-i-1] )\n #xs_exp_limits_1sigma.append( xs_exp_limits_1sigma_up[len(masses)-i-1] )\n #xs_exp_limits_2sigma.append( xs_exp_limits_2sigma_up[len(masses)-i-1] )\n\n\n#print \"masses:\"\n#print masses\n#print \"xs_obs_limits:\"\n#print xs_obs_limits\n#print \"xs_exp_limits:\"\n#print xs_exp_limits\n#print \"\"\n#print \"masses_exp:\"\n#print masses_exp\n#print \"xs_exp_limits_1sigma:\"\n#print xs_exp_limits_1sigma\n#print \"xs_exp_limits_2sigma:\"\n#print xs_exp_limits_2sigma\n\n##\n########################################################\n\n########################################################\n## Comment out this part if running the limit code\n\nif plot_exp:\n masses = array('d', [300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0])\n xs_obs_limits = array('d', [39.3249, 1.3241799999999999, 0.70614600000000005, 4.4668999999999999, 1.87497, 1.04667, 0.37109500000000001, 0.092092099999999996])\n xs_exp_limits = array('d', [7.3874500000000003, 4.16594, 2.5205000000000002, 1.7962, 1.17222, 0.84475299999999998, 0.65692600000000001, 0.42596200000000001])\nelse:\n masses = array('d', [300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0])\n xs_obs_limits = array('d', [39.380800000000001, 1.2964599999999999, 0.68032400000000004, 4.4672000000000001, 1.86924, 1.05078, 0.35594799999999999, 0.088954400000000003])\n\nmasses_exp = array('d', [300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 1000.0, 1000.0, 900.0, 800.0, 700.0, 600.0, 500.0, 400.0, 300.0])\nxs_exp_limits_1sigma = array('d', [3.17753, 1.50461, 1.032, 0.81818000000000002, 0.547682, 0.43849399999999999, 0.33072000000000001, 0.24565100000000001, 0.84676700000000005, 1.3159799999999999, 1.6796899999999999, 2.65605, 3.7145700000000001, 6.5505100000000001, 13.477499999999999, 18.206700000000001])\nxs_exp_limits_2sigma = array('d', [2.00014, 0.81118199999999996, 0.58127700000000004, 0.49383100000000002, 0.28355999999999998, 0.25376500000000002, 0.19730700000000001, 0.133491, 1.5154399999999999, 1.93604, 2.3307500000000001, 4.5853200000000003, 6.2245100000000004, 9.7461699999999993, 20.569600000000001, 35.542400000000001])\n\n##\n########################################################\n\nif plot_exp:\n graph_exp_2sigma = TGraph(len(masses_exp),masses_exp,xs_exp_limits_2sigma)\n graph_exp_2sigma.SetFillColor(kYellow)\n graph_exp_2sigma.GetXaxis().SetTitle(\"Resonance Mass [GeV]\")\n graph_exp_2sigma.GetYaxis().SetTitle(\"#sigma#timesBR(X#rightarrowjj)#timesA [pb]\")\n graph_exp_2sigma.GetYaxis().SetRangeUser(1e-02,1e+03)\n graph_exp_2sigma.GetXaxis().SetNdivisions(1005)\n\n graph_exp_1sigma = TGraph(len(masses_exp),masses_exp,xs_exp_limits_1sigma)\n graph_exp_1sigma.SetFillColor(kGreen+1)\n\n graph_exp = TGraph(len(masses),masses,xs_exp_limits)\n #graph_exp.SetMarkerStyle(24)\n graph_exp.SetLineWidth(2)\n graph_exp.SetLineStyle(2)\n graph_exp.SetLineColor(4)\n\ngraph_obs = TGraph(len(masses),masses,xs_obs_limits)\ngraph_obs.SetMarkerStyle(20)\ngraph_obs.SetLineWidth(2)\n#graph_obs.SetLineStyle(1)\ngraph_obs.SetLineColor(1)\ngraph_obs.GetXaxis().SetTitle(\"Resonance Mass [GeV]\")\ngraph_obs.GetYaxis().SetTitle(\"#sigma#timesBR(X#rightarrowjj)#timesA [pb]\")\ngraph_obs.GetYaxis().SetRangeUser(1e-02,1e+03)\ngraph_obs.GetXaxis().SetNdivisions(1005)\n\n\nc = TCanvas(\"c\", \"\",800,800)\nc.cd()\n\nif plot_exp:\n graph_exp_2sigma.Draw(\"AF\")\n graph_exp_1sigma.Draw(\"F\")\n graph_exp.Draw(\"L\")\n graph_obs.Draw(\"LP\")\nelse:\n graph_obs.Draw(\"ALP\")\n\nlegend = TLegend(.50,.63,.80,.76)\nlegend.SetBorderSize(0)\nlegend.SetFillColor(0)\nlegend.SetFillStyle(0)\nlegend.SetTextFont(42)\nlegend.SetTextSize(0.03)\nlegend.SetHeader('95% CL Upper Limits (stat. only)')\nlegend.AddEntry(graph_obs,\"Observed\",\"lp\")\nif plot_exp:\n legend.AddEntry(graph_exp,\"Expected\",\"lp\")\nlegend.Draw()\n\nl1 = TLatex()\nl1.SetTextAlign(12)\nl1.SetTextFont(42)\nl1.SetNDC()\nl1.SetTextSize(0.04)\nl1.SetTextSize(0.04)\nl1.DrawLatex(0.18,0.40, \"CMS Preliminary\")\nl1.DrawLatex(0.18,0.32, \"#intLdt = 19 fb^{-1}\")\nl1.DrawLatex(0.19,0.27, \"#sqrt{s} = 8 TeV\")\n\n\ngPad.RedrawAxis();\n\nc.SetLogy()\nif plot_exp:\n c.SaveAs('xs_limit_obs_exp_DijetScouting_Run1_8TeV.eps')\nelse:\n c.SaveAs('xs_limit_obs_DijetScouting_Run1_8TeV.eps')\n","sub_path":"plots/xs_limit_DijetScouting_Run1_8TeV.py","file_name":"xs_limit_DijetScouting_Run1_8TeV.py","file_ext":"py","file_size_in_byte":7185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"382754805","text":"import math\nimport time\nfrom datetime import datetime, timedelta\n# from os import path as Path\nfrom pathlib import Path\nfrom data.loader import FileManager\nimport pandas as pd\nimport plotly.graph_objs as go\nimport plotly.io as pio\nfrom plotly import subplots\nimport modules.timeutils as timeutils\nimport modules.utils as utils\nfrom config import config, root_path\nfrom modules.our_tweepy import OurTweepy\n\n\nclass TwitterMonitor(OurTweepy):\n\n def __init__(self, stocks_list, continue_same_day=False, init_tweets_num=5, verbose=False):\n super().__init__(verbose=verbose)\n self.stocks_list = stocks_list\n self.tweets_data = dict.fromkeys(self.stocks_list)\n self.stats_df = pd.DataFrame(columns=(self.stocks_list.append('date_time')))\n self.tweets_path = root_path / Path(config['databases']['tweets']['stocks'])\n self.logs_path = root_path / Path(config['logs']['monitor']['stats'])\n self.update_interval = math.ceil((60 * config['tweepy']['limitations']['interval'] / (\n config['tweepy']['limitations']['max_requests_per_interval'] / len(stocks_list))) * 1.1)\n self.last_time_saved = datetime.now()\n self.init_tweets_num = init_tweets_num\n self.continue_same_day = continue_same_day\n self.filemanager = FileManager(database_folder=self.tweets_path, verbose=True)\n self.init_data()\n\n def init_data(self):\n print(\"Initializing TwitterMonitor():\")\n for stock, fetched_tweets in self.tweets_data.items():\n if self.continue_same_day:\n today = utils.day_format(datetime.now())\n self.tweets_data[stock] = self.filemanager.load(stock=stock, dates=today)\n else:\n search_query = str(\"$\" + stock)\n self.tweets_data[stock], _ = self.fetch(query=search_query, n=self.init_tweets_num)\n\n def fetch(self, query, n=100, since_id=None):\n print(\"\\tSearching for new tweets with \" + query + \" cashtag...\")\n if not since_id:\n latest_tweet, len = self.get_n_last_tweets(query=query, n=n, df=True)\n else:\n latest_tweet, len = self.get_n_last_tweets(query=query, n=n, since_id=since_id, df=True)\n print(\"\\t\\tAdded {} new tweets.\".format(len))\n return latest_tweet, len\n\n def run(self, hours, save_every=60):\n init_amount_of_tweets = self.stats().sum().sum()\n end_time = datetime.now() + timedelta(seconds=(hours * 60 * 60))\n while end_time > datetime.now() + timedelta(seconds=self.update_interval):\n try:\n self.update()\n if datetime.now().hour is not self.last_time_saved.hour:\n self.save() # saves every hour\n print(\"[{}]\\nInterval between updates: {} seconds\\nExpected end time: {}\\nForce stop: Ctrl+C\".\n format(datetime.strftime(datetime.now(), format=\"%H:%M:%S\"),\n self.update_interval,\n datetime.strftime(end_time, format=\"%H:%M:%S\")))\n time.sleep(self.update_interval)\n except KeyboardInterrupt:\n print(\"run: killed by user.\")\n return\n except Exception as e:\n print(\"Error occured ({}) in the run loop - trying to sleep for 15 min to avoid API ban.\".format(e))\n time.sleep(15 * 60)\n # exit while loop\n total_tweets_pulled = self.stats().sum().sum() - init_amount_of_tweets\n print(\"[{}] Time is up. Pulled {} tweets.\".format(datetime.strftime(datetime.now(), format=\"%H:%M:%S\"),\n total_tweets_pulled))\n\n def update(self):\n # TODO Error : [{'message': 'Rate limit exceeded', 'code': 88}] handle this one.\n stocks_volume_absolute_change = dict.fromkeys(self.stocks_list)\n for stock, fetched_tweets in self.tweets_data.items():\n try:\n last_fetched_tweet_id = fetched_tweets['id'].iloc[0]\n search_query = str(\"$\" + stock)\n new_tweets_df, n_tweets = self.fetch(query=search_query,\n since_id=last_fetched_tweet_id) # fetch all tweets since the last fetched tweet (max limit is 100)\n\n if n_tweets > 0 and new_tweets_df is not None:\n self.tweets_data[stock] = pd.concat([fetched_tweets, new_tweets_df], sort=False). \\\n sort_values(by=['id'], ascending=False)\n stocks_volume_absolute_change[stock] = n_tweets\n except:\n print(\"Something went wrong fetching {} new tweets.\".format(stock))\n continue\n self.__update_stats(stocks_volume_absolute_change)\n\n def show(self):\n for stock, fetched_tweets in self.tweets_data.items():\n print(stock)\n for index, row in fetched_tweets.iterrows():\n print(\"\\t\", end=\"\")\n self.__print_tweet(row)\n print(\"Total tweets: {}\".format(len(fetched_tweets.index)))\n print()\n\n def data(self):\n return self.tweets_data\n\n def stats(self):\n if self.stats_df.empty:\n return self.stats_df\n return self.stats_df\n # return self.stats_df.set_index(pd.DatetimeIndex(self.stats_df.date_time))#.drop('date_time')\n\n def plot_stats(self):\n pio.renderers.default = \"browser\" # for default plot in browser\n df = self.stats()\n how_many_plots = len(df.columns)\n rows = int(math.ceil(how_many_plots / 3))\n cols = 3\n fig = subplots.make_subplots(rows=rows, cols=cols, subplot_titles=df.columns,\n shared_xaxes=True, vertical_spacing=0.01)\n j = 0\n for i in df.columns:\n row = j % rows + 1\n col = j % cols + 1\n fig.add_trace(\n go.Scatter(\n {'x': df.index,\n 'y': df[i]}),\n row=row, col=col)\n j += 1\n fig.update_layout(title=\"Twitter Monitor\", title_x=0.5, showlegend=False)\n fig.show()\n\n def save(self, force_all=False):\n self.save_stats(force_all=force_all)\n self.save_tweets(force_all=force_all)\n self.last_time_saved = datetime.now()\n\n def save_stats(self, force_all=False):\n df = self.stats()\n if not force_all:\n df = df[df.index > self.last_time_saved] # save only the stats created from the last time saved.\n if df.empty: return # if no new stats, skip.\n count = len(df.index)\n first_time = df.index[0]\n last_time = df.index[count - 1]\n file_name = 'on_' + datetime.strftime(first_time, '%Y-%m-%d') + '_from_' + \\\n datetime.strftime(first_time, '%H-%M-%S') + '_to_' + \\\n datetime.strftime(last_time, '%H-%M-%S') + '.csv'\n df.to_csv(str( self.logs_path / file_name))\n print(\"saved to file: \" + str( self.logs_path / file_name))\n\n def save_tweets(self, force_all=False):\n self.filemanager.save(data=self.tweets_data, dates=[timeutils.now()])\n # for stock, fetched_tweets in self.tweets_data.items():\n # full_folder_path = self.tweets_path / stock\n # utils.create_dir_if_not_exist(str(full_folder_path))\n # if not force_all:\n # last_fetched_tweets = fetched_tweets[fetched_tweets['fetched_at'] > self.last_time_saved]\n # else:\n # last_fetched_tweets = fetched_tweets\n # if last_fetched_tweets.empty: continue # if no tweets, skip.\n #\n # count = len(last_fetched_tweets.index)\n # last_time = last_fetched_tweets['date_time'].iloc[0]\n # first_time = last_fetched_tweets['date_time'].iloc[count - 1]\n # file_name = 'on_' + datetime.strftime(first_time, '%Y-%m-%d') + '_from_' + datetime.strftime(first_time,\n # '%H-%M-%S') + '_to_' + datetime.strftime(\n # last_time, '%H-%M-%S') + '.csv'\n # last_fetched_tweets.to_csv(str(full_folder_path / file_name))\n # print(\"saved to file: \" + str(full_folder_path / file_name))\n\n def __update_stats(self, stats_dict):\n stats_dict['date_time'] = datetime.now().replace(microsecond=0)\n stats_df = pd.DataFrame([stats_dict]).fillna(0)\n stats_df.index = pd.DatetimeIndex(stats_df.date_time)\n stats_df = stats_df.drop(['date_time'], axis=1)\n self.stats_df = pd.concat([self.stats_df, stats_df], sort=False)\n\n def __print_tweet(self, tweet):\n print(\"id: {} created_at: {}\".format(tweet['id'], tweet['date_time']))\n","sub_path":"products/event_detector/twitter_monitor.py","file_name":"twitter_monitor.py","file_ext":"py","file_size_in_byte":8825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"193073618","text":"\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport editdistance\nimport numpy as np\nimport pandas as pd\n\nfrom refparse.utils.parse import structure_reference\n\ndef calc_lev_distance(s1, s2):\n\n if s1=='' or s2 =='':\n return 0\n\n return editdistance.eval(s1, s2) / max(len(s1), len(s2))\n\ndef get_levenshtein_df(df1, df2):\n \"\"\"\n Input: two equally sized dataframes\n output: a dataframe of the levenshtein distances between each element pair\n \"\"\"\n\n lev_list = [\n calc_lev_distance(a,p) for (a,p) in zip(df1.stack(), df2.stack())\n ]\n lev_dist = pd.DataFrame(\n np.reshape(lev_list, df1.shape),\n columns = df1.columns\n )\n\n return lev_dist\n\ndef evaluate_metric(\n actual_categories, predicted_categories, levenshtein_threshold):\n\n equal = actual_categories == predicted_categories\n\n accuracy_cat = equal.mean()\n accuracy = equal.values.mean()\n\n lev_dist = get_levenshtein_df(actual_categories, predicted_categories)\n\n quite_equal = lev_dist\"+name[:-3]+\"\")\n\n\ndef print_title(name,count):\n ''''''\n temp=''\n for i in range(1,count,1):\n temp = temp+' '\n temp = temp+'* '\n # 输出文件夹目录\n #print(temp,name.split('/'))\n result.append(temp+'【 '+name+' 】') \n\n\n# 递归\ndef create(name,count):\n if(os.path.isdir(name)):\n print_title(name,count)\n for fold in listfiles(name):\n if fold in dirs:\n continue\n if not os.path.isdir(name+'/'+fold):\n #print(\"不是目录--------\",fold)\n print_line(fold,count,name+'/'+fold)\n \n create(name+'/'+fold,count+1)\n else:\n return\n\n# 处理参数\nopts, args = getopt.getopt(sys.argv[1:], \"sha\")\nfor op,value in opts:\n if op == \"-s\":\n flag_show = True\n #print(\"show\")\n elif op == \"-a\":\n flag_append = True\n #print(\"append\")\n elif op == \"-h\":\n show_help()\n\n\nFolders = os.listdir('./')\nFolders.sort()\n\n# 处理根目录下的md文件\nfor fold in Folders:\n if fold.endswith('.md'):\n if fold in files:\n continue\n #print(\"md::::\"+fold)\n result.append(\"* [ \"+fold[:-3]+\" ](./\"+fold+\")\")\n # result.append(\"\"+fold[:-3]+\"\")\n\n# 得到根目录下所有文件夹,然后开始递归得到所有文件 \nfor fold in Folders:\n if(os.path.isdir(fold)):\n if(fold in dirs):\n continue\n create(fold,1)\n\n# 终端输出\nif flag_show : \n for res in result:\n print(res) \n\n# 追加到gitbook的目录文件中\nif flag_append :\n subprocess.call('mv SUMMARY.md SUMMARY.md.bak',shell=True)\n with open('SUMMARY.md','w+') as dest:\n dest.write('# Summary\\n\\n* [Introduction](README.md)\\n\\n')\n for res in result:\n dest.write(res+'\\n')\n print('重新生成目录树完成!')\n","sub_path":"create_tree.py","file_name":"create_tree.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"442052966","text":"#!/usr/bin/env python\n\nfrom git import *\nfrom git.exc import *\nimport subprocess\nfrom os import mkdir,chdir,path,getcwd\nimport coverage\nimport nose\nimport pkg_resources, glob\n\n\n\ndef check_local_repo(REPO_PATH, REPO_NAME):\n \"\"\"\n Check a local clone of a git tree\n \"\"\"\n repo = Repo(REPO_PATH)\n repo.config_reader()\n repo.config_writer()\n repo.remote(name=REPO_NAME).pull()\n return repo\n\n\ndef clone_repo(GIT_PATH, REPO_PATH):\n \"\"\"\n Make a local clone of a git tree\n \"\"\"\n repo = Repo.clone_from(GIT_PATH,REPO_PATH)\n return repo\n\n\ndef create_repo_dir(REPO_PATH):\n \"\"\"\n Creare repo directory\n \"\"\"\n mkdir(REPO_PATH)\n\n\ndef if_repo_exists(REPO_PATH):\n \"\"\"\n Test if local git tree exists\n \"\"\"\n try:\n repo = Repo(REPO_PATH)\n except (InvalidGitRepositoryError,NoSuchPathError):\n return False\n\n return True\n\n\ndef nose_start(LOG, REPO_PATH): #test names\n \"\"\"\n Find all python modules in REPO_PATH\n \"\"\"\n WORKING_DIR = getcwd();\n chdir(REPO_PATH)\n coverage.erase()\n coverage.start()\n nose.run()\n coverage.stop()\n LOG.info(coverage.analysis(nose))\n LOG.info(coverage.report())\n chdir(WORKING_DIR)\n\ndef remove_repo(REPO_PATH):\n \"\"\"\n Remove whole repo directory\n \"\"\"\n cmd = \"rm -rf \" + REPO_PATH\n subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).stdout.read()\n\n\ndef update_local_repo(REPO_PATH):\n \"\"\"\n Check a local clone of a git tree\n \"\"\"\n repo = Repo(REPO_PATH)\n return repo\n","sub_path":"tr/tstgit.py","file_name":"tstgit.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"347431822","text":"import time\r\nimport sys\r\nfrom random import randint\r\nfrom person import *\r\n\r\ndef exist():\r\n society = []\r\n i = 0\r\n for i in range(0, gdv_stp):\r\n society += [Person(gdv_stht_mp, gdv_stht_fp, 0)]\r\n return society\r\n\r\ndef average():\r\n #a = 0 #counter for average geneation abbreviated as of 03/11/17, variable name still in use\r\n #b = 0 #counter for female to male ratio abbreviated as of 07/11/17\r\n #c = 0 #counter for average height abbreviated as of 07/11/17\r\n #d = 0 #counter for average health abbreviated as of 07/11/17\r\n global maxhte\r\n global minhte\r\n maxgen = society[1].special[0]\r\n mingen = society[1].special[0]\r\n maxhtf = 0 #max height female\r\n maxhtm = 0 #max height male\r\n minhtf = 9999 #min height female\r\n minhtm = 9999 #min height male\r\n x = len(society)\r\n f = 0 #number of females (used to determine ftm ratio, also height calculations)\r\n m = 0 #number of males (used to determine ftm ratio, also height calculations)\r\n avgn = 0 #average gen temp value\r\n avht = 0 #average height temp value\r\n avhtm = 0 #average male height temp value\r\n avhtf = 0 #average female height temp value\r\n avhl = 0 #average health temp value\r\n \r\n for a in range(0, x):\r\n avgn += society[a].special[0]\r\n avht += society[a].special[2]\r\n avhl += society[a].special[3]\r\n\r\n if(society[a].special[0] > maxgen):\r\n maxgen = society[a].special[0]\r\n if(society[a].special[0] < mingen):\r\n mingen = society[a].special[0]\r\n \r\n if(society[a].special[1] == 0):\r\n f += 1\r\n avhtf += society[a].special[2]\r\n if(society[a].special[2] < minhtf):\r\n minhtf = society[a].special[2]\r\n if(society[a].special[2] > maxhtf):\r\n maxhtf = society[a].special[2]\r\n if(society[a].special[1] == 1):\r\n m += 1\r\n avhtm += society[a].special[2]\r\n if(society[a].special[2] < minhtm):\r\n minhtm = society[a].special[2]\r\n if(society[a].special[2] > maxhtm):\r\n maxhtm = society[a].special[2]\r\n\r\n g = f + m\r\n g = f / g\r\n fr = g * 100 #female ratio\r\n mr = (1 - g) * 100 #male ratio\r\n\r\n avgn = avgn / x\r\n avhtm = avhtm / m\r\n avhtml.append(avhtm)\r\n avhtf = avhtf / f\r\n avhtfl.append(avhtf)\r\n avht = avht / x\r\n avhtl.append(avht)\r\n avhl = avhl / x\r\n\r\n if(minhte > minhtm):\r\n minhte = minhtm\r\n elif(minhte > minhtf):\r\n minhte = minhtf\r\n elif(maxhte < maxhtm):\r\n maxhte = maxhtm\r\n elif(maxhte < maxhtf):\r\n maxhte = maxhtf\r\n\r\n if(len(sys.argv) >= 1 and not \"noaverage\" in sys.argv):\r\n print(\"gen min/avg/max:\", mingen, \"/\", round(avgn), \"/\", maxgen, \" | height:\", round(avht), \" | health:\", round(avhl), \" | Population ever:\", Person.all_ever(), \" | currently:\", m + f, \" | f:m ratio: \", round(fr, 2), \":\", round(mr, 2), sep='' ) \r\n if(len(sys.argv) > 1 and \"htdt\" in sys.argv):\r\n print(\"male height min/max/avg:\", round(minhtm), round(maxhtm), round(avhtm), \"female height min/max/avg:\", round(minhtf), round(maxhtf), round(avhtf), \"overall average:\", round(avht), \"highest ever:\", round(maxhte), \"smallest ever:\", round(minhte))\r\n \r\ndef die():\r\n a = 0\r\n lifetime = randint(gdv_hlmin, gdv_hlmax) #default: (1, 310) (seems to be the most efficient number for not letting the population explode or die out too fast)\r\n while(a < len(society)): \r\n if((society[a].special[3] - lifetime) > 0):\r\n society[a].special[3] -= lifetime\r\n else:\r\n try:\r\n society.remove(society[a])\r\n except ValueError:\r\n print(\"problem removing\", society[a].special, \"@\", society[a])\r\n a += 1\r\n\r\ndef dating():\r\n a = 0\r\n pairs = []\r\n left = list(range(0, len(society)))\r\n while(a < len(left)):\r\n x = left[randint(0, len(left) - 1)]\r\n try:\r\n left.remove(x)\r\n except ValueError:\r\n print(\"error @\", left[x])\r\n y = left[randint(0, len(left) - 1)]\r\n try:\r\n left.remove(y)\r\n except ValueError:\r\n print(\"error @\", left[y])\r\n pairs += [[x, y]]\r\n a += 2\r\n return(pairs)\r\n\r\ndef reproduce(pairs):\r\n a = 0\r\n while(a < len(pairs)):\r\n if(society[pairs[a][0]].special[1] is not society[pairs[a][1]].special[1]):\r\n if(society[pairs[a][0]].special[0] == society[pairs[a][1]].special[0]): \r\n society.append(Person(society[pairs[a][0]].special[2], society[pairs[a][1]].special[2], society[pairs[a][0]].special[0] + 1))\r\n else:\r\n pass\r\n a+=1\r\n return(society)\r\n\r\ndef execution_parameters():\r\n global gdv_stp\r\n global gdv_hlmin\r\n global gdv_hlmax\r\n global gdv_stht_fp\r\n global gdv_stht_mp\r\n cnt = True\r\n if(len(sys.argv) > 1):\r\n argslst = \"\"\r\n for i in range(1,len(sys.argv)):\r\n argslst += sys.argv[i] + \", \"\r\n if(\"cpar\" in sys.argv):\r\n print(\"Custom parameters (leave blank for default)\")\r\n sys.stdout.write(\"Start Population(default: 50, value: int 0-n)?\")\r\n stpp = input()\r\n try:\r\n stpp = int(stpp)\r\n if(stpp == ''):\r\n gdv_stp = 50\r\n elif(stpp > 0):\r\n gdv_stp = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"Average height startfemales (default: 1670, value: int 0-n, recommended 1500-2000)?\")\r\n stpp = input()\r\n try:\r\n stpp = int(stpp)\r\n if(stpp == ''):\r\n gdv_stht_fp = 1670\r\n elif(stpp > 0):\r\n gdv_stht_fp = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"Average height startmales (default: 1780, value: int 0-n, recommended 1500-2000)?\")\r\n stpp = input()\r\n try:\r\n stpp = int(stpp)\r\n if(stpp == ''):\r\n gdv_stht_mp = 1780\r\n elif(stpp > 0):\r\n gdv_stht_mp = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"Minimal health loss (default: 1, value: int 1-n, recommended 1-n 0):\r\n gdv_hlmin = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"Maximal health loss (default: 310, value: int 1-n, recommended 300-320, consider max health!)?\")\r\n stpp = input()\r\n try:\r\n stpp = int(stpp)\r\n if(stpp == ''):\r\n gdv_hlmax = 1780\r\n elif(stpp > 0):\r\n gdv_hlmax = stpp\r\n except:\r\n print(\"'\", stpp, \"'is not a valid parameter, default will be used\")\r\n sys.stdout.write(\"rektus will be executed with the following parameters: \" + argslst + \"continue? [Y/n]\")\r\n choice = input().lower()\r\n if(choice == '' or choice == 'y'):\r\n cnt = True\r\n else:\r\n cnt = False\r\n return cnt\r\n\r\n\"\"\" gdv --> (g)lobal(d)eclared(v)alue_[sample name]\"\"\"\r\ngdv_hlmin = 1 #(h)ealth(l)oss minimum\r\ngdv_hlmax = 310 #(h)ealth(l)oss maximum\r\ngdv_stp = 50 #(st)art(p)opulation\r\ngdv_stht_fp = 1670 #(st)art(h)eigh(t)_(f)emale(p)arent\r\ngdv_stht_mp = 1780 #(st)art(h)eigh(t)_(m)ale(p)arent\r\ncnt = execution_parameters() #cnt is used to determine if the user is happy with the parameters of execution\r\nmaxhte = 0\r\nminhte = 9999\r\nif cnt:\r\n society = exist()\r\n average() \r\nwhile cnt:\r\n pointao = time.perf_counter()\r\n die()\r\n pointac = time.perf_counter()\r\n pointbo = time.perf_counter()\r\n couplets = dating()\r\n pointbc = time.perf_counter()\r\n pointco = time.perf_counter()\r\n society = reproduce(couplets)\r\n pointcc = time.perf_counter()\r\n pointdo = time.perf_counter() \r\n average()\r\n pointdc = time.perf_counter()\r\n if(len(sys.argv) > 1 and \"perf\" in sys.argv):\r\n print(\"runtime overall:\", round(pointdc - pointao, 5), \"die:\", round(pointac - pointao, 5), \"dating:\", round(pointbc - pointbo, 5), \"reproduce:\", round(pointcc - pointco, 5), \"average:\", round(pointdc - pointdo, 5), \"for\", len(society), \"elements in society[]\")","sub_path":"rektus.py","file_name":"rektus.py","file_ext":"py","file_size_in_byte":9103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"563677889","text":"from SAMP_WEB_API import CRUD\nimport time as t\n\nclass sessions(CRUD):\n def __init__(self):\n self.id = None\n self.login_time = t.datetime()\n self.mac = None\n self.user_id = None\n self.key = None\n","sub_path":"SAMP_WEB_API/sessions.py","file_name":"sessions.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"60820468","text":"import teoria_numeros\n\n\nclass CurvasElipticas:\n\n def __init__(self):\n self.lamda = 0\n self.a = 1\n self.b = 1\n\n def setA(self, a):\n self.a = a\n\n def setB(self, b):\n self.b = b\n\n def calculateLambda(self, P, Q, n):\n if P[0] != Q[0]:\n calc = teoria_numeros.inv((P[0] - Q[0]), n)\n self.lamda = ((P[1] - Q[1]) * calc) % n\n elif P[0] == Q[0]:\n calc = (3 * teoria_numeros.exponenciacion(P[0], 2, n) + self.a) % n\n self.lamda = calc * teoria_numeros.inv((2 * P[1]), n)\n\n def suma(self, P, Q, n):\n result = []\n if self.lamda == 0:\n self.calculateLambda(P, Q, n)\n\n x3 = (teoria_numeros.exponenciacion(self.lamda, 2, n) - P[0] - Q[0])\n y3 = ((P[0] - x3) * self.lamda - P[1])\n\n while x3 < 0:\n x3 = x3 + n\n\n while x3 > n:\n x3 = x3 - n\n\n while y3 < 0:\n y3 = y3 + n\n\n while y3 > n:\n y3 = y3 - n\n\n result.append(x3)\n result.append(y3)\n return result\n\n def multiplicacion(self, k, P, n):\n temp = []\n if k > 0:\n PT = P\n for i in range(1, k):\n temp = self.suma(PT, P, n)\n PT.clear()\n PT.append(temp[0])\n PT.append(temp[1])\n elif k < 0:\n PT = P * (-1)\n for i in range(1, k):\n temp = self.suma(PT, (P * (-1)), n)\n PT.clear()\n PT.append(temp[0])\n PT.append(temp[1])\n else:\n print(\"Punto en el Infinito\")\n return PT\n\n def generateTabla(self, n):\n table = []\n temp = []\n for i in range(0, n):\n z = ((i) ** 3 + self.a * i + self.b) % n\n\n if teoria_numeros.jacobi(z, n) == 1:\n res = \"SI\"\n else:\n res = \"NO\"\n\n if res == \"SI\":\n #y1 = teoria_numeros.exponenciacion(z, ((n + 1) / 4), n)\n #y2 = n - y1\n #y12 = [y1, y2]\n y12 = teoria_numeros.raizcuadradaprima(z, 11)\n else:\n y12 = []\n\n temp = [i, z, res, y12]\n table.append(temp)\n\n return table\n\n def constructTable(self, n):\n table = cv.generateTabla(n)\n print([\"i\", \"z\", \"res\", \"y12\"])\n for i in range(len(table)):\n print((table[i]))\n\n\nif __name__ == \"__main__\":\n cv = CurvasElipticas()\n #cv.setA(3)\n #cv.setB(6)\n #cv.calculateLambda([10, 7], [1, 4], 13)\n #print((cv.lamda))\n #print((cv.suma([0, 1], [1, 4], 13)))\n #print((cv.multiplicacion(21, [0, 1], 79)))\n #H = cv.multiplicacion(2, [1, 4], 13)\n #H = cv.multiplicacion(2, [0, 1], 13)\n #K = cv.suma(H, [1, 4], 13)\n #print(K)\n #print((cv.suma(H, [0, 1], 13)))\n #print((cv.construirTabla(11)))\n #cv.constructTable(11)\n","sub_path":"CurvasElipticas.py","file_name":"CurvasElipticas.py","file_ext":"py","file_size_in_byte":2931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"414614140","text":"# Import all relevant libraries.\nprint(\"Please wait while relevant libraries are being imported...\")\nfrom pandas_datareader import data\nfrom datetime import datetime, timedelta\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import minimize\nfrom scipy.stats import skew, kurtosis\nfrom sklearn.linear_model import LinearRegression\n\n# Initial variable declaration. Change monthly mean return value, lookback period (days) and risk-free to affect stocks selected for analysis.\nCAPITAL = 50000\nMONTHLY_MEAN_RET = 0.10\nLOOKBACK_PERIOD = 90\nRISK_FREE = 0.01963\nend = datetime.today()\nstart = datetime.today()-timedelta(days=LOOKBACK_PERIOD)\n\nfilename = input(\"Enter the name of the file with the list of companies: \")\nstocks = pd.read_csv(filename+\".csv\")\n# Check if Prices and Volumes files have already been previously created.\ntry:\n prices = pd.read_csv(\"Prices\", index_col=0, parse_dates=True)\n volumes = pd.read_csv(\"Volumes\", index_col=0, parse_dates=True)\nexcept FileNotFoundError:\n print(\"Generating Prices and Volumes files, please wait as this may take a while...\")\n prices = pd.DataFrame()\n volumes = pd.DataFrame()\n norm_rets = pd.DataFrame()\n for stock in stocks[\"Code\"]:\n try:\n temp_df = data.DataReader(stock+\".AX\", \"yahoo\", start, end)\n prices[stock+\".AX\"] = temp_df[\"Adj Close\"]\n volumes[stock+\".AX\"] = temp_df[\"Volume\"]\n except:\n pass\n prices.to_csv(\"Prices\")\n volumes.to_csv(\"Volumes\")\n\n# Select stocks based on criteria.\nchosen_stocks = pd.DataFrame()\nprices.dropna(axis=1, how=\"any\", inplace=True)\nvolumes.dropna(axis=1, how=\"any\", inplace=True)\nfor stock in prices:\n # Critera = 12 day SMA > 26 day SMA and 30-day cumulative return > given monthly mean return.\n if (prices[stock].rolling(12).mean()[-1] > prices[stock].rolling(26).mean()[-1] and prices[stock][-1]/prices[stock][-30] > 1+MONTHLY_MEAN_RET):\n chosen_stocks[stock] = prices[stock]\n\nprint(\"Descriptive statistics for chosen stocks: \")\ntry:\n print(round(chosen_stocks.describe().transpose(), 3))\nexcept:\n print(\"No stocks available according to set criteria. Please change criteria and try again.\")\n input(\"Press ENTER to exit: \")\n quit()\nprint(\"\\n\")\n\n# Optional choice to view historical price charts of chosen stocks.\ngraphs = input(\"Do you wish to view historical price charts for selected stocks (y/n): \")\nif graphs == \"y\":\n sma_12 = chosen_stocks.rolling(12).mean()\n sma_26 = chosen_stocks.rolling(26).mean()\n sns.set_style(\"whitegrid\")\n for stock in chosen_stocks:\n user_choice = input(\"Enter 1 for the next graph, the stock code for stock specific graph or 0 to stop displaying graphs: \")\n if user_choice is \"1\":\n plt.figure(figsize=(10, 6))\n sns.lineplot(x=chosen_stocks.index, y=stock, data=chosen_stocks, label=\"Adj Close\", color=\"black\")\n plt.plot(sma_12[stock], label=\"12 Day SMA\", color=\"red\")\n plt.plot(sma_26[stock], label=\"26 Day SMA\", color=\"blue\")\n plt.legend()\n plt.xlabel(\"Date\")\n plt.ylabel(\"Price ($AUD)\")\n plt.title(f\"{stock} Price\")\n plt.tight_layout()\n plt.show()\n elif len(user_choice) == 6 and user_choice[-2:] == \"AX\":\n plt.figure(figsize=(10, 6))\n sns.lineplot(x=chosen_stocks[user_choice].index, y=user_choice, data=chosen_stocks, label=\"Adj Close\", color=\"black\")\n plt.plot(sma_12[stock], label=\"12 Day SMA\", color=\"red\")\n plt.plot(sma_26[stock], label=\"26 Day SMA\", color=\"blue\")\n plt.legend()\n plt.xlabel(\"Date\")\n plt.ylabel(\"Price ($AUD)\")\n plt.title(f\"{user_choice} Price\")\n plt.tight_layout()\n plt.show()\n else:\n print(\"\\n\")\n break\n\n# Normalising daily returns for chosen stocks together with histogram of the returns.\nlog_ret = np.log(chosen_stocks/chosen_stocks.shift(1))\nlog_ret.dropna(axis=0, how=\"any\", inplace=True)\n\n# Optional choice to view distributions of chosen stocks.\ngraphs = input(\"Do you wish to view distributions for selected stocks? (y/n) \")\nif graphs == \"y\":\n sns.set_style(\"whitegrid\")\n for stock in chosen_stocks:\n user_choice = input(\"Enter 1 for the next graph, the stock code for stock specific graph or anything else to stop displaying graphs: \")\n if user_choice == \"1\":\n plt.figure(figsize=(10, 6))\n sns.distplot(log_ret[stock].iloc[1:], hist=False,\n label=f\"Skewness = {round(skew(log_ret[stock].iloc[1:]),3)}\\nKurtosis = {round(kurtosis(log_ret[stock].iloc[1:]),3)}\")\n plt.title(f\"{stock} Price Distribution\")\n plt.tight_layout()\n plt.show()\n elif len(user_choice) == 6 and user_choice[-2:] == \"AX\":\n plt.figure(figsize=(10, 6))\n sns.distplot(log_ret[user_choice].iloc[1:], hist=False,\n label=f\"Skewness = {round(skew(log_ret[user_choice].iloc[1:]),3)}\\nKurtosis = {round(kurtosis(log_ret[user_choice].iloc[1:]),3)}\")\n plt.title(f\"{user_choice} Price Distribution\")\n plt.tight_layout()\n plt.show()\n else:\n print(\"\\n\")\n break\n\nuser_choice = int(input(\"Enter 1 for Markowitz optimisation, 2 for CAPM - Index Model or 0 to exit program: \"))\n\nif user_choice == 1:\n num_stocks = len(chosen_stocks.columns)\n\n # MATHEMATICAL OPTIMISATION OF PORTFOLIO WEIGHTS - MPT (Markowitz).\n def ret_vol_sharpe(weights):\n # Uses portfolio weights as inputs, outputs expected return, volatility and the Sharpe ratio for the weights.\n weights = np.array(weights)\n returns = np.sum(log_ret.mean()*weights)*252\n volatility = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov()*252, weights)))\n sharpe = (returns-RISK_FREE)/volatility\n return np.array([returns, volatility, sharpe])\n\n def negative_sharpe(weights):\n # Converts positive Sharpe ratio to negative since we are using a minimiser (minimise most negative Sharpe = maximise Sharpe).\n return ret_vol_sharpe(weights)[2]*-1\n\n def check_sum(weights):\n # Return 0 if sum of portfolio weights = 1.\n return np.sum(weights)-1\n\n # By convention of minimize function it should be a function that returns zero for conditions.\n constraints = ({'type': 'eq', 'fun': check_sum})\n # [0, 1] bounds for each weight, short selling not allowed.\n bounds = [(0, 1)]*num_stocks\n # Initial Guess (equal distribution).\n init_guess = [1/num_stocks]*num_stocks\n optimal_results = minimize(negative_sharpe, init_guess, method='SLSQP', bounds=bounds, constraints=constraints)\n print(f\"Optimal Portfolio: [Exp.Return Risk Sharpe] = {ret_vol_sharpe(optimal_results.x)}\")\n print(\"Please wait while the Efficient Frontier is generated...\\n\")\n\n # EFFICIENT FRONTIER.\n # Create a linspace number of points to calculate x on.\n frontier_return = np.linspace(0, ret_vol_sharpe(optimal_results.x)[0]+0.3, 50)\n\n def minimize_volatility(weights):\n return ret_vol_sharpe(weights)[1]\n\n frontier_volatility = []\n for possible_return in frontier_return:\n # Two constraints - sum of weights = 1 and difference in returns is equal to 0 (optimal weights at every\n # possible return).\n cons = ({'type': 'eq', 'fun': check_sum},\n {'type': 'eq', 'fun': lambda w: ret_vol_sharpe(w)[0] - possible_return})\n # Minimum volatility for each possible return (Efficient Frontier).\n result = minimize(minimize_volatility, init_guess, method='SLSQP', bounds=bounds, constraints=cons)\n # Returning volatility here instead of Sharpe ratio because minimising volatility.\n frontier_volatility.append(result['fun'])\n\n # CREATING RANDOM PORTFOLIOS BASED ON RANDOM WEIGHTS - SCATTER PLOT DATA.\n num_ports = 15000\n all_weights = np.zeros((num_ports, num_stocks))\n ret_arr = np.zeros(num_ports)\n vol_arr = np.zeros(num_ports)\n sharpe_arr = np.zeros(num_ports)\n for ind in range(num_ports):\n # Create Random Weights\n weights = np.array(np.random.random(num_stocks))\n # Rebalance Weights\n weights = weights/np.sum(weights)\n # Save Weights\n all_weights[ind, :] = weights\n # Expected Return\n ret_arr[ind] = np.sum((log_ret.mean()*weights)*252)\n # Expected Variance\n vol_arr[ind] = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov()*252, weights)))\n # Sharpe Ratio\n sharpe_arr[ind] = ret_arr[ind]/vol_arr[ind]\n\n plt.figure(figsize=(10, 6))\n plt.scatter(vol_arr, ret_arr, c=sharpe_arr, cmap=\"plasma\")\n plt.colorbar(label=\"Sharpe Ratio\")\n plt.xlabel(\"Volatility\")\n plt.ylabel(\"Return\")\n # Add frontier line and red dot for max Sharpe ratio.\n plt.plot(frontier_volatility, frontier_return, 'g--', linewidth=3)\n plt.scatter(ret_vol_sharpe(optimal_results.x)[1], ret_vol_sharpe(optimal_results.x)[0], c='red', s=50, edgecolors='black')\n plt.show()\n\n # Amount invested in each firm and number of shares in each firm using optimal weights.\n pos_value = round(pd.DataFrame(optimal_results.x*50000).transpose(), 3)\n pos_value.columns = chosen_stocks.columns\n print(\"Positional value: \")\n print(pos_value)\n print(\"\\n\")\n pos_shares = pos_value/chosen_stocks.iloc[-1]\n pos_shares = pos_shares.apply(int)\n print(\"Number of shares in each selected stock: \")\n print(pos_shares)\n print(\"\\n\")\n final_return = round((1+(ret_vol_sharpe(optimal_results.x)[0]/4))*CAPITAL, 3)\n print(f\"Final expected return as at June 2019: ${final_return} \\n\")\n\nelif user_choice == 2:\n # CAPM - only use this as a test for the theory. Bewary as R^2 and p-values have not been checked for the stock betas.\n market_ret = data.DataReader(\"^AXJO\", \"yahoo\", start, end)\n log_market_ret = np.log(market_ret[\"Adj Close\"]/market_ret[\"Adj Close\"].shift(1))\n log_market_ret.dropna(axis=0, how=\"any\", inplace=True)\n betas = []\n # Linear regression of stock excess return on market excess return.\n for stock in chosen_stocks:\n lin_reg = LinearRegression(fit_intercept=True)\n lin_reg.fit(np.array(log_market_ret-RISK_FREE).reshape(-1, 1), np.array(log_ret[stock]-RISK_FREE).reshape(-1, 1))\n betas.append(lin_reg.coef_[0][0])\n\n plt.figure(figsize=(10, 6))\n sns.regplot(betas, log_ret.mean())\n plt.title(\"CAPM Index Model For Chosen Stocks During Given Period\")\n plt.xlabel(\"Beta\")\n plt.ylabel(\"E(r)\")\n plt.tight_layout()\n plt.show()\n\ninput(\"Press ENTER to exit: \")\n","sub_path":"ASX Competition/ASX Competition Strategy.py","file_name":"ASX Competition Strategy.py","file_ext":"py","file_size_in_byte":10714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"112612245","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom upemtk import *\nimport os\nfrom random import choice\n\n\ndef creation_map(fichier):\n \"\"\"Crée la matrice de jeu , ainsi que les autres données , a partir du fichier map passé en paramètre\"\"\"\n\n # On crée les différentes données\n matrice = []\n lst_k = []\n lst_b = []\n joueur = None\n titre = \"\"\n\n \n with open(fichier) as f:\n \n for y, ligne in enumerate(f):\n \n # La ligne 0 correspond au titre , on ne recupère que celui-ci sans ce qu'il y a autour\n if y == 0:\n titre = ligne.split('\"')[1]\n continue\n \n lst = []\n \n # On crée la matrice, et, pour un soucis de simplicité, on met les boites et les clés dans des listes a part\n \n for x, elt in enumerate(ligne):\n \n if elt != \"\\n\":\n\n if elt == \"S\":\n lst.append(\".\")\n joueur = (x, y-1)\n continue\n\n if elt == \"K\":\n lst_k.append((x, y - 1))\n lst.append(\".\")\n continue\n\n if elt == \"B\":\n lst_b.append((x, y - 1))\n lst.append(\".\")\n continue\n\n lst.append(elt)\n \n matrice.append(lst)\n \n return matrice, joueur, titre, lst_k, lst_b\n\n\ndef afficher_jeu(joueur, nb_k, titre):\n \"\"\"Fonction qui prend en paramètre les éléments susceptibles de changer, ainsi que le titre,\n et affiche tous les elements du jeu a l'écran\"\"\"\n \n # On réinitialise l'affichage pour éviter que les éléments se chevauchent\n efface_tout()\n \n for y,lst in enumerate(matrice):\n for x,elt in enumerate(lst):\n\n # Affichage Case vide\n if elt == \".\":\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n \n # Affichage Clé\n if (x, y) in lst_k:\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x * 50, (y * 50) + 110, 'sprites/key.png', ancrage='nw')\n \n # Affichage Boite\n if (x, y) in lst_b:\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x*50, (y*50)+100, 'sprites/crate.png', ancrage='nw')\n \n # Affichage Mur\n elif elt == \"W\":\n image(x * 50, (y * 50) + 100, 'sprites/wall.png', ancrage='nw')\n \n # Affichage Porte\n elif elt == \"D\":\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x * 50, (y * 50) + 100, 'sprites/door.png', ancrage='nw')\n \n # Affichage Cible\n elif elt == \"T\":\n image(x * 50, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image((x * 50) + 10, (y * 50) + 110, 'sprites/target.png', ancrage='nw')\n\n # On affiche le joueur a la fin\n x, y = joueur\n image((x * 50) + 10, (y * 50) + 100, 'sprites/character.png', ancrage='nw')\n \n # On affiche les informations supplémentaires au dessus\n texte(50, 5, titre, couleur='red')\n aff_k = \"Clé(s) : \" + str(nb_k)\n texte(50, 50, aff_k, couleur='red')\n\n \n mise_a_jour()\n\n\ndef evenement(joueur, debug, lst_k, lst_b, matrice, Map,titre):\n \"\"\"Fonction qui gère les évènements et effectue l'action appropriée selon la touche pressée\"\"\"\n \n ev = donne_evenement()\n \n # Si rien ne se passe, on renvoie les données telles qu'elles\n if ev == (\"RAS\",\"\"):\n return joueur,debug,lst_k,lst_b,matrice\n \n if type_evenement(ev) == \"Touche\":\n \n # Si c'est une touche directionelle, on met a jour avec la fonction déplacement la position du joueur\n if touche(ev) == \"Up\":\n joueur = deplacement(joueur,\"Up\", nb_k)\n \n elif touche(ev) == \"Down\":\n joueur = deplacement(joueur,\"Down\", nb_k)\n \n elif touche(ev) == \"Right\":\n joueur = deplacement(joueur,\"Right\", nb_k)\n \n elif touche(ev) == \"Left\":\n joueur = deplacement(joueur,\"Left\", nb_k)\n \n # Si on appuie sur la touche 'r', on reset tout le jeu a partir du fichier de la map\n elif touche(ev) == \"r\":\n matrice, joueur, lst_k , lst_b = reset(Map)\n \n # Si on appuie sur 'd', on active le mode debug, s'activant alors dès le prochain tour de boucle\n elif touche(ev) == \"d\":\n debug = True\n \n # Si on appuie sur 's' (save), on sauvegarde la map dans son etat actual\n elif touche(ev) == \"s\":\n save_map(titre, joueur, Map)\n \n # Si on appuie sur 'l' (load), on charge la dernière sauvegarde associée a la map en question\n elif touche(ev) == \"l\":\n joueur, debug, lst_k, lst_b, matrice,titre = load_save(Map)\n\n if type_evenement(ev) == \"Quitte\":\n exit()\n \n return joueur,debug,lst_k,lst_b,matrice\n\n\ndef reset(Map):\n \"\"\"Réinitialise la carte en remettant toutes les valeurs a celles de bases, prend en argument le chemin du niveau\"\"\"\n\n # On utilise une variable globale pour simplifier le programme\n global nb_k\n \n # On efface l'affichage précédent\n efface_tout()\n\n # On remet a 0 le nombre de clés\n nb_k = 0\n \n # On reprend les données de début et on les affiche a l'écran\n matrice, joueur, titre, lst_k, lst_b = creation_map(Map)\n afficher_jeu(joueur, nb_k,titre)\n\n return matrice, joueur,lst_k,lst_b\n\n\ndef collision(joueur, direction, nb_k):\n \"\"\"Fonction qui vérifie si le joueur peut se déplacer dans une direction et renvoie False si le\n déplacement est possible\"\"\"\n \n x, y = joueur\n \n # On vérifie que le joueur ne sort pas du jeu\n if x in range(len(matrice[0])) and y in range(len(matrice)):\n \n # On vérifie si le joueur tente de se déplacer vers une boite\n if (x, y) in lst_b:\n \n # Si Oui, on verifie si on peut déplacer la boite\n if deplacement_box(matrice, joueur, direction) is True:\n return False\n else:\n return\n \n # Si le joueur tente de se déplacer dans une cible vide, ou une case vide, on autorise le déplacement\n if matrice[y][x] in [\"T\", \".\"]:\n return False\n \n # Si le joueur tente d'aller dans une porte, on vérifie qu'il puisse l'ouvrir\n if matrice[y][x] == \"D\":\n if ouverture_porte(joueur, nb_k) is True:\n return False\n\n\ndef deplacement_box(matrice, joueur, direction):\n \"\"\"Fonction gérant le déplacement des boites, prend en paramètre la direction afin de savoir dans quel sens il faut\n déplacer la boite.\n On regarde si le déplacement de la boîte est possible, si oui, on met a jour les données\"\"\"\n x, y = joueur\n \n # On vérifie pour la direction indiquée si la boite peut se déplacer\n # (qu'elle ne rentre pas en collision avec une autre boite ou tout bloc \"dur\" et qu'elle ne sort pas de la matrice)\n if x in range(len(matrice[0])) and y - 1 in range(len(matrice)):\n if direction == \"Up\" and matrice[y-1][x] in [\".\", \"T\"] and (x, y-1) not in lst_b:\n \n # Si le déplacement est possible , on met a jour les coordonnées de la boite :\n # On récupère l'indice de la boite qui va être déplacée\n rang_box = lst_b.index((x, y))\n # Puis on le modifie\n lst_b[rang_box] = (x, y-1)\n return True\n \n # On repète les mêmes actions pour chaque direction :\n\n if x in range(len(matrice[0])) and y + 1 in range(len(matrice)):\n if direction == \"Down\" and matrice[y+1][x] in [\".\", \"T\"] and (x, y+1) not in lst_b:\n\n rang_box = lst_b.index((x, y))\n lst_b[rang_box] = (x, y + 1)\n return True\n\n if x - 1 in range(len(matrice[0])) and y in range(len(matrice)):\n if direction == \"Left\" and matrice[y][x-1] in [\".\", \"T\"] and (x-1, y) not in lst_b:\n\n rang_box = lst_b.index((x, y))\n lst_b[rang_box] = (x - 1, y)\n return True\n\n if x + 1 in range(len(matrice[0])) and y in range(len(matrice)):\n if direction == \"Right\" and matrice[y][x+1] in [\".\", \"T\"] and (x+1, y) not in lst_b:\n\n rang_box = lst_b.index((x, y))\n lst_b[rang_box] = (x + 1, y)\n return True\n\n\ndef stock_cle(joueur, action):\n \"\"\"Fonction gérant le stock de clé du joueur, elle est appelée lorsque le joueur récupère ou utilise des clés\n c'est-a-dire lorsqu'il en gagne ou qu'il en perd. C'est a cela que sert le paramètre action (qui prend soit la\n valeur 'add' ou 'remove')\"\"\"\n \n global nb_k\n \n # Si on souhaite ajouter une clé\n if action == \"add\":\n # On recherche la clé ou se trouve le joueur, on la retire de la liste et on ajoute 1 au nombre de clés\n for elt in lst_k:\n\n if elt == joueur:\n lst_k.remove(elt)\n nb_k += 1\n \n # Si on souhaite utiliser une clé, alors on met a jour la variable en enlevant 1\n elif action == \"remove\":\n nb_k -= 1\n\n\ndef ouverture_porte(joueur, nb_k):\n \"\"\"Fonction pour l'ouverture des portes, renvoie True si l'ouverture est possible\"\"\"\n \n x, y = joueur\n \n # Si le joueur a au moins une clé, on enlève la porte de la matrice et supprime la clé au joueur,\n # enfin on renvoie True pour signifier que l'on peut ouvrir la porte\n if nb_k > 0:\n matrice[y][x] = \".\"\n stock_cle(joueur, \"remove\")\n return True\n\n\ndef deplacement(joueur, direction, nb_k):\n \"\"\"Prend les coordonnées du joueur et la direction dans laquelle il se rend et met a jour les données si le\n déplacement est possible\"\"\"\n \n # On regarde pour la direction indiquée si le déplacement est possible, si oui,\n # on renvoie les coordonnées du joueur mises a jour\n if direction == \"Up\" and collision((joueur[0],joueur[1]-1), direction, nb_k) is False:\n return joueur[0], joueur[1]-1\n \n elif direction == \"Down\" and collision((joueur[0],joueur[1]+1), direction, nb_k) is False:\n return joueur[0], joueur[1]+1\n \n elif direction == \"Left\" and collision((joueur[0]-1,joueur[1]), direction, nb_k) is False:\n return joueur[0]-1, joueur[1]\n \n elif direction == \"Right\" and collision((joueur[0]+1,joueur[1]), direction, nb_k) is False:\n return joueur[0]+1, joueur[1]\n \n # On retourne la position du joueur telle qu'elle si il n'y a pas eu de déplacement\n return joueur\n\n\ndef fonction_debug(joueur, debug):\n \"\"\"Fonction permettant au joueur de faire des déplacements aléatoires de manière rapide sans a avoir a attendre une\n action de l'utilisateur\"\"\"\n\n ev = donne_evenement()\n \n # On regarde si le joueur désactive le mode débug\n if type_evenement(ev) == \"Touche\":\n if touche(ev) == \"d\":\n debug = False\n directions = [\"Up\", \"Left\", \"Down\", \"Right\"]\n # On renvoie le joueur après un déplacement aléatoire ainsi que l'état du débug\n return deplacement(joueur, choice(directions), nb_k), debug\n\n\ndef win(matrice, lst_b):\n \"\"\"Fonction vérifiant si le joueur a gagné pour mettre fin au jeu\"\"\"\n \n # On vérifie, pour chaque boite de la liste, si elle est dans une cible\n for elt in lst_b:\n \n if matrice[elt[1]][elt[0]] == \"T\":\n \n continue\n \n else:\n\n # Si oui, on retourne True, sinon on retourne False\n return False\n\n return True\n\n\ndef save_map(Titre, Joueur, Map):\n \"\"\"Ecrit dans un fichier (sous la forme \"map.save\") l'état actuel de la partie pour le récupérer plus tard\"\"\"\n \n if \".save\" in Map:\n chemin_map = Map\n \n else:\n chemin_map = Map + \".save\"\n \n if \"\\n\" in Titre:\n Titre = Titre.replace(\"\\n\",\"\")\n \n with open(chemin_map,\"w\") as save:\n \n # On sauvegarde (dans l'ordre) : Le titre, la position du joueur, les possitions des boites, les positions des\n # clés, le nombre de clés qu'a le joueur et enfin la matrice\n \n save.write(Titre+\"\\n\")\n save.write(str(Joueur)+\"\\n\")\n \n for elt in lst_b:\n \n save.write(str(elt)+\";\")\n \n save.write(\"\\n\")\n \n for elt in lst_k:\n \n save.write(str(elt)+\";\")\n \n save.write(\"\\n\")\n \n save.write(str(nb_k)+\"\\n\")\n \n for lst in matrice:\n \n save.writelines(lst)\n save.write(\"\\n\")\n\n\ndef load_save(Map):\n \"\"\"Fonction lisant le fichier (\"map.save\") sauvegardé au préalable\"\"\"\n global nb_k\n \n if \".save\" not in Map:\n chemin_map = Map + \".save\"\n \n else:\n chemin_map = Map\n \n debug = False\n \n with open(chemin_map) as save:\n \n matrice = []\n \n ligne = save.readlines()\n # On récupère le titre\n Titre = ligne[0]\n \n # On récupère les coordonnées de joueur (en enlevant les caractères superflus) et on les remet sous forme de tuple\n joueur = ligne[1].replace(\"(\",\"\").replace(\")\",\"\").replace(\"\\n\",\"\").replace(\" \",\"\").split(\",\")\n joueur = (int(joueur[0]),int(joueur[1]))\n \n # On lit la liste des coordonnées des boites, et comme pour 'joueur', on les remet sous forme de tuples\n lst_b = [tuple(elt.replace(\"(\",\"\").replace(\")\",\"\").replace(\" \",\"\").split(\",\")) for elt in ligne[2].split(\";\") if elt != \"\\n\"]\n lst_b = list(map(lambda x: (int(x[0]), int(x[1])) , lst_b))\n \n # On effectue la même opération que sur la listes des coordonnées des boites\n lst_k = [tuple(elt.replace(\"(\",\"\").replace(\")\",\"\").replace(\" \",\"\").split(\",\")) for elt in ligne[3].split(\";\") if elt != \"\\n\"]\n lst_k = list(map(lambda x: (int(x[0]), int(x[1])) , lst_k))\n \n # On recupère le nombre de clé en le transtypant en entier et en enlevant les caractères superflus\n nb_k = int(ligne[4].replace(\"\\n\",\"\"))\n \n # On lit la matrice a la fin du fichier pour mettre a jour l'actuelle matrice affichée\n for ligne_matrice in ligne[5:]:\n \n lst = list()\n \n for elt in ligne_matrice:\n \n if elt != \"\\n\":\n \n lst.append(elt)\n \n matrice.append(lst)\n \n # On renvoie les données mises a jour\n return joueur, debug, lst_k, lst_b, matrice,Titre\n\n\ndef editeur():\n \"\"\"Editeur de niveau\"\"\"\n\n cree_fenetre(800, 500)\n selecteur = \".\"\n \n # On recupère les valeurs nécéssaires : hauteur/largeur et nom de fichier\n hauteur_map = entree_utilisateur(\"Entrez la Hauteur de la Map\", int)\n largeur_map = entree_utilisateur(\"Entrez la Largeur de la Map\", int)\n Nom_map = entree_utilisateur(\"Entrez le nom de fichier de la map a creer ou a modifier\", str, lettres=True)\n\n # On cree une fenêtre adapté a la taille de la map en cours de creation\n # On impose une largeur minimale 450\n \n if largeur_map * 50 < 450:\n largeur_fenetre = 450\n else:\n largeur_fenetre = largeur_map*50\n # On ouvre la fenêtre au proportion calculées\n ferme_fenetre()\n \n # On affiche les instruction\n cree_fenetre(450,450)\n image(0,0,\"sprites/instructions_editeur.png\", ancrage=\"nw\")\n attente_touche()\n ferme_fenetre()\n \n cree_fenetre(largeur_fenetre, hauteur_map*50+100)\n \n # On crée la matrice de la nouvelle carte\n carte = [[\".\" for i in range(largeur_map)] for j in range(hauteur_map)]\n \n Continuer = True\n while Continuer:\n # On récupère les évènements et on met a jour la matrice\n affiche_editeur(carte,largeur_fenetre)\n selecteur, Continuer = gestion_ev_editeur(carte, largeur_fenetre, selecteur)\n \n ferme_fenetre()\n cree_fenetre(800, 500)\n nomfichier = entree_utilisateur(\"Entrez le nom de fichier\", str, lettres=True)\n \n enregistrer_editeur(carte,Nom_map,nomfichier)\n \n # On ferme la fenetre pour ensuite retourner au menu\n ferme_fenetre()\n\n\ndef entree_utilisateur(Texte, typeval, lettres=False):\n \"\"\"On affiche un message passé en paramètres dans la fenêtre , et on lui applique la fonctiona a la fin\"\"\"\n val = \"\"\n \n while True:\n efface_tout()\n texte(50,5,Texte,taille=15)\n texte(50,200,val)\n mise_a_jour()\n ev = donne_evenement()\n \n if type_evenement(ev) == \"Touche\":\n \n if touche(ev) == \"Escape\":\n exit()\n \n elif touche(ev) in \"1234567890\":\n val += touche(ev)\n \n # On autorise les lettres seulement si lettres a été passé en paramètres comme True\n elif lettres is True and touche(ev) in \"azertyuiopqsdfghjklmwxcvnbAZERTYUIOPQSDFGHJKLMWXCVBN\":\n val += touche(ev)\n \n elif touche(ev) == \"Return\":\n return typeval(val)\n \n elif touche(ev) == \"BackSpace\":\n val = val[:-1]\n \n if type_evenement(ev) == \"Quitte\":\n exit()\n\n\ndef affiche_editeur(carte, largeur_fenetre):\n \"\"\"Similaire a afficher jeu , mais pour la map editée\"\"\"\n # On réinitialise l'affichage pour éviter que les éléments se chevauchent\n efface_tout()\n decalage = 0\n \n # On calcule le decalage si la fenêtre a la largeur minimale (450)\n if largeur_fenetre == 450:\n decalage = (largeur_fenetre-len(carte[0])*50) /2\n \n # Affichage Selecteurs\n rectangle(0,0,largeur_fenetre,99,couleur=\"grey\",remplissage=\"grey\")\n \n \n ###Case Vide\n image(largeur_fenetre/2 - 25, 30, 'sprites/ground.png', ancrage='nw')\n ###Boite\n image(largeur_fenetre / 2 - 75, 30, 'sprites/crate.png', ancrage='nw')\n ###Clé\n image(largeur_fenetre / 2 - 130, 40, 'sprites/key.png', ancrage='nw')\n ###Porte\n image(largeur_fenetre / 2 - 185, 30, 'sprites/door.png', ancrage='nw')\n ###Mur\n image(largeur_fenetre/2+25,30,'sprites/wall.png', ancrage='nw')\n ###Cible\n image(largeur_fenetre/2+85,40,'sprites/target.png', ancrage='nw')\n ###Spawn\n image(largeur_fenetre/2+130,30,'sprites/character.png', ancrage='nw')\n \n for y,lst in enumerate(carte):\n for x,elt in enumerate(lst):\n \n # Affichage Clé\n if elt == \"K\":\n image(x*50 + decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x * 50 + decalage, (y * 50) + 110, 'sprites/key.png', ancrage='nw')\n \n # Affichage Boite\n if elt ==\"B\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x*50+decalage, (y*50)+100, 'sprites/crate.png', ancrage='nw')\n \n # Affichage Case vide\n if elt == \".\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n \n # Affichage Mur\n elif elt == \"W\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/wall.png', ancrage='nw')\n \n # Affichage Porte\n elif elt == \"D\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image(x * 50 + decalage, (y * 50) + 100, 'sprites/door.png', ancrage='nw')\n \n # Affichage Cible\n elif elt == \"T\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image((x * 50) + 10 + decalage, (y * 50) + 110, 'sprites/target.png', ancrage='nw')\n \n elif elt == \"S\":\n image(x*50+decalage, (y * 50) + 100, 'sprites/ground.png', ancrage='nw')\n image((x * 50) + 10 + decalage, (y * 50) + 100, 'sprites/character.png', ancrage='nw')\n\n mise_a_jour()\n\n\ndef gestion_ev_editeur(carte, largeur_fenetre, selecteur):\n decalage = 0\n Continuer = True\n\n if largeur_fenetre == 450:\n decalage = (largeur_fenetre - len(carte[0]) * 50) // 2\n\n ev = donne_evenement()\n\n if type_evenement(ev) == \"ClicGauche\":\n\n coordonees = (int(clic_x(ev)), int(clic_y(ev)))\n # Permet de recuperer la valeur x et y\n x, y = int((coordonees[0] - decalage) / 50), int((coordonees[1] - 100) / 50)\n if y in range(len(carte)) and x in range(len(carte[0])) and coordonees[0] in range(decalage, len(\n carte[0]) * 50 + decalage) and coordonees[1] in range(100, len(carte) * 50 + 100):\n carte[y][x] = selecteur\n\n ###Vérification clic sur selecteurs\n\n elif coordonees[0] in range(largeur_fenetre // 2 - 25, largeur_fenetre // 2 + 25) and coordonees[1] in range(30,\n 80):\n selecteur = \".\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 - 75, largeur_fenetre // 2 - 25) and coordonees[1] in range(30,\n 80):\n selecteur = \"B\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 - 125, largeur_fenetre // 2 - 75) and coordonees[1] in range(\n 30, 80):\n selecteur = \"K\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 - 175, largeur_fenetre // 2 - 125) and coordonees[1] in range(\n 30, 80):\n selecteur = \"D\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 + 25, largeur_fenetre // 2 + 75) and coordonees[1] in range(30,\n 80):\n selecteur = \"W\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 + 75, largeur_fenetre // 2 + 125) and coordonees[1] in range(\n 30, 80):\n selecteur = \"T\"\n\n elif coordonees[0] in range(largeur_fenetre // 2 + 125, largeur_fenetre // 2 + 175) and coordonees[1] in range(\n 30, 80):\n selecteur = \"S\"\n \n \n if type_evenement(ev) == \"Touche\":\n \n # Si on appuie sur entrée , on vérifie que la map est valide avant d'autoriser son enregistrement\n if touche(ev) == \"Return\":\n if valide(carte):\n return selecteur, False\n \"\"\"\n elif touche(ev) == \"Escape\":\n ferme_fenetre()\n menu()\n \"\"\"\n \n if type_evenement(ev) == \"Quitte\":\n exit()\n\n return selecteur, Continuer\n\n\ndef valide(carte):\n \n dico_elt = dict()\n \n # On met chaque élément dans un dico par le nombre de fois ou ils apparaissent\n for ligne in carte:\n for elt in ligne:\n \n if elt not in dico_elt.keys():\n dico_elt[elt]=1\n else:\n dico_elt[elt]+=1\n \n dico_keys = dico_elt.keys()\n # On vérifie quelques erreurs et on les affiche dans la console\n \n if \"T\" not in dico_keys or \"B\" not in dico_keys or \"S\" not in dico_keys:\n print(\"Map non valide , il manque une élément obligatoire(Target , Spawn du joueur ou Box)\")\n return False\n \n if dico_elt[\"B\"] != dico_elt[\"T\"]:\n print (\"Pas le même nombre de Box et de Target\")\n return False\n \n if dico_elt[\"S\"] > 1:\n print(\"Il y a trop de Spawn\")\n return False\n \n return True\n\n\ndef enregistrer_editeur(carte, Nom_map, nomfichier):\n \n # On écrit le titre de la map puis la matrice qui la compose\n with open(\"map/\"+nomfichier,\"w\") as f:\n f.write(\"Titre : \\\"\"+Nom_map+\"\\\"\\n\")\n \n for ligne in carte:\n for elt in ligne:\n f.write(elt)\n f.write(\"\\n\")\n\n\ndef affiche_menu(taille_fenetre):\n \"\"\"Fonction affichant dans une fenetre préalablement créée tous les éléments immobiles du menu principal\"\"\"\n\n # On affiche le rectangle servant de couleur d'arriere-plan\n rectangle(0, 0, taille_fenetre - 1, taille_fenetre - 1, remplissage='dark blue')\n\n # On crée les variables correspondant au marge et a la taille des rectangles contenant le texte,\n # afin de les modifier facilement si nécessaire\n big_margin = 60\n small_margin = 40\n hauteur_rectangle = 100\n\n # On crée les rectangles\n for y in range(big_margin - 1, taille_fenetre - big_margin, small_margin + hauteur_rectangle):\n\n rectangle(big_margin, y, taille_fenetre - big_margin, y + hauteur_rectangle, remplissage='light yellow')\n\n # On écrit le texte a l'intérieur de chacun d'entre eux\n texte(taille_fenetre//2, 110, 'Jouer', couleur='blue', ancrage='center', taille=24)\n texte(taille_fenetre//2, 250, 'Editeur de niveau', couleur='blue', ancrage='center', taille=24)\n texte(taille_fenetre//2, 390, 'Quitter', couleur='blue', ancrage='center', taille=24)\n\n\ndef deplacement_selection(lst, selection, direction):\n \"\"\"Prend en parametre la liste des options du menu principal, la précedente option selectionnée et la touche pressée\n par l'utilisateur (soit 'Up', soit 'Down'). Renvoie le nouvel élément de la liste sélectionné\"\"\"\n\n # On garde dans une variable l'indice de la précedente sélection\n i = lst.index(selection)\n\n # La liste des options est faite ainsi : l'element d'indice 0 est affiché en haut, le plus grand indice est en bas\n\n if direction == 'Up':\n # Donc si l'utilisateur a appuyé sur 'Up' (fleche du haut), on renvoie l'élément précedent dans la liste\n return lst[i - 1]\n\n # Si le dernier élément sélectionné est le dernier élément de la liste, on renvoie le premier\n elif selection == lst[-1]:\n return lst[0]\n\n # Sinon, l'utilisateur a forcément appuyé sur 'Down' (c'est la seule autre option)\n else:\n # On renvoie donc l'élément suivant\n return lst[i + 1]\n\n\ndef selection_menu(taille_fenetre):\n \"\"\"Boucle principale du menu principal\"\"\"\n\n # On crée la liste des options disponibles dans le menu principal\n lst_options = ['jeu', 'editeur', 'quitter']\n # Le menu s'ouvre avec l'option tout en haut de l'ecran comme premiere selection\n selection = lst_options[0]\n\n while True:\n # On attend un évenement de la part de l'utilisateur\n ev = donne_evenement()\n type_ev = type_evenement(ev)\n\n # Si il a appuyé sur une touche\n if type_ev == 'Touche':\n\n # Si la touche est la fleche 'Bas' ou 'Haut' :\n if touche(ev) in ['Down', 'Up']:\n # On efface tout ce qui a été affiché\n efface_tout()\n # On réaffiche le menu\n affiche_menu(taille_fenetre)\n # La sélection change en fonction de la direction pressée\n selection = deplacement_selection(lst_options, selection, touche(ev))\n\n # Si la touche est 'Entrée' :\n elif touche(ev) == 'Return':\n # L'utilisateur a sélectionné son option, donc on la renvoie\n return selection\n\n # Si l'utilisateur a cliqué sur l'icone 'croix' pour fermer la fenetre, on quitte le programme\n if type_evenement(ev) == \"Quitte\":\n exit()\n\n # On affiche la sélection (un rectangle aux bords jaunes autour de l'option sélectionnée) et on met a jour\n # l'affichage\n affiche_selection(lst_options, selection)\n mise_a_jour()\n\n\ndef menu():\n \"\"\"Fonction principale gérant le menu, renvoyant la sélection choisie par l'utilisateur dans le menu principal\"\"\"\n\n # On définit la taille de la fenetre du menu, puis on la crée\n taille_fenetre = 500\n cree_fenetre(taille_fenetre, taille_fenetre)\n\n # On affiche le menu une premiere fois sur la nouvelle fenetre\n affiche_menu(taille_fenetre)\n # On rentre dans la boucle principale du menu, des que l'utilisateur a appuyé sur 'Entrée', la sélection est faite\n # et renvoyée a cette fonction\n selection = selection_menu(taille_fenetre)\n\n # Une fois la sélection faite, on ferme la fenetre du menu pour laisser place a celle de la sélection\n ferme_fenetre()\n\n return selection\n\n\ndef affiche_selection(lst, selection):\n \"\"\"Affiche le rectangle aux bords jaunes autour de la sélection dans le menu principal\"\"\"\n\n # Pour chaque indice d'élément dans la liste des options du menu\n for i in range(len(lst)):\n\n # Si l'élément d'indice i est la sélection :\n if lst[i] == selection:\n # On affiche un rectangle avec des bordures jaunes d'une épaisseur de 10px\n rectangle(50, 50 + 140*i, 450, 170 + 140*i, couleur='yellow', epaisseur=10)\n\n\ndef selection_niv(taille_fenetre, lst_map):\n \"\"\"Boucle principale du menu de sélection de niveau\"\"\"\n\n # Le menu s'ouvre avec l'option tout en haut de l'écran comme premiere sélection\n selection = lst_map[0]\n\n # On crée des pages (des sous-listes de lst_map contenant autant de niveaux\n # qu'une page peut afficher) et on fait afficher la premiere au debut\n pages = creation_page(lst_map)\n lst_map = pages[0]\n\n # On initialise le nombre de pages a 0\n nb_page = 0\n while True:\n\n # On attend un évenement de la part de l'utilisateur\n ev = donne_evenement()\n type_ev = type_evenement(ev)\n\n # Si il a appuyé sur une touche\n if type_ev == 'Touche':\n\n # Si la touche est 'Entrée' :\n if touche(ev) == 'Return':\n # L'utilisateur a sélectionné son option, donc on la renvoie\n return selection\n\n # Si la touche est la fleche 'Gauche' ou 'Droite' :\n if touche(ev) in ['Left', 'Right']:\n # La page va changer, l'indice de la nouvelle page est renvoyé par la fonction selection_page\n nb_page = selection_page(nb_page, len(pages), touche(ev))\n # La liste des cartes a afficher change pour devenir la liste des cartes de la nouvelle page\n lst_map = pages[nb_page]\n # La nouvelle page s'ouvre avec l'option tout en haut sélectionnée\n selection = lst_map[0]\n\n # On efface la précedente page et on réaffiche le menu de sélection avec la bonne page\n efface_tout()\n affiche_menu_niv(taille_fenetre, lst_map)\n\n # Si la touche est la fleche 'Gauche' ou 'Droite' :\n if touche(ev) in ['Down', 'Up']:\n\n # La sélection va changer donc :\n # On efface tous les éléments affichés précedemment et on réaffiche le menu\n efface_tout()\n affiche_menu_niv(taille_fenetre, lst_map)\n # La nouvelle sélection est renvoyée par la fonction deplacement_selection\n selection = deplacement_selection(lst_map, selection, touche(ev))\n\n # Si l'utilisateur a cliqué sur l'icone 'croix' pour fermer la fenetre, on quitte le programme\n if type_ev == \"Quitte\":\n exit()\n\n # On affiche la sélection (un rectangle aux bords jaunes autour de l'option sélectionnée) et on met a jour\n # l'affichage\n affiche_selection_niv(lst_map, selection)\n mise_a_jour()\n\n\ndef liste_map():\n \"\"\"Renvoie la liste triée de tous les niveaux et sauvegardes jouables\"\"\"\n\n # On crée une liste vide\n lst_map = []\n\n # Pour chaque élément dans la liste des fichiers dans le dossier 'map'\n for fic in os.listdir('map'):\n # Si l'élément est un fichier, on l'ajoute a la liste\n if os.path.isfile(os.path.join('map', fic)):\n lst_map.append(fic)\n\n # On renvoie la liste triée par la fonction sorted\n return sorted(lst_map)\n\n\ndef affiche_instructions():\n \"\"\"Fonction affichant les instructions du menu de sélection de niveau\"\"\"\n\n # On crée une fenetre\n cree_fenetre(450, 450)\n\n # On affiche l'image contenant les instructions\n image(0, 0, 'sprites/instructions_selec_niv.png', ancrage='nw')\n\n # On attend que l'utilisateur appuie sur n'importe quelle touche pour continuer\n attente_touche()\n ferme_fenetre()\n\n\ndef affiche_menu_niv(taille_fenetre, lst_map):\n \"\"\"Fonction affichant dans une fenetre préalablement créée tous les éléments immobiles du menu de sélection de\n niveau\"\"\"\n\n # On affiche le rectangle servant de couleur d'arriere-plan\n rectangle(0, 0, taille_fenetre - 1, taille_fenetre - 1, remplissage='dark blue')\n\n # On crée les variables correspondant au marge et a la taille des rectangles contenant le texte,\n # afin de les modifier facilement si nécessaire\n big_margin = 40\n small_margin = 40\n hauteur_rectangle = 50\n\n # On crée les rectangles\n for y in range(big_margin - 1, taille_fenetre - big_margin, small_margin + hauteur_rectangle):\n rectangle(big_margin, y, taille_fenetre - big_margin, y + hauteur_rectangle, remplissage='light yellow')\n\n decalage_texte = big_margin + (hauteur_rectangle//2)\n # On crée un compteur afin de s'arreter quand toutes les cartes sont affichées\n i = 0\n for y in range(decalage_texte, decalage_texte + 5*(small_margin+hauteur_rectangle), small_margin+hauteur_rectangle):\n texte(taille_fenetre // 2, y, lst_map[i], couleur='blue', ancrage='center', taille=24)\n i += 1\n\n # Si le compteur a dépassé l'indice maximum (len(lst) - 1), on sort de la boucle\n if i == len(lst_map):\n break\n\n\ndef affiche_selection_niv(lst, selection):\n \"\"\"Affiche le rectangle aux bords jaunes autour de la sélection dans le menu de sélection de niveau\"\"\"\n\n # Pour chaque indice d'élément dans la liste des options du menu\n for i in range(len(lst)):\n\n # Si l'élément d'indice i est la sélection :\n if lst[i] == selection:\n # On affiche un rectangle avec des bordures jaunes d'une épaisseur de 10px\n rectangle(30, 30 + 90*i, 470, 100 + 90*i, couleur='yellow', epaisseur=10)\n\n\ndef menu_niv():\n \"\"\"Fonction principale gérant le menu, renvoyant la sélection choisie par l'utilisateur dans le menu de sélection\n de niveau\"\"\"\n\n # On fait appel a la fonction ouvrant une fenetre contenant les instructions pour ce menu\n affiche_instructions()\n\n # On définit la taille de la fenetre du menu, puis on la crée\n taille_fenetre = 500\n cree_fenetre(taille_fenetre, taille_fenetre)\n\n # On crée la liste de tous les niveaux et sauvegardes jouables dans le dossier 'map'\n lst_map = liste_map()\n\n # On affiche le menu de sélection de niveau une premiere fois sur la nouvelle fenetre\n affiche_menu_niv(taille_fenetre, lst_map)\n # On rentre dans la boucle principale du menu, ou l'utilisateur peut faire sa sélection\n selection = selection_niv(taille_fenetre, lst_map)\n\n # Une fois la sélection faite, on ferme la fenetre du menu pour laisser place a celle de la sélection\n ferme_fenetre()\n # Puis on renvoie la sélection\n return selection\n\n\ndef creation_page(lst_map):\n \"\"\"Fonction créant les pages, chacune contenant au maximum 5 cartes.\n Prend en parametre la liste de tous les niveaux et sauvegardes jouables dans le dossier 'map'.\n Renvoie une liste de listes, chaque sous-liste correspondant a une page, chaque page est donc une liste contenant au\n maximum 5 cartes\"\"\"\n\n nb_map = len(lst_map)\n\n pages = []\n\n i = 0\n page = []\n while i < nb_map:\n\n # On ajoute la carte d'indice i dans la page en train d'etre créée\n page.append(lst_map[i])\n i += 1\n\n # Si la page contient 5 cartes, la liste finale ajoute la liste page, puis on réinitialise la page a une liste vide\n if len(page) == 5:\n pages.append(page)\n page = []\n\n # Les deux lignes suivantes servent a ajouter la derniere page si celle-ci n'est pas pleine (donc que le nombre\n # total de cartes n'est pas un multiple de 5\n\n # Si la page n'est pas vide et qu'elle n'est pas deja dans la liste finale (donc qu'elle ne contient pas 5 cartes):\n if page != [] and page not in pages:\n # On ajoute cette page a la liste finale\n pages.append(page)\n\n # On renvoie la liste des pages\n return pages\n\n\ndef selection_page(i, nb_pages, direction):\n \"\"\"Fonction prenant en parametre l'indice de la precedente page, le nombre total de pages, et la touche pressée\n par le joueur. Elle renvoie l'indice de la nouvelle page a afficher.\"\"\"\n\n # La liste des options est faite ainsi : la page d'indice 0 sera affichée le plus \"vers la gauche\" possible,\n # la page avec le plus grand indice sera affichée le plus \"vers la droite\" possible.\n\n if direction == 'Left':\n # La direction est la gauche, a moins que la page soit la premiere (auquel cas on renvoie le meme indice\n # puisqu'on ne veut pas changer de page)\n if i == 0:\n return i\n\n # On renvoie l'indice précedent\n return i - 1\n\n else:\n # La direction est la droite, a moins que la page soit la derniere (auquel cas on renvoie le meme indice\n # puisqu'on ne veut pas changer de page)\n\n if i == nb_pages - 1:\n return i\n\n # On renvoie l'indice suivant\n return i + 1\n\n\nif __name__ == '__main__':\n\n while True:\n # On ouvre le menu principal\n selection = menu()\n\n # Si la sélection est de quitter le menu principal\n if selection == 'quitter':\n # On quitte le programme\n exit()\n\n # Si la sélection est l'editeur graphique\n if selection == 'editeur':\n # On lance l'editeur\n editeur()\n\n # Si la sélection est de jouer\n if selection == 'jeu':\n # On ouvre le menu de sélection de niveau\n Map = 'map/' + menu_niv()\n\n # On crée les données nécessaires :\n\n # Si la carte contient la chaine '.save', alors on sait que c'est une sauvegarde et on la charge\n if \".save\" in Map:\n joueur, debug, lst_k, lst_b, matrice, titre = load_save(Map)\n\n # Sinon c'est une carte, on crée les données\n else:\n matrice, joueur, titre, lst_k, lst_b = creation_map(Map)\n debug = False\n Win = False\n nb_k = 0\n\n # On crée la fenêtre, ayec une taille relative a la taille de la matrice\n taille_fenetre = (len(matrice[0]) * 50, len(matrice) * 50 + 100)\n cree_fenetre(taille_fenetre[0], taille_fenetre[1])\n\n # Boucle principale, tourne tant le booléen win est False, c'est-a-dire tant que le joueur n'a pas gagné\n while True:\n\n # On actualise l'affichage\n afficher_jeu(joueur, nb_k, titre)\n\n # On vérifie si le joueur n'a pas gagné\n Win = win(matrice, lst_b)\n\n # Si le joueur a gagné , on affiche un Bravo , et on on attend qu'il n'appuie sur n'importe quelle\n # touche pour sortir de la boucle principale et retourner au menu\n if Win is True:\n efface_tout()\n ferme_fenetre()\n cree_fenetre(600,150)\n texte(50,50, \"Bravo ! Vous avez gagné\")\n attente_clic()\n ferme_fenetre()\n break\n\n # Si le debug est activé, on appelle la fonction debug, la fonction evenement sinon\n if debug is False:\n joueur, debug, lst_k, lst_b, matrice = evenement(joueur, debug, lst_k, lst_b, matrice, Map,titre)\n else:\n joueur, debug = fonction_debug(joueur, debug)\n\n # On vérifie si le joueur n'est pas sur une clé\n stock_cle(joueur, \"add\")\n\n","sub_path":"Sokoban.py","file_name":"Sokoban.py","file_ext":"py","file_size_in_byte":40434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"599649475","text":"import pymongo\n\n\nclass StockExchangeDataInfos:\n\n def __init__(self, database, *data):\n self.database = database['stocks']['stock_exchange']\n self.data = data\n\n def __str__(self):\n description = \"This class allows to save the stock exchange informations for each country is part of.\\n1.\" \\\n \" SetStockExchangeInDB save the value in the DB params(ClientDB, data to save). the data input params\" \\\n \" is {'exchg'(_id), 'exchg country'} \\n2.\" \\\n \" GetStockExchangeFromDB retrieve values from the DB params(ClientDB, query to search, data\" \\\n \"to display.\"\n return description\n\n async def SetStockExchangeInDB(self):\n \"{'exchg'(_id), 'exchg country'}\"\n try:\n self.database.insert_one(self.data[0])\n except pymongo.errors.DuplicateKeyError:\n print('StocksExchangeDataInfos.SetStockExchangeInDB.DuplicateKeyError', self.data[0]['_id'])\n\n def GetStockExchangeFromDB(self):\n\n query = self.data[0]\n display = self.data[1]\n tab = []\n\n for value in self.database.find(query, display):\n tab.append(value)\n return tab","sub_path":"aBlackFireCapitalClass/ClassStockExchangeData/ClassStockExchangeDataInfos.py","file_name":"ClassStockExchangeDataInfos.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"102850823","text":"import pygame\n\ndef write(surface, text, fontsize, colour, position):\n\tmyfont = pygame.font.SysFont(\"None\", fontsize)\n\tmytext = myfont.render(text, True, colour)\n\tmytext = mytext.convert_alpha()\n\tsurface.blit(mytext, position)\n\ndef color(colorname):\n\tcolors = {\n\t\t\"white\": (255, 255, 255),\n\t\t\"black\": (0, 0, 0),\n\t\t\"red\": (255, 0, 0),\n\t\t\"yellow\": (175, 175, 50),\n\t\t\"green\": (0, 255, 0)\n\t}\n\treturn colors[colorname]","sub_path":"Helpers.py","file_name":"Helpers.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"420421974","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport bz2\n\ndef main():\n # inputfile = open(\"./test.xml\", \"r\")\n # outfile = open(\"./ttest.xml\", \"w\")\n\n # position = int(2006442797*1440000/1870253)\n\n count = 0\n # inputxml = bz2.BZ2File(\"jawiki-latest-pages-articles.xml.bz2\", 'r')\n # outfile = bz2.BZ2File(\"jawiki-latest-pages-articles_2.xml.bz2\", 'w')\n inputxml = bz2.BZ2File(\"jawiki-latest-pages-articles.xml.bz2\", 'r')\n outfile = open(\"./test_2.xml\", 'w')\n\n inputxml.seek(-10000, 2)\n\n for line in inputxml:\n count += 1\n if count > 50:\n break\n # if count > 100579840:\n outfile.writelines(line)\n inputxml.close()\n outfile.close()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"_src/cleaning.py","file_name":"cleaning.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"350420885","text":"import pandas as pd\nimport numpy as np\n\nfrom pathlib import Path\nimport pickle\nimport gym\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# how to import or load local files\nimport os\nimport sys\npath = os.path.split(os.path.realpath(__file__))[0]\nsys.path.append(path)\nimport gym_cfg\nwith open(path + \"/gym_cfg.py\", \"r\") as f:\n pass\n\nclass TestAgent():\n def __init__(self):\n self.now_phase = {}\n self.green_sec = 2\n self.red_sec = 0\n self.max_phase = 8\n self.last_change_step = {}\n self.agent_list = []\n self.phase_passablelane = {}\n self.phase_mv_inc = [(1, 2), (1, 4), (2, 3), (2, 5),\n (3, 0), (3, 6), (4, 1), (4, 7),\n (5, 2), (5, 3), (6, 0), (6, 1),\n (7, 4), (7, 5), (8, 6), (8, 7)]\n self.road_idx_to_arm = {0:\"Ni\", 1:\"Ei\", 2:\"Si\", 3:\"Wi\",\n 4:\"No\", 5:\"Eo\", 6:\"So\", 7:\"Wo\"}\n self.lane_idx_to_mv = {0:\"L\", 1:\"T\", 2:\"R\"}\n self.mv_to_phase = {\n \"NiL\":1, \"SiL\":1, \"NiT\":2, \"SiT\":2,\n \"EiL\":3, \"WiL\":3, \"EiT\":4, \"WiT\":4\n }\n self.prev_action = None\n \n ################################\n # don't modify this function.\n # agent_list is a list of agent_id\n def load_agent_list(self,agent_list):\n self.agent_list = agent_list\n self.now_phase = dict.fromkeys(self.agent_list,1)\n self.last_change_step = dict.fromkeys(self.agent_list,0)\n ################################\n\n \n def obs_process(self, observations):\n # preprocess observations\n observations_for_agent = {}\n for key,val in observations.items():\n observations_agent_id = int(key.split('_')[0])\n observations_feature = key[key.find('_')+1:]\n if(observations_agent_id not in observations_for_agent.keys()):\n observations_for_agent[observations_agent_id] = {}\n observations_for_agent[observations_agent_id][observations_feature] = val\n \n # format into pd.dataframe\n obs = []\n for agent_id, agent_obs in observations_for_agent.items():\n sim_step = agent_obs['lane_speed'][0]\n lane_speed = agent_obs['lane_speed'][1:]\n lane_vehicle_num = agent_obs['lane_vehicle_num'][1:]\n assert len(lane_speed) == len(lane_vehicle_num)\n for idx, speed in enumerate(lane_speed):\n road_idx = idx // 3\n lane_idx = idx % 3\n veh_num = lane_vehicle_num[idx]\n obs.append([sim_step, agent_id, road_idx, lane_idx, speed, veh_num])\n\n obs_df = pd.DataFrame(obs, columns=['sim_step', 'agent_id', 'road_idx', 'lane_idx', 'speed', 'veh_num'])\n \n return obs_df\n \n \n def gen_pressure(self, obs_df):\n \n # formatting obs_df\n obs_df = obs_df[(obs_df.road_idx < 4) & (obs_df.lane_idx < 2)]\n obs_df['road_idx'] = obs_df['road_idx'].replace(self.road_idx_to_arm)\n obs_df['lane_idx'] = obs_df['lane_idx'].replace(self.lane_idx_to_mv)\n obs_df['mv'] = obs_df['road_idx'] + obs_df['lane_idx']\n obs_df['phase'] = obs_df['mv'].replace(self.mv_to_phase)\n \n # define pressure: the number of vehicles on the approach\n pressure = obs_df.pivot_table(index='agent_id',\n columns='mv',\n values='veh_num',\n aggfunc='sum')\n \n return pressure\n \n \n def act(self, obs):\n \"\"\" !!! MUST BE OVERRIDED !!!\n \"\"\"\n # here obs contains all of the observations and infos\n\n # observations is returned 'observation' of env.step()\n # info is returned 'info' of env.step()\n observations = obs['observations']\n info = obs['info']\n actions = {}\n\n # a simple fixtime agent\n\n # preprocess observations\n obs_df = self.obs_process(observations)\n cur_step = obs_df['sim_step'].unique()[0]\n if (self.prev_action is not None) and (cur_step % self.green_sec > 1):\n return self.prev_action\n \n # get pressure\n pressure = self.gen_pressure(obs_df)\n\n # get actions\n phase_mv_incidence = np.zeros((4, 8))\n for x, y in self.phase_mv_inc[:8]:\n phase_mv_incidence[x - 1, y] = 1\n \n action = {}\n for i in range(len(pressure)):\n agent_id = pressure.index[i]\n phase_pressures = np.dot(phase_mv_incidence, pressure.iloc[i, :].values)\n max_locs = np.where(phase_pressures == np.max(phase_pressures))[0]\n if np.std(phase_pressures) == 0:\n action[agent_id] = np.random.randint(1, 5, 1)[0]\n elif len(max_locs) > 1:\n loc = np.random.randint(0, len(max_locs), 1)\n action[agent_id] = max_locs[loc][0] + 1\n else:\n agent_action = np.argmax(phase_pressures) + 1\n action[agent_id] = agent_action\n self.prev_action = action\n \n return action\n\nscenario_dirs = [\n \"test\"\n]\n\nagent_specs = dict.fromkeys(scenario_dirs, None)\nfor i, k in enumerate(scenario_dirs):\n # initialize an AgentSpec instance with configuration\n agent_specs[k] = TestAgent()\n\n","sub_path":"agent/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":5377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"386596343","text":"#!/usr/bin/env python\n\nfrom distutils.core import setup\n\n\nVERSION=\"0.4.0\"\n\nsetup(\n name = 'cattleprod',\n packages = ['cattleprod'],\n version = VERSION,\n description = 'A quickly constructed interface to the Rancher API (http://rancher.com)',\n author = 'Axel Bock',\n author_email = 'mr.axel.bock@gmail.com',\n url = 'https://github.com/flypenguin/python-cattleprod',\n download_url = 'https://github.com/flypenguin/python-cattleprod/tarball/{}'.format(VERSION),\n keywords = ['rancher', 'api'],\n classifiers = [\n \"License :: OSI Approved :: MIT License\",\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: System Administrators\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Operating System :: POSIX\",\n \"Operating System :: MacOS\",\n \"Topic :: System :: Systems Administration\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"172121676","text":"import json\n\nfrom app import dh\nfrom app.portal.models import SettingModel\n\n\n# 读取设定数据\ndef load_setting(key: str):\n item = SettingModel.query.filter_by(key=key).first() # type: SettingModel\n if item is not None:\n return json.loads(item.value)\n\n return None\n\n\n# 保存设定数据\ndef save_setting(key: str, value):\n item = SettingModel.query.filter_by(key=key).first() # type: SettingModel\n if item is None:\n item = SettingModel(key=key)\n\n item.value = json.dumps(value, ensure_ascii=False)\n\n dh.session.add(item)\n dh.session.commit()\n\n return False\n","sub_path":"FlaskChapter7/app/portal/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"3030726","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\n\nclass Post(models.Model):\n\tname = models.CharField(max_length=80)\n\tdescription = models.TextField()\n\tdate = models.DateTimeField()\n\timage = models.FileField(null=True, blank=True)\n\towner = models.ForeignKey(User, on_delete=models.CASCADE)\n\n\tdef __str__(self):\n\t\treturn self.name\n","sub_path":"blog_post/blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"196974333","text":"from django.core.management.base import BaseCommand\nfrom web_app.models import Table\nimport sys\nimport os\n\nsys.path.append(os.getcwd())\nfrom scrape.src import crawl\n\n\nclass Command(BaseCommand):\n \"\"\"internのwebサイトからデータを取得して、データベースに挿入するコマンド\n\n \"\"\"\n\n def _crawl(self):\n \"\"\"データベースにデータを挿入する関数\n\n :return:\n \"\"\"\n for cate_name, title, content in crawl.crawler():\n q = Table(category=cate_name, title=title, content=content)\n q.save()\n\n def _insert_crawled_data(self):\n \"\"\"データベースを空にしてクローリングしたデータを入れる関数\n\n :return:\n \"\"\"\n\n if Table.objects.all():\n print(\"データベースにデータがあります。\\nデータを削除をして良いですか?\")\n while True:\n print(\"(y/n)>>\")\n answer = input()\n if answer == \"y\":\n print(\"データ挿入を開始\")\n Table.objects.all().delete()\n self._crawl()\n break\n elif answer == \"n\":\n print(\"データ挿入を中止\")\n break\n else:\n print(\"値が正確ではありません。\")\n else:\n print(\"データ挿入を開始\")\n self._crawl()\n\n def handle(self, *args, **options):\n self._insert_crawled_data()\n","sub_path":"web_app/management/commands/command_insert_crawled_data.py","file_name":"command_insert_crawled_data.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"467044895","text":"from mcpi.minecraft import Minecraft\nfrom mcpi import block\nfrom time import sleep\nqblock = 5\ndef init():\n\tmc = Minecraft.create(\"127.0.0.1\",4711)\n\tx, y, z = mc.player.getPos()\n\treturn mc\n\t\ndef wall1(mc,x,y,z):\n\tmc.setBlocks(x,y,z,x,y,z,qblock)\n\n\ndef main():\n\tmc = init()\n\tx, y, z = mc.player.getPos()\n\twall1(mc,x,y,z+8)\t\nmain()\n","sub_path":"python-2017/Minecraft-Pi-Python/PiM_DC/MinecraftPi/PiM_DC/Template.py","file_name":"Template.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"212923356","text":"import pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom rdflib import Graph, Literal, URIRef\nfrom rdflib.namespace import FOAF , XSD, DC, FOAF, SKOS, RDF, RDFS\n\nimport cleansing.contact as cls_contact\nfrom helper.functions import add_literal, concept_uri, export_data, export_df, exists_contact_cont, get_cleansed_data\nimport helper.namespaces as ns\n\ndef main(file, mode):\n contact_cleansed = get_cleansed_data(file, 'contact')\n\n g = Graph()\n\n for _, row in contact_cleansed.iterrows():\n abb_id, abb_uuid = concept_uri(ns.lblod + 'persoon/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']))\n\n g.add((abb_id, RDF.type, ns.person.Person))\n add_literal(g, abb_id, ns.mu.uuid, abb_uuid, XSD.string)\n add_literal(g, abb_id, FOAF.familyName, str(row['Familienaam Contact Cleansed']), XSD.string)\n add_literal(g, abb_id, ns.persoon.gebruikteVoornaam, str(row['Voornaam Contact Cleansed']), XSD.string)\n\n if exists_contact_cont(row):\n site_id, site_uuid = concept_uri(ns.lblod + 'vesting/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']))\n g.add((site_id, RDF.type, ns.org.Site))\n add_literal(g, site_id, ns.mu.uuid, site_uuid, XSD.string)\n\n contact_id, contact_uuid = concept_uri(ns.lblod + 'contactpunt/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + '1')\n g.add((contact_id, RDF.type, ns.schema.ContactPoint))\n add_literal(g, contact_id, ns.mu.uuid, contact_uuid, XSD.string)\n\n add_literal(g, contact_id, ns.schema.email, str(row['Titel Cleansed']), XSD.string)\n add_literal(g, contact_id, ns.schema.email, str(row['Mail nr2 Cleansed']), XSD.string)\n add_literal(g, contact_id, ns.schema.telephone, str(row['Telefoonnr Contact 1']), XSD.string) \n g.add((site_id, ns.schema.siteAddress, contact_id))\n\n if str(row['Telefoonnr Contact 2']) != str(np.nan):\n contact_tel2_id, contact_tel2_uuid = concept_uri(ns.lblod + 'contactpunt/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + str(row['Telefoonnr Contact 2']))\n g.add((contact_tel2_id, RDF.type, ns.schema.ContactPoint))\n add_literal(g, contact_tel2_id, ns.mu.uuid, contact_tel2_uuid, XSD.string)\n\n add_literal(g, contact_tel2_id, ns.schema.telephone, str(row['Telefoonnr Contact 2']), XSD.string) \n g.add((site_id, ns.schema.siteAddress, contact_tel2_id))\n\n if str(row['GSMnr Contact Cleansed']) != str(np.nan):\n contact_gsm_id, contact_gsm_uuid = concept_uri(ns.lblod + 'contactpunt/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + str(row['GSMnr Contact Cleansed']))\n g.add((contact_gsm_id, RDF.type, ns.schema.ContactPoint))\n add_literal(g, contact_gsm_id, ns.mu.uuid, contact_gsm_uuid, XSD.string)\n\n add_literal(g, contact_gsm_id, ns.schema.telephone, str(row['GSMnr Contact Cleansed']), XSD.string) \n g.add((site_id, ns.schema.siteAddress, contact_gsm_id))\n \n g.add((abb_id, ns.org.basedAt, site_id))\n \n if str(row['Id']) != str(np.nan):\n attr_id, _ = concept_uri(ns.lblod + 'gestructureerdeIdentificator/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']))\n g.add((attr_id, RDF.type, ns.generiek.GestructureerdeIdentificator))\n add_literal(g, attr_id, ns.generiek.lokaleIdentificator, str(row['Id']), XSD.string)\n\n g.add((abb_id, ns.generiek.gestructureerdeIdentificator, attr_id))\n\n org_id, _ = concept_uri(ns.lblod + 'organisatie/', str(row['organisation_id']))\n if (str(row['Decretale functie Cleansed']) == str(np.nan)) and (str(row['Functietitel Cleansed']) != str(np.nan)):\n position_id, _ = concept_uri(ns.lblod + 'hoedanigheid/', str(row['organisation_id']) + str(row['Functietitel Cleansed']))\n g.add((position_id, RDF.type, ns.organisatie.Hoedanigheid))\n\n # TODO: Map Functietitel properly\n role_id, _ = concept_uri(ns.lblod + 'rol/', str(row['Functietitel Cleansed']))\n g.add((role_id, RDF.type, ns.org.Role))\n add_literal(g, role_id, RDFS.label, str(row['Functietitel Cleansed']), XSD.string)\n\n g.add((position_id, ns.org.role, role_id))\n\n g.add((position_id, ns.org.postIn, org_id))\n g.add((org_id, ns.org.hasPost, position_id))\n\n g.add((abb_id, ns.org.holds, position_id))\n g.add((position_id, ns.org.heldBy, abb_id))\n elif str(row['Decretale functie Cleansed']) != str(np.nan):\n # Bestuur temporary\n bestuur_temporary, bestuur_uuid = concept_uri(ns.lblod + 'bestuursorgaan/', str(row['organisation_id']) + str(datetime.now()))\n g.add((bestuur_temporary, RDF.type, ns.besluit.Bestuursorgaan))\n add_literal(g, bestuur_temporary, ns.mu.uuid, bestuur_uuid, XSD.string)\n g.add((bestuur_temporary, ns.generiek.isTijdspecialisatieVan, org_id))\n\n ## Functionaris\n person_functionaris, _ = concept_uri(ns.lblod + 'functionaris/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + str(row['organisation_id']) + str(row['Decretale functie Cleansed'].lower().replace(\" \", \"\")))\n g.add((person_functionaris, RDF.type, ns.lblodlg.Functionaris))\n g.add((person_functionaris, ns.mandaat.isBestuurlijkeAliasVan, abb_id))\n #start\n #einde\n #status ~ cf loket lokale besturen PoC https://poc-form-builder.relance.s.redpencil.io/codelijsten\n # https://data.vlaanderen.be/id/conceptscheme/MandatarisStatusCode\n g.add((person_functionaris, ns.mandaat.status, ns.functionaris_status[row['Functionaris status']]))\n g.add((abb_id, ns.mandaat.isAangesteldAls, person_functionaris))\n\n # https://data.vlaanderen.be/doc/conceptscheme/BestuursfunctieCode\n ## Bestuuursfunctie\n person_bestuursfunctie, person_bestuursfunctie_uuid = concept_uri(ns.lblod + 'bestuursfunctie/', str(row['Voornaam Contact Cleansed']) + str(row['Familienaam Contact Cleansed']) + str(row['organisation_id']))\n g.add((person_bestuursfunctie, RDF.type, ns.lblodlg.Bestuursfunctie))\n add_literal(g, person_bestuursfunctie, ns.mu.uuid, person_bestuursfunctie_uuid, XSD.string)\n\n g.add((person_bestuursfunctie, ns.org.role, ns.bestursfunctie_code[row['Decretale functie Cleansed']]))\n g.add((person_bestuursfunctie, ns.org.heldBy, person_functionaris))\n g.add((person_functionaris, ns.org.holds, person_bestuursfunctie))\n\n g.add((bestuur_temporary, ns.org.hasPost, person_bestuursfunctie))\n g.add((person_bestuursfunctie, ns.org.postIn, bestuur_temporary))\n\n\n export_data(g, f'contact-{mode}')","sub_path":"mapping/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":6642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"421361062","text":"from django.db import models\nfrom cases_app.models import Cases\nfrom donors_app.models import Donors\n\n# Create your models here.\nclass Donations(models.Model):\n donor_name = models.ForeignKey(Donors, on_delete=models.SET_NULL, null=True)\n case_name = models.ForeignKey(Cases, on_delete=models.SET_NULL, null=True, related_name='donation_cases')\n donation_amount = models.PositiveIntegerField()\n paid_flag = models.BooleanField()\n\n def __str__(self):\n return self.case_name.case_name + ' / ' + str(self.donation_amount)\n\n","sub_path":"charity_project/charity/donations_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"346803325","text":"# Create a SQLite3 database and table\n\nimport sqlite3\n\nconn = sqlite3.connect(\"new.db\") # creates new database\n#conn = sqlite3.connect(\":memory:\") # would create a memory-only database (not persisted)\n\ncursor = conn.cursor() # creates cursor object to execute SQL commands\n\ncursor.execute(\"\"\"INSERT INTO population VALUES('New York City','NY',8200000)\"\"\") # insert data into table\ncursor.execute(\"\"\"INSERT INTO population VALUES('San Francisco','CA',800000)\"\"\")\n\nconn.commit() # commit changes to database\n\nconn.close() # close database connection\n\n\n\n","sub_path":"sqlb.py","file_name":"sqlb.py","file_ext":"py","file_size_in_byte":552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"470360011","text":"def mergeInBetween(self, list1: ListNode, a: int, b: int, list2: ListNode) -> ListNode:\n ''' basic linked list, get to a certain vertex and continue on\n '''\n \n # set dummy and actual movement\n dummy = final = ListNode(-1)\n \n final.next = list1\n \n # go to a\n for _ in range(a):\n final = final.next\n \n temp = final.next\n final.next = list2\n \n # go past list 2\n while final.next is not None:\n final = final.next\n \n for _ in range(b-a+1):\n temp = temp.next\n \n \n # add rest of list 1\n final.next = temp\n return dummy.next","sub_path":"mergeinbetweenlinkedlist.py","file_name":"mergeinbetweenlinkedlist.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"527805115","text":"\"\"\"\nProgrammer: Chris Tralie / IDS 301 Class\nPurpose: To load in Trump's tweets since 11/1/2016, and\n to do some data wrangling on them\n\"\"\"\n\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\n# A dictionary for converting from the 3 letter months\n# that Twitter gives back to a 2-digit month string\nMONTHS = {'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04', 'May':'05', 'Jun':'06', 'Jul':'07', 'Aug':'08', 'Sep':'09', 'Oct':'10', 'Nov':'11', 'Dec':'12'}\n\n\ndef get_devices(tweets):\n \"\"\"\n Print out a dictionary which counts how many tweets \n Trump made on each different type of device\n Parameters\n ----------\n tweets: list of dictionary\n A list of tweets, each of which is a dictionary\n \"\"\"\n devices = {} # The dictionary will hold \"device name\":counts\n for tweet in tweets: # This is one way to loop through a list\n device = tweet['source']\n # If the device hasn't been seen yet, we need to make\n # A key for it in the dictionary\n if not (device in devices):\n devices[device] = 0 # Set the initial count to be zero\n devices[device] += 1 # Add one to the counts for this device\n print(devices)\n\ndef get_most_favorited(tweets):\n \"\"\"\n Print out the tweet with the maximum number of retweets\n Parameters\n ----------\n tweets: list of dictionary\n A list of tweets, each of which is a dictionary\n \"\"\"\n # First, we setup a parallel numpy array with the same\n # number of elements as there are tweets\n counts = np.zeros(len(tweets))\n # Then, this loop fills the list with the retweet counts\n for i, tweet in enumerate(tweets):\n counts[i] = tweet['retweet_count']\n # Finally, we can use the nifty \"argmax\" function in\n # numpy to pull out the index with the maximum counts\n max_index = np.argmax(counts)\n # We then use this index back in the original tweets list\n # to print out the tweet with the maximum counts\n print(tweets[max_index])\n\ndef get_tweet_date(tweet):\n \"\"\"\n Return a date in Year/MM/DD format, which ensures\n that sorting by the string will sort the tweets in\n alphabetical order\n Parameters\n ----------\n tweet: dictionary\n The tweet dictionary\n Returns\n -------\n day: Year/MM/DD string\n \"\"\"\n date = tweet['created_at']\n # Separate out date into components in a list\n # Each element is a different component separated\n # by a space\n fields = date.split() \n # The year is the last field\n year = fields[-1]\n # Use the dictionary defined at the top of the file\n # to convert from a three letter month to a two digit month\n month = MONTHS[fields[1]] \n # This magic code formats a day to be 2 digits, potentially\n # with a leading zero\n day = \"%02d\"%int(fields[2]) \n return year + \"/\" + month + \"/\" + day\n\n\ntweets = pickle.load(open(\"trumpSinceElection.dat\", \"rb\"))\nget_devices(tweets)\nget_most_favorited(tweets)\nprint(get_tweet_date(tweets[0]))","sub_path":"Twitter.py","file_name":"Twitter.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"113604278","text":"'''\n 11404 플로이드\n 알고리즘:\n 1. 플로이드 알고리즘 사용\n 2. 한 도시에서 다른 도시로 가는 노선이 여러개인 경우, 최솟값을 넣어서 최단거리가 될 수 있도록 한다\n'''\nimport sys\nn = int(input())\nm = int(input())\nINF = int(1e9)\ngraph = [[INF]*(n+1) for i in range(n+1)]\n\nfor i in range(1, n+1):\n for j in range(1, n+1):\n if i == j: # 시작 도시와 도착 도시가 같은 경우는 없다는 조건\n graph[i][j] = 0\n\nfor i in range(m):\n a, b, c = map(int, sys.stdin.readline().split())\n graph[a][b] = min(graph[a][b], c) # 도시로 가는 노선이 여러개라면, 최단거리를 가기 위해서는 최솟값이 들어가야한다\n \n# 플로이드 알고리즘\nfor k in range(1, n+1):\n for i in range(1, n+1):\n for j in range(1, n+1):\n graph[i][j] = min(graph[i][j], graph[i][k]+graph[k][j])\n\n# 결과 출력\nfor i in range(1, n+1):\n for j in range(1, n+1):\n if graph[i][j] == INF: # 갈 수 없는 경우 0 출력\n print(0, end = ' ')\n else:\n print(graph[i][j], end = ' ')\n print()","sub_path":"11404.py","file_name":"11404.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"335483293","text":"from converter import Converter\nfrom validator import Validator\n\nclass Uzbekistan:\n\n\tdef __init__(self, data):\n\t\tself.name = 'Uzbekistan Airways'\n\n\t\tself.totalFare = int(data['totalFare'])\t\t# total fare ok booking\n\t\tself.baseFare = int(data['baseFare'])\t\t# base fare of booking\n\t\tself.rules = data['rules']\t\t\t\t\t# text of fare rules\n\t\tself.taxes = data['taxes']\t\t\t\t\t# array of pairs type of taxe and its amount\n\t\tself.now = data['dates'][0]\t\t\t\t\t# current date\n\t\tself.depDate = data['dates'][1]\t\t\t\t# departure date\n\t\tself.currency = data['currencies']\n\n\t\tself.charge = ''\n\t\tself.charge_cur = ''\n\t\tself.percent = False\n\t\tself.penalty = ''\n\n\t\t# print('Total fare is ' + str(self.totalFare))\n\t\t# print('Base fare is ' + str(self.baseFare))\n\t\t# print('Taxes are ' + str(self.taxes))\n\t\t# print('Departure date is ' + str(self.depDate))\n\t\t# print(self.currency)\n\n\t\t# print(self.rules)\n\n\t\tself.dom = True\n\n\t\tself.__set_values()\n\n\t\t# print('Fare rules is ' + str(self.rules))\n\n\t\tself.non_ref = []\t\t\t\t# array of nonrefundable taxes` types\n\n\tdef calculate(self):\n\t\tc = Converter()\n\n\t\t# print(c.currencies())\n\n\t\tif self.__check_status():\n\n\t\t\tif self.charge != '' and self.charge_cur != '':\n\t\t\t\t# print(self.charge_cur)\n\t\t\t\t# print(self.charge)\n\t\t\t\t# print(self.currency)\n\n\t\t\t\tself.penalty = c.calc(self.charge_cur, float(self.charge), self.currency)\n\n\t\t\t\t# print(self.penalty)\n\t\t\t\t\n\t\t\telif self.charge != '' and self.percent:\n\t\t\t\tself.penalty = round(self.baseFare * self.percent / 100)\n\n\t\t\t# print(self.penalty)\n\n\t\t\tself.non_ref_tax, self.ref_tax = self.__calc_taxes()\n\n\t\t\tself.total = self.totalFare - self.penalty - self.non_ref_tax\n\n\t\t\tdata = self.__get_data()\n\n\t\t\treturn data\n\n\tdef __get_data(self):\n\t\tdata = {}\n\n\t\tdata['non_refundable taxes'] = self.non_ref\n\t\tdata['penalty'] = self.penalty\n\n\t\tdata['refunded_fare'] = self.baseFare - self.penalty\n\t\tdata['refunded_taxes'] = self.ref_tax\n\t\tdata['refunded_total'] = self.total\n\t\tdata['name'] = self.name\n\n\t\treturn data\n\n\tdef __calc_taxes(self):\t\t\t# get nonrefundable taxes\n\t\tnon_ref = 0\n\t\tref = 0\n\n\t\tfor tax in self.taxes:\n\t\t\tif tax['Type'] in self.non_ref:\n\t\t\t\tnon_ref += int(tax['Amount'])\n\n\t\t\telse:\n\t\t\t\tref += int(tax['Amount'])\n\n\t\treturn non_ref, ref\n\n\tdef __check_status(self):\t\t# check status of flight\n\t\treturn self.now < self.depDate\n\n\tdef __set_values(self):\n\t\tv = Validator()\n\n\t\tps = self.rules.split('\\n\\n')\n\n\t\t# print(ps)\n\n\t\tif 'BETWEEN' in ps[0] and 'UZBEKISTAN' in ps[0]:\n\t\t\tself.dom = False\n\t\n\t\tfor p in ps:\n\t\t\t\n\t\t\tp = p.replace('\\n', ' ').replace(' ', ' ')\n\t\t\t# print(p)\n\t\t\t# print()\n\t\t\tif self.dom:\n\t\t\t\tif 'REFUND' in p and 'CANCELLATION' in p and 'CHANGES' not in p:\n\t\t\t\t\tqwe = p.split('.')\n\n\t\t\t\t\tfor qw in qwe:\n\t\t\t\t\t\tif 'REFUND' in qw and 'CHARGE' in qw:\n\t\t\t\t\t\t\tfor i in range(len(qw)):\n\t\t\t\t\t\t\t\tif v.is_number(qw[i]):\n\t\t\t\t\t\t\t\t\tself.charge = qw[i]\n\n\t\t\t\t\t\t\t\t\tif v.is_percent(qw[i+1]):\n\t\t\t\t\t\t\t\t\t\tself.percent = True\n\n\t\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t\t\t\tif v.is_percent(qw[i]):\n\t\t\t\t\t\t\t\t\tself.percent = True\n\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\t# print(self.charge, '%')\n\n\t\t\t\t\tbreak\n\n\n\t\t\telse:\n\t\t\t\tif 'CANCELLATIONS PERMITTED' in p and 'BEFORE DEPARTURE' in p and 'REFUND' in p:\n\t\t\t\t\t# print(p)\n\t\t\t\t\t# print(len(p))\n\t\t\t\t\t\n\t\t\t\t\ts = list(p)\n\n\t\t\t\t\tfor i in range(1, len(s) - 1):\n\t\t\t\t\t\tif s[i] == '.' and not v.is_number(s[i-1]) and not v.is_number(s[i+1]):\n\t\t\t\t\t\t\ts[i] = ''\n\n\t\t\t\t\tp = ''.join(s)\n\n\t\t\t\t\tqwe = p.split(' ')\n\n\t\t\t\t\ti = qwe.index('CHARGE')\n\n\t\t\t\t\tif v.is_currency(qwe[i+1]):\n\t\t\t\t\t\tself.charge_cur = qwe[i+1]\n\n\t\t\t\t\t\tif v.is_number(qwe[i+2]):\n\t\t\t\t\t\t\tself.charge = qwe[i+2]\n\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tfor qw in qwe:\n\t\t\t\t\t\t\t\tif v.is_number(qw):\n\t\t\t\t\t\t\t\t\tself.charge = qwe[i+1]\n\t\t\t\t\t\t\t\t\tbreak\n\n\t\t\t\t\tprint(self.charge, self.charge_cur)\n\n\t\t\t\t\tbreak\n\n\tdef __split_all(self, p):\n\t\tqwe = []\n\n\t\twordsss = p.split('\\n')\n\n\t\tfor wordss in wordsss:\n\n\t\t\twords = wordss.split(' ')\n\n\t\t\tfor word in words:\n\t\t\t\tif not self.__is_number(word):\n\t\t\t\t\tword = word.replace('.', '')\n\t\t\t\tqwe.append(word)\n\n\t\treturn qwe","sub_path":"uzbekistan.py","file_name":"uzbekistan.py","file_ext":"py","file_size_in_byte":3916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"259614559","text":"from controller import Robot, Camera\nimport cv2 as cv\nimport numpy as np\n#from time import sleep\n\nrobot = Robot()\ntimestep = int(robot.getBasicTimeStep())\n\ncamera1 = robot.getDevice(\"camera1\")\ncamera1.enable(timestep)\ncamera2 = robot.getDevice(\"camera2\")\ncamera2.enable(timestep)\nflag = True\n\ndef empty(a):\n pass\n\ndef vconcat_different_size_images(im_list, interpolation=cv.INTER_CUBIC):\n w_min = min(im.shape[1] for im in im_list)\n im_list_resize = [cv.resize(im, (w_min, int(im.shape[0] * w_min / im.shape[1])), interpolation=interpolation)\n for im in im_list]\n return cv.vconcat(im_list_resize)\n\ncv.namedWindow(\"trackBars\")\ncv.resizeWindow(\"trackBars\", 640,240)\ncv.createTrackbar(\"hue mini\", \"trackBars\", 51, 255, empty),\ncv.createTrackbar(\"hue max\", \"trackBars\", 96, 255, empty),\ncv.createTrackbar(\"saturation mini\", \"trackBars\", 0, 255, empty),\ncv.createTrackbar(\"saturation max\", \"trackBars\", 224, 255, empty),\ncv.createTrackbar(\"min value\", \"trackBars\", 127 , 255, empty),\ncv.createTrackbar(\"max value\", \"trackBars\", 255, 255, empty),\n\n\n\nwhile robot.step(timestep) != -1:\n image1 = camera1.getImage()\n image1 = np.frombuffer(image1, np.uint8).reshape((camera1.getHeight(), camera1.getWidth(), 4))\n image1 = np.array(image1 ,dtype=np.uint8)\n \n image2 = camera2.getImage()\n image2 = np.frombuffer(image2, np.uint8).reshape((camera2.getHeight(), camera2.getWidth(), 4))\n image2 = np.array(image2 ,dtype=np.uint8)\n \n hsv_image1 = cv.cvtColor(image1, cv.COLOR_BGRA2BGR)\n hsv_image2 = cv.cvtColor(image2, cv.COLOR_BGRA2BGR)\n hue_min=cv.getTrackbarPos(\"hue mini\", \"trackBars\")\n hue_max=cv.getTrackbarPos(\"hue max\", \"trackBars\")\n\n saturation_min=cv.getTrackbarPos(\"saturation mini\", \"trackBars\")\n saturation_max=cv.getTrackbarPos(\"saturation max\", \"trackBars\")\n \n min_value=cv.getTrackbarPos(\"min value\", \"trackBars\")\n max_value=cv.getTrackbarPos(\"max value\", \"trackBars\")\n\n #print(f\"The min hue is -> {hue_min}\\tThe max hue is -> {hue_max}\\tThe min saturation is -> {saturation_min}\\tThe max saturation is -> {saturation_max}\\tThe min value is -> {min_value}\\tThe max value is -> {max_value}\")\n\n lower = np.array([hue_min, saturation_min, min_value])\n upper = np.array([hue_max, saturation_max, max_value])\n \n mask1 = cv.inRange(hsv_image1, lower, upper)\n mask2 = cv.inRange(hsv_image2, lower, upper)\n imgResult1 = cv.bitwise_and(image1, image1, mask=mask1)\n imgResult2 = cv.bitwise_and(image2, image2, mask=mask2)\n \n\n both_mask_images = cv.hconcat([mask1, mask2])\n both_final_results = cv.hconcat([imgResult1, imgResult2])\n rows_list = [both_mask_images, both_final_results]\n \n\n cv.imshow(\"Camera panel masks\", both_mask_images)\n cv.imshow(\"Camera panel final results\", both_final_results)\n \n gridOfValues = both_mask_images\n for i in gridOfValues:\n for a in i:\n if a == 255:\n if flag == True:\n print(\"I spot something...\")\n flag=False\n else:\n pass\n\n cv.waitKey(1)","sub_path":"Alumnos/Maximo_Cansino/color_detection_simulationV3.py","file_name":"color_detection_simulationV3.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"117756263","text":"import FWCore.ParameterSet.Config as cms\n\nfrom PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask\n\nprocess = cms.Process(\"bphAnalysis\")\n\npatAlgosToolsTask = getPatAlgosToolsTask(process)\n\n#process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(1000) )\n\nprocess.load(\"Configuration.Geometry.GeometryRecoDB_cff\")\nprocess.load(\"Configuration.StandardSequences.MagneticField_cff\")\nprocess.load('Configuration.StandardSequences.Services_cff')\nprocess.load('SimGeneral.HepPDTESSource.pythiapdt_cfi')\nprocess.load('FWCore.MessageService.MessageLogger_cfi')\nprocess.load('Configuration.EventContent.EventContent_cff')\nprocess.load('Configuration.StandardSequences.GeometryRecoDB_cff')\nprocess.load('Configuration.StandardSequences.MagneticField_AutoFromDBCurrent_cff')\nprocess.load('Configuration.StandardSequences.EndOfProcess_cff')\npatAlgosToolsTask.add(process.MEtoEDMConverter)\nprocess.load('Configuration.StandardSequences.FrontierConditions_GlobalTag_cff')\nprocess.load(\"TrackingTools/TransientTrack/TransientTrackBuilder_cfi\")\n\nprocess.CandidateSelectedTracks = cms.EDProducer( \"ConcreteChargedCandidateProducer\",\n src=cms.InputTag(\"oniaSelectedTracks::RECO\"),\n particleType=cms.string('pi+')\n)\npatAlgosToolsTask.add(process.CandidateSelectedTracks)\n\n\nfrom PhysicsTools.PatAlgos.producersLayer1.genericParticleProducer_cfi import patGenericParticles\nprocess.patSelectedTracks = patGenericParticles.clone(src=cms.InputTag(\"CandidateSelectedTracks\"))\npatAlgosToolsTask.add(process.patSelectedTracks)\n\n\nprocess.MessageLogger.cerr.FwkReport.reportEvery = 100\nprocess.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )\n\nprocess.source = cms.Source(\"PoolSource\",fileNames = cms.untracked.vstring(\n#\n### use this to access the nearest copy of the input file, querying the catalog\n#\n '/store/data/Run2016E/Charmonium/USER/BPHSkim-PromptReco-v2/000/276/831/00000/00FD1519-714D-E611-B686-FA163E321AE0.root'\n### use this to access the input file if by any reason you want to specify \n### the data server\n# 'root://xrootd-cms.infn.it//store/data/Run2016E/Charmonium/USER/BPHSkim-PromptReco-v2/000/276/831/00000/00FD1519-714D-E611-B686-FA163E321AE0.root'\n#\n### use this to access an input file locally available\n# 'file:/...complete_file_path.../XXXX.root'\n))\n\nfrom Configuration.AlCa.GlobalTag import GlobalTag\nprocess.GlobalTag = GlobalTag(process.GlobalTag, 'auto:run2_data', '')\n\nprocess.testBPHSpecificDecay = cms.EDAnalyzer('TestBPHSpecificDecay',\n gpCandsLabel = cms.string('patSelectedTracks'),\n ccCandsLabel = cms.string('onia2MuMuPAT::RECO'),\n outDump = cms.string('dump_skim.txt'),\n outHist = cms.string('hist_skim.root')\n)\n\nprocess.p = cms.Path(\n process.testBPHSpecificDecay,\n patAlgosToolsTask\n)\n\n","sub_path":"HeavyFlavorAnalysis/SpecificDecay/test/cfg_skim.py","file_name":"cfg_skim.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"615065675","text":"import numpy as np\nimport torch\nfrom torchvision.transforms.functional import normalize, to_tensor\n\nfrom catalyst.utils.image import tensor_to_ndimage, \\\n _IMAGENET_MEAN, _IMAGENET_STD\n\n\ndef test_tensor_to_ndimage():\n orig_images = np.random.randint(0, 255, (2, 20, 10, 3), np.uint8)\n\n torch_images = torch.stack(\n [\n normalize(to_tensor(im), _IMAGENET_MEAN, _IMAGENET_STD)\n for im in orig_images\n ],\n dim=0\n )\n\n byte_images = tensor_to_ndimage(torch_images, dtype=np.uint8)\n float_images = tensor_to_ndimage(torch_images, dtype=np.float32)\n\n assert np.allclose(byte_images, orig_images)\n assert np.allclose(float_images, orig_images / 255, atol=1e-3, rtol=1e-3)\n\n assert np.allclose(\n tensor_to_ndimage(torch_images[0]),\n orig_images[0] / 255,\n atol=1e-3,\n rtol=1e-3\n )\n","sub_path":"catalyst/utils/tests/test_image.py","file_name":"test_image.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"333676288","text":"\"\"\"\"\nEdited MNIST logistic regression to predict the notMNIST\ndata with TensorFlow\n\n\"\"\"\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport time\nimport json\nimport os\n\n# Define params for the model\n\nwith open('config.json') as config_file:\n config = json.load(config_file)\n\nlearning_rate = config['learning_rate']\nbatch_size = config['batch_size']\nn_epochs = config['n_epochs']\n\n# Step 1: Read in data\nnot_mnist = input_data.read_data_sets('notMNIST_data', one_hot=True)\n\n# Step 2: create placeholders for features and labels\n# each image in the notMNIST data is of shape 28*28 = 784\n# therefore, each image is represented with a 1x784 tensor\n# there are 10 classes for each image, correspondong to letters A-J\n# labels follow a one-hot-encoding\nX = tf.placeholder(tf.float32, [batch_size, 784], name='X_placeholder')\nY = tf.placeholder(tf.float32, [batch_size, 10], name='Y_placeholder')\n\n# Step 3: create weights and bias\n# w is initialized to random variables with mean of 0, stddev of 0.01\n# b is initialized to 0\n# shape of w depends on the dimension of X and Y so that Y = tf.matmul(X, w)\n# shape of b depends on Y\nw = tf.Variable(tf.random_normal(shape=[784, 10], stddev=0.01), name='weights')\nb = tf.Variable(tf.zeros([1, 10]), name='bias')\n\n# Step 4: Build model\n# the model that returns the logits\n# this logit will be later passed though a softmax layer\nlogits = tf.matmul(X, w) + b\n\n# Step 5: define loss function\n# use cross entropy of softmax of logits as the loss function\nentropy = tf.nn.softmax_cross_entropy_with_logits(labels=Y,\n logits=logits, name='loss')\n\nloss = tf.reduce_mean(entropy)\n\n# Step 6: define training op.\noptimizer_list = {\n \"gradient_descent\": lambda learn_rate, loss:\n tf.train.GradientDescentOptimizer(learn_rate).minimize(loss),\n \"adadelta\": lambda learn_rate, loss:\n tf.train.AdadeltaOptimizer(learn_rate).minimize(loss),\n \"adam\": lambda learn_rate, loss:\n tf.train.AdamOptimizer(learn_rate).minimize(loss)\n}\n\nfor key, value in config['optimizer'].items():\n if value:\n optimizer_func = optimizer_list[key]\n\noptimizer = optimizer_func(learning_rate, loss)\n\nwith tf.Session() as sess:\n\n output = {\"train_samples\": -1,\n \"test_samples\": -1,\n \"accuracy\": -1,\n \"time\": -1\n }\n # to visualize using TensorBoard\n writer = tf.summary.FileWriter('./graph', sess.graph)\n\n # print('samples: train {0} \\n test {1}'\n # .format(not_mnist.train.num_examples,\n # not_mnist.test.num_examples))\n output[\"train_samples\"] = not_mnist.train.num_examples\n output[\"test_samples\"] = not_mnist.test.num_examples\n\n start_time = time.time()\n sess.run(tf.global_variables_initializer())\n n_batches = int(not_mnist.train.num_examples / batch_size)\n\n for i in range(n_epochs):\n total_loss = 0\n\n for _ in range(n_batches):\n X_batch, Y_batch = not_mnist.train.next_batch(batch_size)\n _, loss_batch = sess.run([optimizer, loss],\n feed_dict={X: X_batch, Y: Y_batch})\n total_loss += loss_batch\n print('Average loss epoch {0}: {1}'.format(i, total_loss / n_batches))\n\n print('Optimization Finished!')\n\n # Test the model\n n_batches = int(not_mnist.test.num_examples / batch_size)\n\n total_correct_preds = 0\n\n for i in range(n_batches):\n X_batch, Y_batch = not_mnist.test.next_batch(batch_size)\n _, loss_batch, logits_batch = sess.run([optimizer, loss, logits],\n feed_dict={X: X_batch,\n Y: Y_batch})\n preds = tf.nn.softmax(logits_batch)\n correct_preds = tf.equal(tf.argmax(preds, 1), tf.argmax(Y_batch, 1))\n accuracy = tf.reduce_sum(tf.cast(correct_preds, tf.float32))\n total_correct_preds += sess.run(accuracy)\n\n print('Accuracy {0}'.format(total_correct_preds /\n not_mnist.test.num_examples))\n output[\"accuracy\"] = total_correct_preds / not_mnist.test.num_examples\n output[\"time\"] = time.time() - start_time\n\n # Write results in a file\n agg_outputs = []\n\n if not os.path.exists('results.json'):\n with open('results.json', 'w+') as f:\n f.write('[]')\n\n with open('results.json', 'r') as output_file:\n agg_outputs = json.load(output_file)\n\n # new Python 3.5 syntax\n config_and_result = {**config, **output}\n agg_outputs.append(config_and_result)\n\n # Pretty Print the results\n with open('results.json', 'w') as output_file:\n json.dump(agg_outputs, output_file, sort_keys=True,\n indent=4, separators=(',', ': '))\n\n writer.close()\n sess.close()\n","sub_path":"sprint2_stanford_tf_cs20SI/src/nikhaas/01_not_mnist/logistic_regression_not_mnist.py","file_name":"logistic_regression_not_mnist.py","file_ext":"py","file_size_in_byte":4839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"489378164","text":"# -*- coding:utf-8 -*-\nfrom numpy import *\nfrom NaiveBayes import bayes\nfrom Utils import Config\n\nclass Test(object):\n\n bayes = bayes.Bayes()\n\n def testingNB(self):\n listOPosts, listClasses = self.bayes.loadDataSet()\n myVocabList = self.bayes.createVocabList(listOPosts)\n trainMat = []\n for postinDoc in listOPosts:\n trainMat.append(self.bayes.setOfWords2Vec(myVocabList, postinDoc))\n p0V, p1V, pAb = self.bayes.trainNB0(array(trainMat), array(listClasses))\n testEntry = ['love', 'my', 'dalmation']\n thisDoc = array(self.bayes.setOfWords2Vec(myVocabList, testEntry))\n testEntry = ['stupid', 'garbage']\n thisDoc = array(self.bayes.setOfWords2Vec(myVocabList, testEntry))\n print(testEntry, 'classified as: ', self.bayes.classifyNB(thisDoc, p0V, p1V, pAb))\n\n # 测试书上例子\n def testingNB01(self):\n list_X = [\n [1, 'S'],\n [1, 'M'],\n [1, 'M'],\n [1, 'S'],\n [1, 'S'],\n [2, 'S'],\n [2, 'M'],\n [2, 'M'],\n [2, 'L'],\n [2, 'L'],\n [3, 'L'],\n [3, 'M'],\n [3, 'M'],\n [3, 'L'],\n [3, 'L']\n ]\n list_Y = [-1,-1,1,1,-1,-1,-1,1,1,1,1,1,1,1,-1]\n # listOPosts, listClasses = self.bayes.loadDataSet()\n mylist = self.bayes.createVocabList(list_X)\n trainMat = []\n for x in list_X:\n trainMat.append(self.bayes.setOfWords2Vec(mylist, x))\n p0V, p1V, pAb = self.bayes.trainNB0(array(trainMat), array(list_Y))\n test_X = [2, 'S']\n # res = array(self.bayes.setOfWords2Vec(mylist, test_X))\n\n res = array(self.bayes.setOfWords2Vec(mylist, test_X))\n print(test_X, 'classified as: ', self.bayes.classifyNB(res, p0V, p1V, pAb))\n\n\n # 测试函数\n def spamTest(self):\n docList = []\n classList = []\n fullText = []\n for i in range(1, 26):\n # 导入文件 并解析成词列表\n wordList = self.bayes.textParse(open(Config.DATAS + 'NaiveBayes/email/spam/%d.txt' % i).read())\n docList.append(wordList)\n fullText.extend(wordList)\n classList.append(1)\n wordList = self.bayes.textParse(open(Config.DATAS + 'NaiveBayes/email/ham/%d.txt' % i).read())\n docList.append(wordList)\n fullText.extend(wordList)\n classList.append(0)\n vocabList = self.bayes.createVocabList(docList) # create vocabulary\n trainingSet = range(50);\n testSet = [] # 随机构建测试函数\n for i in range(10):\n randIndex = int(random.uniform(0, len(trainingSet)))\n testSet.append(trainingSet[randIndex])\n del (trainingSet[randIndex])\n trainMat = []\n trainClasses = []\n for docIndex in trainingSet: # 测试分类器\n trainMat.append(self.bayes.bagOfWords2VecMN(vocabList, docList[docIndex]))\n trainClasses.append(classList[docIndex])\n p0V, p1V, pSpam = self.bayes.trainNB0(array(trainMat), array(trainClasses))\n errorCount = 0\n for docIndex in testSet: # classify the remaining items\n wordVector = self.bayes.bagOfWords2VecMN(vocabList, docList[docIndex])\n if self.bayes.classifyNB(array(wordVector), p0V, p1V, pSpam) != classList[docIndex]:\n errorCount += 1\n print(\"classification error\", docList[docIndex])\n e = float(errorCount) / len(testSet)\n return e\n print('the error rate is: ', e)\n\n\nif __name__ == '__main__':\n # Test().testingNB()\n Test().testingNB01()\n","sub_path":"src/NaiveBayes/TestBayes.py","file_name":"TestBayes.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"209785280","text":"from django.db import models\n\n# Create your models here.\nfrom timetables.models import Timetable\nfrom django import forms\n#class Timetable(models.Model):\n # pass\n\nMONDAY = 0\nTUESDAY = 1\nWEDNESDAY = 2\nTHURSDAY = 3\nFRIDAY = 4\nSATURDAY = 5\nSUNDAY = 6\nDAY_CHOICES = (\n (MONDAY, 'Monday'),\n (TUESDAY, 'Tuesday'),\n (WEDNESDAY, 'Wednesday'),\n (THURSDAY, 'Thursday'),\n (FRIDAY, 'Friday'),\n (SATURDAY, 'Saturday'),\n (SUNDAY, 'Sunday')\n)\n\nORDER_CHOICES = (\n (1, '1'),\n (2, '2'),\n (3, '3'),\n (4, '4'),\n (5, '5'),\n (6, '6'),\n (7, '7'),\n (8, '8'),\n (9, '9'),\n (10, '10'),\n)\n\n\nclass Period(models.Model):\n code = models.CharField(max_length=10)\n name = models.CharField(max_length=30)\n lecturer = models.CharField(max_length=30)\n length = models.IntegerField(max_length=2)\n timetable = models.ForeignKey(Timetable)\n position = models.IntegerField(max_length=2)\n\n\n","sub_path":"periods/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"1947665","text":"from pyspark.sql import SparkSession\n\nspark = SparkSession.builder \\\n .appName(\"demo01\") \\\n .config(\"spark.sql.shuffle.partitions\", \"4\") \\\n .getOrCreate()\n\nemp_df = spark.read.parquet(\"/tmp/data01_csv\")\n\nemp_df.createOrReplaceTempView(\"emp_view\")\n\nresult1 = spark.sql(\"SELECT job, AVG(sal) avgsal FROM emp_view GROUP BY job ORDER BY job\")\nresult1.show()\nresult1.explain()\n\nresult2 = emp_df \\\n .groupBy(\"job\") \\\n .avg(\"sal\") \\\n .orderBy(\"job\")\nresult2.show()\nresult2.explain()\n\nspark.stop()\n","sub_path":"spark/sparkSQL/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"627271334","text":"from django.db.models import Sum, Q\nfrom django.utils.translation import gettext as _, gettext_lazy\n\nfrom lib.templatetags.custom_filters import nz\nfrom shared_models import models as shared_models\nfrom . import models\n\n\ndef get_help_text_dict():\n my_dict = {}\n for obj in models.HelpText.objects.all():\n my_dict[obj.field_name] = str(obj)\n\n return my_dict\n\n\ndef in_projects_admin_group(user):\n \"\"\"\n Will return True if user is in project_admin group\n \"\"\"\n if user:\n return user.groups.filter(name='projects_admin').exists()\n\n\ndef is_management(user):\n \"\"\"\n Will return True if user is in project_admin group, or if user is listed as a head of a section, division or branch\n \"\"\"\n if user and user.id:\n return shared_models.Section.objects.filter(head=user).exists() or \\\n shared_models.Division.objects.filter(head=user).exists() or \\\n shared_models.Branch.objects.filter(head=user).exists()\n\n\ndef is_management_or_admin(user):\n \"\"\"\n Will return True if user is in project_admin group, or if user is listed as a head of a section, division or branch\n \"\"\"\n if user.id:\n return in_projects_admin_group(user) or is_management(user)\n\n\ndef is_section_head(user, project):\n try:\n return True if project.section.head == user else False\n except AttributeError as e:\n print(e)\n\n\ndef is_division_manager(user, project):\n try:\n return True if project.section.division.head == user else False\n except AttributeError:\n pass\n\n\ndef is_rds(user, project=None):\n if project:\n try:\n return True if project.section.division.branch.head == user else False\n except AttributeError:\n pass\n else:\n return shared_models.Branch.objects.filter(head=user).exists()\n\n\ndef is_project_lead(user, project_id=None, project_year_id=None):\n \"\"\"\n returns True if user is among the project's project leads\n \"\"\"\n if user.id:\n project = None\n if project_year_id:\n project = models.ProjectYear.objects.get(pk=project_year_id).project\n elif project_id:\n project = models.Project.objects.get(pk=project_id)\n\n if project:\n return user in [s.user for s in models.Staff.objects.filter(project_year__project=project, is_lead=True)]\n\n\ndef can_modify_project(user, project_id, return_as_dict=False):\n \"\"\"\n returns True if user has permissions to delete or modify a project\n The answer of this question will depend on whether the project is submitted. Project leads cannot edit a submitted project\n \"\"\"\n my_dict = dict(can_modify=False, reason=_(\"You are not logged in\"))\n\n if user.id:\n\n my_dict[\"reason\"] = \"You are not a project lead or manager of this project\"\n project = models.Project.objects.get(pk=project_id)\n\n # check to see if a superuser or projects_admin -- both are allow to modify projects\n if in_projects_admin_group(user):\n my_dict[\"reason\"] = \"You can modify this record because you are a system administrator\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are a section head\n elif is_section_head(user, project):\n my_dict[\"reason\"] = \"You can modify this record because it falls under your section\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are a div. manager\n elif is_division_manager(user, project):\n my_dict[\"reason\"] = \"You can modify this record because it falls under your division\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are an RDS\n elif is_rds(user, project):\n my_dict[\"reason\"] = \"You can modify this record because it falls under your branch\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are a project lead\n elif is_project_lead(user, project_id=project.id):\n my_dict[\"reason\"] = \"You can modify this record because you are a project lead\"\n my_dict[\"can_modify\"] = True\n\n # check to see if they are a project lead\n elif not models.Staff.objects.filter(project_year__project=project, is_lead=True).exists():\n my_dict[\"reason\"] = \"You can modify this record because there are currently no project leads\"\n my_dict[\"can_modify\"] = True\n\n return my_dict if return_as_dict else my_dict[\"can_modify\"]\n\n\ndef is_admin_or_project_manager(user, project):\n \"\"\"returns True if user is either in 'projects_admin' group OR if they are a manager of the project (section head, div. manager, RDS)\"\"\"\n if user.id:\n\n # check to see if a superuser or projects_admin -- both are allow to modify projects\n if \"projects_admin\" in [g.name for g in user.groups.all()]:\n return True\n\n # check to see if they are a section head, div. manager or RDS\n if is_section_head(user, project) or is_division_manager(user, project) or is_rds(user, project):\n return True\n\n\ndef get_manageable_sections(user):\n if in_projects_admin_group(user):\n return shared_models.Section.objects.filter(projects2__isnull=False).distinct()\n return shared_models.Section.objects.filter(Q(head=user) | Q(division__head=user) | Q(division__branch__head=user))\n\n\ndef get_section_choices(all=False, full_name=True, region_filter=None, division_filter=None):\n if full_name:\n my_attr = \"full_name\"\n else:\n my_attr = _(\"name\")\n\n if region_filter:\n reg_kwargs = {\n \"division__branch__region_id\": region_filter\n }\n else:\n reg_kwargs = {\n \"division__branch__region_id__isnull\": False\n }\n\n if division_filter:\n div_kwargs = {\n \"division_id\": division_filter\n }\n else:\n div_kwargs = {\n \"division_id__isnull\": False\n }\n\n if not all:\n my_choice_list = [(s.id, getattr(s, my_attr)) for s in\n shared_models.Section.objects.all().order_by(\n \"division__branch__region\",\n \"division__branch\",\n \"division\",\n \"name\"\n ).filter(**div_kwargs).filter(**reg_kwargs) if s.projects2.count() > 0]\n else:\n my_choice_list = [(s.id, getattr(s, my_attr)) for s in\n shared_models.Section.objects.filter(\n division__branch__name__icontains=\"science\").order_by(\n \"division__branch__region\",\n \"division__branch\",\n \"division\",\n \"name\"\n ).filter(**div_kwargs).filter(**reg_kwargs)]\n\n return my_choice_list\n\n\ndef get_division_choices(all=False, region_filter=None):\n division_list = set(\n [shared_models.Section.objects.get(pk=s[0]).division_id for s in get_section_choices(all=all, region_filter=region_filter)])\n return [(d.id, str(d)) for d in\n shared_models.Division.objects.filter(id__in=division_list).order_by(\"branch__region\", \"name\")]\n\n\ndef get_region_choices(all=False):\n region_list = set(\n [shared_models.Division.objects.get(pk=d[0]).branch.region_id for d in get_division_choices(all=all)])\n return [(r.id, str(r)) for r in\n shared_models.Region.objects.filter(id__in=region_list).order_by(\"name\", )]\n\n\ndef get_omcatagory_choices():\n return [(o.id, str(o)) for o in models.OMCategory.objects.all()]\n\n\ndef get_funding_sources(all=False):\n return [(fs.id, str(fs)) for fs in models.FundingSource.objects.all()]\n\n\ndef get_user_fte_breakdown(user, fiscal_year_id):\n staff_instances = models.Staff.objects.filter(user=user, project_year__fiscal_year_id=fiscal_year_id)\n my_dict = dict()\n my_dict['name'] = f\"{user.last_name}, {user.first_name}\"\n my_dict['fiscal_year'] = str(shared_models.FiscalYear.objects.get(pk=fiscal_year_id))\n my_dict['draft'] = nz(staff_instances.filter(\n project_year__status=1\n ).aggregate(dsum=Sum(\"duration_weeks\"))[\"dsum\"], 0)\n\n my_dict['submitted_unapproved'] = nz(staff_instances.filter(\n project_year__status__in=[2, 3]\n ).aggregate(dsum=Sum(\"duration_weeks\"))[\"dsum\"], 0)\n\n my_dict['approved'] = nz(staff_instances.filter(\n project_year__status=4\n ).aggregate(dsum=Sum(\"duration_weeks\"))[\"dsum\"], 0)\n\n return my_dict\n\n\ndef financial_project_year_summary_data(project_year):\n \"\"\" this function will return a list, where each row corresponds to a funding source\"\"\"\n # for every funding source, we will want to summarize: Salary, O&M, Capital and TOTAL\n my_list = []\n\n for fs in project_year.get_funding_sources():\n my_dict = dict()\n my_dict[\"type\"] = fs.get_funding_source_type_display()\n my_dict[\"name\"] = str(fs)\n my_dict[\"salary\"] = 0\n my_dict[\"om\"] = 0\n my_dict[\"capital\"] = 0\n\n # first calc for staff\n for staff in project_year.staff_set.filter(funding_source=fs):\n # exclude any employees that should be excluded. This is a fail safe since the form should prevent data entry\n if not staff.employee_type.exclude_from_rollup:\n if staff.employee_type.cost_type == 1:\n my_dict[\"salary\"] += nz(staff.amount, 0)\n elif staff.employee_type.cost_type == 2:\n my_dict[\"om\"] += nz(staff.amount, 0)\n\n # O&M costs\n for cost in project_year.omcost_set.filter(funding_source=fs):\n my_dict[\"om\"] += nz(cost.amount, 0)\n\n # Capital costs\n for cost in project_year.capitalcost_set.filter(funding_source=fs):\n my_dict[\"capital\"] += nz(cost.amount, 0)\n\n my_dict[\"total\"] = my_dict[\"salary\"] + my_dict[\"om\"] + my_dict[\"capital\"]\n\n my_list.append(my_dict)\n\n return my_list\n\n\ndef financial_project_summary_data(project):\n my_list = []\n if project.get_funding_sources():\n for fs in project.get_funding_sources():\n my_dict = dict()\n my_dict[\"type\"] = fs.get_funding_source_type_display()\n my_dict[\"name\"] = str(fs)\n my_dict[\"salary\"] = 0\n my_dict[\"om\"] = 0\n my_dict[\"capital\"] = 0\n\n # first calc for staff\n for staff in models.Staff.objects.filter(funding_source=fs, project_year__project=project):\n # exclude any employees that should be excluded. This is a fail safe since the form should prevent data entry\n if not staff.employee_type.exclude_from_rollup:\n if staff.employee_type.cost_type == 1:\n my_dict[\"salary\"] += nz(staff.amount, 0)\n elif staff.employee_type.cost_type == 2:\n my_dict[\"om\"] += nz(staff.amount, 0)\n\n # O&M costs\n for cost in models.OMCost.objects.filter(funding_source=fs, project_year__project=project):\n my_dict[\"om\"] += nz(cost.amount, 0)\n\n # Capital costs\n for cost in models.CapitalCost.objects.filter(funding_source=fs, project_year__project=project):\n my_dict[\"capital\"] += nz(cost.amount, 0)\n\n my_dict[\"total\"] = my_dict[\"salary\"] + my_dict[\"om\"] + my_dict[\"capital\"]\n\n my_list.append(my_dict)\n\n return my_list\n\n\ndef multiple_financial_project_year_summary_data(project_years):\n my_list = []\n\n fs_list = list()\n # first get funding source list\n for py in project_years:\n fs_list.extend([fs.id for fs in py.get_funding_sources()])\n funding_sources = models.FundingSource.objects.filter(id__in=fs_list)\n\n for fs in funding_sources:\n my_dict = dict()\n my_dict[\"type\"] = fs.get_funding_source_type_display()\n my_dict[\"name\"] = str(fs)\n my_dict[\"salary\"] = 0\n my_dict[\"om\"] = 0\n my_dict[\"capital\"] = 0\n\n for py in project_years:\n # first calc for staff\n for staff in models.Staff.objects.filter(funding_source=fs, project_year=py):\n # exclude any employees that should be excluded. This is a fail safe since the form should prevent data entry\n if not staff.employee_type.exclude_from_rollup:\n if staff.employee_type.cost_type == 1:\n my_dict[\"salary\"] += nz(staff.amount, 0)\n elif staff.employee_type.cost_type == 2:\n my_dict[\"om\"] += nz(staff.amount, 0)\n\n # O&M costs\n for cost in models.OMCost.objects.filter(funding_source=fs, project_year=py):\n my_dict[\"om\"] += nz(cost.amount, 0)\n\n # Capital costs\n for cost in models.CapitalCost.objects.filter(funding_source=fs, project_year=py):\n my_dict[\"capital\"] += nz(cost.amount, 0)\n\n my_dict[\"total\"] = my_dict[\"salary\"] + my_dict[\"om\"] + my_dict[\"capital\"]\n\n my_list.append(my_dict)\n\n return my_list\n\n\ndef get_project_field_list(project):\n is_acrdp = project.is_acrdp\n is_csrf = project.is_csrf\n is_sara = project.is_sara\n general_project = not is_csrf and not is_acrdp and not is_sara\n\n my_list = [\n 'id',\n 'section',\n # 'title',\n 'overview' if general_project else None,\n # do not call the html field directly or we loose the ability to get the model's verbose name\n 'activity_type',\n 'functional_group.theme|{}'.format(_(\"theme\")),\n 'functional_group',\n 'default_funding_source',\n 'start_date',\n 'end_date',\n 'fiscal_years|{}'.format(_(\"Project years\")),\n 'funding_sources',\n 'lead_staff',\n\n # acrdp fields\n 'overview|{}'.format(gettext_lazy(\"Project overview / ACRDP objectives\")) if is_acrdp else None,\n 'organization' if is_acrdp else None,\n 'species_involved' if is_acrdp else None,\n 'team_description_html|{}'.format(_(\"description of team and required qualifications (ACRDP)\")) if is_acrdp else None,\n 'rationale_html|{}'.format(_(\"project problem / rationale (ACRDP)\")) if is_acrdp else None,\n 'experimental_protocol_html|{}'.format(_(\"experimental protocol (ACRDP)\")) if is_acrdp else None,\n\n # csrf fields\n 'overview' if is_csrf else None,\n 'csrf_theme|{}'.format(_(\"CSRF theme\")) if is_csrf else None,\n 'csrf_sub_theme|{}'.format(_(\"CSRF sub-theme\")) if is_csrf else None,\n 'csrf_priority|{}'.format(_(\"CSRF priority\")) if is_csrf else None,\n 'client_information_html|{}'.format(_(\"Additional info supplied by client\")) if is_csrf else None,\n 'second_priority' if is_csrf else None,\n 'objectives_html|{}'.format(_(\"project objectives (CSRF)\")) if is_csrf else None,\n 'innovation_html|{}'.format(_(\"innovation (CSRF)\")) if is_csrf else None,\n 'other_funding_html|{}'.format(_(\"other sources of funding (CSRF)\")) if is_csrf else None,\n\n # sara fields\n 'overview|{}'.format(_(\"Objectives and methods\")) if is_sara else None,\n 'reporting_mechanism' if is_sara else None,\n 'future_funding_needs' if is_sara else None,\n\n 'tags',\n 'references',\n 'metadata|{}'.format(_(\"metadata\")),\n ]\n while None in my_list: my_list.remove(None)\n return my_list\n\n\ndef get_project_year_field_list(project_year=None):\n my_list = [\n 'dates|dates',\n 'priorities', # do not call the html field directly or we loose the ability to get the model's verbose name\n # 'deliverables', # do not call the html field directly or we loose the ability to get the model's verbose name\n\n # SPECIALIZED EQUIPMENT COMPONENT\n #################################\n 'requires_specialized_equipment|{}'.format(_(\"requires specialized equipment?\")),\n 'technical_service_needs' if not project_year or project_year.requires_specialized_equipment else None,\n 'mobilization_needs' if not project_year or project_year.requires_specialized_equipment else None,\n\n # FIELD COMPONENT\n #################\n 'has_field_component|{}'.format(_(\"has field component?\")),\n 'vehicle_needs' if not project_year or project_year.has_field_component else None,\n 'ship_needs' if not project_year or project_year.has_field_component else None,\n 'coip_reference_id' if not project_year or project_year.has_field_component else None,\n 'instrumentation' if not project_year or project_year.has_field_component else None,\n 'owner_of_instrumentation' if not project_year or project_year.has_field_component else None,\n 'requires_field_staff' if not project_year or project_year.has_field_component else None,\n 'field_staff_needs' if not project_year or project_year.has_field_component and project_year.requires_field_staff else None,\n\n # DATA COMPONENT\n ################\n 'has_data_component',\n 'data_collected' if not project_year or project_year.has_data_component else None,\n 'data_products' if not project_year or project_year.has_data_component else None,\n 'open_data_eligible' if not project_year or project_year.has_data_component else None,\n 'data_storage_plan' if not project_year or project_year.has_data_component else None,\n 'data_management_needs' if not project_year or project_year.has_data_component else None,\n\n # LAB COMPONENT\n ###############\n 'has_lab_component',\n 'requires_abl_services' if not project_year or project_year.has_lab_component else None,\n 'requires_lab_space' if not project_year or project_year.has_lab_component else None,\n 'requires_other_lab_support' if not project_year or project_year.has_lab_component else None,\n 'other_lab_support_needs' if not project_year or project_year.has_lab_component else None,\n\n 'it_needs|{}'.format(_(\"special IT requirements\")),\n 'additional_notes',\n 'coding',\n 'submitted',\n 'formatted_status|{}'.format(_(\"status\")),\n # 'allocated_budget|{}'.format(_(\"allocated budget\")),\n # 'review_score|{}'.format(_(\"review score\")),\n 'metadata|{}'.format(_(\"metadata\")),\n ]\n\n # remove any instances of None\n while None in my_list: my_list.remove(None)\n\n return my_list\n\n\ndef get_review_field_list():\n my_list = [\n 'collaboration_score_html|{}'.format(\"external pressures score\"),\n 'strategic_score_html|{}'.format(\"strategic direction score\"),\n 'operational_score_html|{}'.format(\"operational considerations score\"),\n 'ecological_score_html|{}'.format(\"ecological impact score\"),\n 'scale_score_html|{}'.format(\"scale score\"),\n 'total_score',\n 'comments_for_staff',\n 'approval_level',\n 'approver_comment',\n 'allocated_budget',\n 'metadata',\n ]\n return my_list\n\n\ndef get_staff_field_list():\n my_list = [\n 'smart_name|{}'.format(_(\"name\")),\n 'funding_source',\n 'is_lead',\n 'employee_type',\n 'level',\n 'duration_weeks',\n # 'overtime_hours',\n # 'overtime_description',\n # 'student_program',\n 'amount',\n ]\n return my_list\n\n\ndef get_citation_field_list():\n my_list = [\n 'tname|{}'.format(_(\"title\")),\n 'authors',\n 'year',\n 'publication',\n 'pub_number',\n # 'turl|{}'.format(_(\"url\")),\n 'tabstract|{}'.format(_(\"abstract\")),\n 'series',\n 'region',\n ]\n return my_list\n\n\ndef get_om_field_list():\n my_list = [\n 'category_type|{}'.format(_(\"category type\")),\n 'om_category',\n 'description',\n 'funding_source',\n 'amount',\n ]\n return my_list\n\n\ndef get_capital_field_list():\n my_list = [\n 'category',\n 'description',\n 'funding_source',\n 'amount',\n ]\n return my_list\n\n\ndef get_activity_field_list():\n my_list = [\n 'type',\n 'name',\n 'description',\n 'target_date',\n 'responsible_party',\n 'latest_update|{}'.format(_(\"latest status\")),\n ]\n return my_list\n\n\ndef get_collaboration_field_list():\n my_list = [\n 'type',\n 'new_or_existing',\n 'organization',\n 'people',\n 'critical',\n 'agreement_title',\n # 'gc_program',\n # 'amount',\n 'notes',\n ]\n return my_list\n\n\ndef get_status_report_field_list():\n my_list = [\n 'report_number|{}'.format(\"number\"),\n 'status',\n 'major_accomplishments_html|{}'.format(_(\"major accomplishments\")),\n 'major_issues_html|{}'.format(_(\"major issues\")),\n 'target_completion_date',\n 'general_comment',\n 'supporting_resources|{}'.format(_(\"supporting resources\")),\n 'section_head_comment',\n 'section_head_reviewed',\n 'metadata',\n ]\n return my_list\n\n\ndef get_activity_update_field_list():\n my_list = [\n 'activity',\n 'status',\n 'notes_html|{}'.format(\"notes\"),\n 'metadata|{}'.format(\"meta\"),\n ]\n return my_list\n\n\ndef get_file_field_list():\n my_list = [\n 'name',\n 'ref|{}'.format(\"reference\"),\n 'external_url',\n 'file',\n 'date_created',\n\n ]\n return my_list\n\n\ndef get_review_score_rubric():\n return {\n \"collaboration\": {\n 1: {\n \"criteria\": _(\n \"no formal commitments; limited interest from stakeholders; limited opportunity for partnership or collaboration.\"),\n \"examples\": _(\n \"No expressed interest or identified as a low priority (or potential conflict) by a stakeholder advisory committee.\"),\n },\n 2: {\n \"criteria\": _(\"Informal departmental commitments; some interest from stakeholders; internal collaboration.\"),\n \"examples\": _(\n \"Verbal agreement with stakeholders or external partner. Collaboration between internal programs of science staff.\"),\n },\n 3: {\n \"criteria\": _(\n \"regulatory or legal commitment; high interest from stakeholders; strong opportunity for external partnership and collaboration.\"),\n \"examples\": _(\"Signed G&C agreement with external partner.\"),\n },\n },\n \"strategic\": {\n 1: {\n \"criteria\": _(\"limited long-term value; short-term benefit (fire-fighting)\"),\n \"examples\": _(\n \"Local, archived dataset, with limited likelihood of replication going forward. No clear link to decision-making.\"),\n },\n 2: {\n \"criteria\": _(\"some strategic value to department; medium-term benefit\"),\n \"examples\": _(\n \"Regional dataset of current high value, but potential to be replaced by emerging technology. Indirect link to decision.\"),\n },\n 3: {\n \"criteria\": _(\"high long-term strategic value to the department; high innovation value; broad applicability\"),\n \"examples\": _(\n \"High value/priority, nationally consistent dataset using emerging, more cost effective (emerging) technology. Clear link to high-priority decision-making.\"),\n },\n },\n \"operational\": {\n 1: {\n \"criteria\": _(\"One-off project; feasible now but not sustainable in the long-term.\"),\n \"examples\": _(\"New data collection. Significant admin work required.\"),\n },\n 2: {\n \"criteria\": _(\n \"Moderate level of feasibility or operational efficiency, e.g. equipment/tools readily available to be implemented within year\"),\n \"examples\": _(\"Some processing/analysis required of an existing dataset.\"),\n },\n 3: {\n \"criteria\": _(\n \"high feasibility, e.g. data availability, expertise, existing monitoring platforms, and regulatory tools available\"),\n \"examples\": _(\n \"Open publication of an existing data layer. Low administrative burden (e.g. existing agreements in place).\"),\n },\n },\n \"ecological\": {\n 1: {\n \"criteria\": _(\"limited ecological value, or lower priority species/habitats\"),\n \"examples\": _(\"Project related to a species or area with limited or unknown ecological role, or of localized interest.\"),\n },\n 2: {\n \"criteria\": _(\"Evidence of ecological value, e.g., prey linkages to key species.\"),\n \"examples\": _(\n \"Project related to a species or area with known linkages to a species of high ecological value (prey species), or importance identified through ecological modelling.\"),\n },\n 3: {\n \"criteria\": _(\"high ecological value (important species) or high ecological risk (SARA-listed species)\"),\n \"examples\": _(\n \"Project related to a nationally or regionally recognized ESS (Eelgrass) or EBSA (Minas Basin), or SAR (Blue Whale).\"),\n },\n },\n \"scale\": {\n 1: {\n \"criteria\": _(\"limited geographic or temporal scope; site-specific and lessons not readily applicable to other areas\"),\n \"examples\": _(\"Data only available for a single location or bay.\"),\n },\n 2: {\n \"criteria\": _(\"broad geographic/temporal scope; area of some significance\"),\n \"examples\": _(\"Subregional data layer, e.g., for a single NAFO Unit or MPA.\"),\n },\n 3: {\n \"criteria\": _(\"broad geographic or temporal scope; area of high significance\"),\n \"examples\": _(\"Bioregional data layers, e.g. remote sensing, RV Survey.\"),\n },\n },\n\n }\n\n\ndef get_risk_rating(impact, likelihood):\n \"\"\"This is taken from the ACRDP application form\"\"\"\n l = 1\n m = 2\n h = 3\n rating_dict = {\n # impact\n 1: {\n # likelihood -- > risk rating\n 1: l, 2: l, 3: l, 4: m, 5: m,\n },\n 2: {\n 1: l, 2: l, 3: m, 4: m, 5: m,\n },\n 3: {\n 1: l, 2: m, 3: m, 4: m, 5: h,\n },\n 4: {\n 1: m, 2: m, 3: m, 4: h, 5: h,\n },\n 5: {\n 1: m, 2: m, 3: h, 4: h, 5: h,\n },\n }\n return rating_dict[impact][likelihood]\n","sub_path":"projects2/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":26722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"572304112","text":"#!/usr/bin/env python\n# encoding: utf-8\n\nimport json\nimport os\nimport glob\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom models import News, Base\nfrom datetime import date\nimport shutil\n\n\nmedia_list = {\n 1: '蘋果',\n 2: '中時',\n 3: '中央社',\n 4: '東森',\n 5: '自由',\n 6: '新頭殼',\n 7: 'NowNews',\n 8: '聯合',\n 9: 'TVBS',\n 10: '中廣新聞網',\n 11: '公視新聞網',\n 12: '台視',\n 13: '華視',\n 14: '民視',\n # // 15 : '三立',\n 16: '風傳媒',\n}\n\n\ndef inspect_josn_format(inspect_str):\n try:\n json.loads(inspect_str)\n except ValueError:\n return False\n return True\n\n\ndef create_output_file(f, news_event):\n print('title: ' + f.name)\n f.write('--->\\n')\n f.write(news_event.get_url() + '\\n\\n')\n f.write(news_event.get_title() + '\\n')\n f.write(news_event.get_content())\n\n\ndef get_news_info(news_file, session, is_diff_file):\n title = ''\n content = ''\n is_exists_id = False\n already_get_id = False\n for line in news_file:\n if inspect_josn_format(line) and line.startswith('{'):\n already_get_id = True\n is_exists_id = False\n title = ''\n content = ''\n meta = json.loads(line)\n id = meta['id']\n create_time = date.fromtimestamp(int(meta['created_at'])).strftime(\"%Y-%m-%d\")\n try_get = session.query(News).filter_by(news_id=id).first()\n\n if try_get and is_diff_file:\n is_exists_id = True\n # if not try_get.inspect_expiration_date(create_time):\n session.query(News).filter_by(news_id=id).first().update_changed_count()\n elif (not try_get) and (not is_diff_file):\n url = meta['url']\n source_media = media_list[int(meta['source'])]\n else:\n already_get_id = False\n print('Error item!')\n else:\n if already_get_id == False:\n continue\n if is_exists_id == True:\n if content == '' and title != '':\n content = line\n already_get_id = False\n if not((\"404\" in content) or (\"404\" in title)):\n session.query(News).filter_by(news_id=id).update({'title': title, 'content': content})\n if title == '':\n title = line\n else:\n if content == '' and title != '':\n content = line\n already_get_id = False\n news_add = News(news_id=id, url=url, title=title,\n source_media=source_media,\n content=content, create_time=create_time)\n session.add(news_add)\n session.commit\n if title == '':\n title = line\n return session\n\n\ndef create_diff_map(source_dir):\n print('source_dir: ' + source_dir)\n if os.path.exists('db.sqlite'):\n os.remove('db.sqlite')\n engine = create_engine(\"sqlite:///db.sqlite\", echo=False)\n Base.metadata.create_all(engine)\n Session = sessionmaker(bind=engine)\n session = Session()\n for file_name in glob.glob(source_dir + '/*'):\n if 'diff' in file_name:\n continue\n with open(file_name, 'r') as f:\n print('normal: ' + file_name)\n session = get_news_info(f, session, False)\n\n for file_name in glob.glob(source_dir + '/*diff*'):\n print('diff: ' + file_name)\n with open(file_name, 'r') as f:\n session = get_news_info(f, session, True)\n\n all_of_news = session.query(News).all()\n output_dir = source_dir + '_output'\n if os.path.exists(output_dir):\n shutil.rmtree(output_dir)\n os.makedirs(output_dir)\n for news_event in all_of_news:\n print('title: ' + news_event.get_news_file_name())\n with open(output_dir + '/' + news_event.get_news_file_name(), 'w') as f:\n create_output_file(f, news_event)\n\n\ndef arrange(source_dir, dest_dir):\n if not os.path.exists(dest_dir):\n os.mkdir(dest_dir)\n\n create_diff_map(source_dir)\n '''\n for news_file in source_dir:\n with open(news_file, 'r') as news_f:\n '''\n# arrange('test_input', 'tmp')\narrange('extract', 'tmp')\n","sub_path":"src/newest_arrange.py","file_name":"newest_arrange.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"103777605","text":"import sys\r\n\r\ndef convertIdToPhones(m_align, phonesFile):\r\n\tphoneLabeling = {}\r\n\twith open(phonesFile, 'r') as pf:\r\n\t\tfor line in pf:\r\n\t\t\tphone, pid = line.split()\r\n\t\t\tphoneLabeling[pid] = phone\r\n\r\n\tm_align_cols = []\r\n\tedited_lines = []\r\n\twith open(m_align, 'r') as mf:\r\n\t\tfor line in mf:\r\n\t\t\tcols = line.split()\r\n\t\t\tcols[4] = phoneLabeling[cols[4]]\r\n\t\t\tedited_lines.append(' '.join(cols))\r\n\r\n\tprint('\\n'.join(edited_lines))\r\n\t\r\nif __name__ == '__main__':\r\n\tif len(sys.argv) != 3:\r\n\t\tprint(\"usage: python3 id2phone.py path/to/merged_alignments path/to/phones.txt\")\r\n\t\texit(0)\r\n\tconvertIdToPhones(sys.argv[1], sys.argv[2])\r\n","sub_path":"Submission/task7/id2phone.py","file_name":"id2phone.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"48693909","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 11 09:15:11 2020\n\n@author: iit-dharwad\n\"\"\"\n\nimport scipy.io\nimport sklearn.metrics\nfrom Confusion_Kaggle import plot_confusion_matrix\nimport numpy as np\ntemp1=scipy.io.loadmat('Acurracies/3 Class/y_true.mat')\ntemp2=scipy.io.loadmat('Acurracies/3 Class/y_pred.mat')\n \nyt=temp1[\"y_true\"]\nyp=temp2[\"y_pred\"]\nyt=np.squeeze(yt)\nyp=np.squeeze(yp)\n\ndifference=yt-yp\ndifference[difference!=0]=1;\n\nerror=np.sum(difference,axis=1)/600\naccuracy=(1-error)*100\n#%% ACCURACY PLOTS\nimport matplotlib.pyplot as plt\nx = range(50, 2000,20)\n\nplt.figure(num=None, figsize=(18, 12), dpi=100, facecolor='w', edgecolor='k')\n# plt.imshow(cm, interpolation='nearest', cmap=cmap)\nplt.plot(x,accuracy)\nplt.title('Dirichlet 3 Class')\n# plt.rcParams.update({'font.size': 20})\nplt.xlabel('Vocabulary Size')\nplt.ylabel('Accuracy %')\n\n#%% CONFUSION MATRIX\nbest_accuracy=np.argmax(accuracy)\nbest_vocab_size=x[best_accuracy]\nmytitle='Confusion Matrix for Vocabulary Length: '+np.str(best_vocab_size)\nconf_matx=sklearn.metrics.confusion_matrix(yp[best_accuracy],yt[best_accuracy],normalize=None)\nplot_confusion_matrix(conf_matx,['Motorcycles','Hockey','Pol: Mid East'],title=mytitle, normalize=False)\n# plot_confusion_matrix(conf_matx,range(20),title=mytitle, normalize=False)\n\n","sub_path":"Assignment 1/News Data Part 2/Plots_and_Figures.py","file_name":"Plots_and_Figures.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"622416402","text":"from rit_lib import *\r\n\r\n\"\"\"\r\nRaymond Healy\r\n\r\nUtilities: This task involves writing tools for reading and processing the data, as well\r\nas defining data structures to store the data. The other tasks import and use these\r\ntools.\r\n\"\"\"\r\n\r\n\r\n# -----------------------------------------------------------------------------------------#\r\ndef read_data(filename=\"worldbank_life_expectancy\"):\r\n return ReadData(filename)\r\n\r\n\r\ndef filter_region(data, region):\r\n return FilterForRegion(data, region.strip())\r\n\r\n\r\ndef filter_income(data, income):\r\n return FilterForIncomeGroup(data, income.strip())\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -----------------------------------------------------------------------------------------------#\r\ndef kNoRegionString():\r\n return \"No Region\"\r\n\r\n\r\ndef kNoIncomeString():\r\n return \"No Income Group\"\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -----------------------------------------------------------------------------------------#\r\nDatum = struct_type(\"Datum\", (str, \"name\"), (str, \"code\"), (list, \"data\"), (str, \"region\"),\r\n (str, \"incomeGroup\"), (str, \"notes\"))\r\n\r\n\r\ndef MkDatum(name='', code='', data=[], region='', incomeGroup='', notes=''):\r\n return Datum(name, code, data, region, incomeGroup, notes)\r\n\r\n\r\ndef DataForYear(datum, year):\r\n if 1960 <= year <= 2015:\r\n return datum.data[year - 1960]\r\n else:\r\n raise IndexError(\r\n \"Attempted to access data for an invalid year. <> only accepts years b/n 1960 and 2015, inc.\")\r\n\r\n\r\nCountryValue = struct_type(\"CountryValue\", (str, \"country\"), (float, \"value\"))\r\n\r\n\r\ndef CountryValueSort(countryValues, reverse=False):\r\n if reverse:\r\n countryValues.sort(key=lambda x: x.value, reverse=False)\r\n else:\r\n countryValues.sort(key=lambda x: x.value, reverse=True)\r\n return countryValues\r\n\r\n\r\nRange = struct_type(\"Range\", (str, \"country\"), (int, \"year1\"), (int, \"year2\"),\r\n (float, \"value1\"), (float, \"value2\"))\r\n\r\n\r\ndef RangeSort(ranges):\r\n ranges.sort(key=lambda x: x.value2 - x.value1, reverse=False)\r\n return ranges\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# ------------------------------------------------------------------------------------------#\r\ndef ReadData(filename=\"worldbank_life_expectancy\"):\r\n \"\"\"\r\n Init. Conditions: A file to an expectancy data <> file formatted as nindicated in the documentation\r\n Final Conditions: NA\r\n\r\n Parameters: filepath - A valid string filepath to the expectancy data plaintext file\r\n metaFilepath - A valid string filepath to the expectancy metadata plaintext file\r\n\r\n Returns: A tuple of four dictionaries.\r\n idx 0: Values are <>s, indexed by <>\r\n idx 1: Values are <>s, indexed by <>\r\n idx 2: Values are lists of <>s, indexed by <>\r\n idx 3: Values are lists of <>s, indexed by <>\r\n\r\n Description: Takes the specified life-expectancy data and metadata files and returns a <> with two\r\n dictionaries of <>s indexed by <> and <>, and 2 dictionaries of <>s\r\n of <>s indexed by <> and <>\r\n \"\"\"\r\n\r\n filepath = \"data/\" + filename.strip() + \"_data.txt\"\r\n metaFilepath = \"data/\" + filename.strip() + \"_metadata.txt\"\r\n\r\n # ---------------------------------------------------------------#\r\n countries = {} # To hold the <> entries indexed by their <>\r\n codes = {} # To hold the <> entries indexed by their three-character <>\r\n regions = {} # To hold <>s of <> entries sorted by <>\r\n incomeGroups = {} # To hold <>s of <> entries sorted by <>\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # ------------------------------------------------------------------------#\r\n f = open(filepath) # Open the file indicated by <> as <>\r\n lines = f.readlines()[1:] # Take all lines from <>, discarding the first, header line\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # ------------------------------>s>------------------------------#\r\n for line in lines: # On each line from the data <>\r\n data = line.split(',')[:-1] # Split <> on each comma, and discard the empty, final string\r\n country = MkDatum(data[0].strip(),\r\n data[1].strip(), []) # Make a new <> instance with the specified <> and <>\r\n data = data[2:] # Remove the name and code from <> to avoid \"double counting\"\" them\r\n\r\n for dP in data: # Go through each remaining sub-strings in <> (refered to as data points or <>\r\n dP = dP.strip() # Strip down the next number's string representation\r\n if dP == '': # If <> is an empty string (i.e. no expectancy data)\r\n country.data += [None] # Add a representative <> in the data slot for that year\r\n else: # Otherwise (if there is expectancy data for the year)\r\n country.data += [float(dP)]\r\n # Add the data point as a <> to the expectancy data in the slot in order from 1960 to 2015\r\n\r\n # Save the partial country <> indexed by <> to easily insert metadata\r\n codes[country.code] = country\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # --------------------------------------------------------------#\r\n f.close() # Close the expectancy data file\r\n f = open(metaFilepath) # Open the expectancy metadata file as <>\r\n lines = f.readlines()[1:] # Read all metadata sets and discard the header line\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # ------------------------->s>-------------------------#\r\n for line in lines: # For each data set <> in the metadata file\r\n line = line.strip().split(',') # Strip down the data set and separate out the components\r\n\r\n code = line[0] # Salvage the country code to find the pre-existing entry, if there is one\r\n\r\n region = line[1] # Take the country region from the metadata file\r\n if region.strip() == '': # If no region data is provided\r\n region = kNoRegionString() # Lable the region as such\r\n\r\n incomeGroup = line[2] # Take the income level indicated by the file\r\n if incomeGroup.strip() == '': # If no income level data is provided\r\n incomeGroup = kNoIncomeString() # Lable the group as such\r\n\r\n notes = '' # Create an empty string for the remainder\r\n if len(line) > 3: # If there are eny entries left\r\n notes = str(line[3]) # Add the next entry\r\n if len(line) > 3: # If there are any remaining notes\r\n line = line[4:] # Strip out the previously added note sub-string\r\n for l in line: # For each remaining sub-string of <>\r\n notes += ',' + l # Replace the stripped out comma from <> and add the next sub-string\r\n\r\n if code in codes: # If this country code was specified in the data file\r\n codes[code].region = region # Label the region that the country belongs to\r\n codes[code].incomeGroup = incomeGroup # Lable the country's income bracket\r\n codes[code].notes = notes.strip(\r\n ' \\t\\r\\n\"').strip() # Annotate each country <>, removing whitespace and double quotes\r\n else: # Otherwise (if this is a new country code)\r\n codes[code] = MkDatum('', code, [], region, incomeGroup,\r\n notes) # Make a new <> to store meta-data and store that by <>\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n # ------------------>, <>, and <>>-------------------#\r\n for datum in codes.values(): # For each country (or, <>)\r\n region = datum.region # Take the <> from the country data\r\n incomeGroup = datum.incomeGroup # Take the <> from the country data\r\n\r\n countries[datum.name] = datum # Insert <>, labled with its <>\r\n\r\n if region in regions: # If the <> has an associated <> in <>\r\n regions[region] += [datum] # Append <> to that <>\r\n else: # Otherwise (if the <> does not have an associated <> in <>)\r\n regions[region] = [datum] # Create a new <> for the <> in <>\r\n\r\n if incomeGroup in incomeGroups: # If the <> has an associated <> in <>\r\n incomeGroups[incomeGroup] += [datum] # Append <> to that <>\r\n else: # Otherwise (if the <> does not have an associated <> in <>)\r\n incomeGroups[incomeGroup] = [datum] # Create a new <> for the <> in <>\r\n # --------------------------------------------------------------------------------------------#\r\n\r\n return countries, codes, regions, incomeGroups # Return all of the created dictionaries\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# ------------------------------------------------------------------------------------------------#\r\ndef NumEntries(countryList):\r\n return len(countryList)\r\n\r\n\r\ndef NumCountries(dictIn):\r\n if isinstance(dictIn, tuple):\r\n dictIn = dictIn[0]\r\n\r\n countryList = DictValuesToList(dictIn)\r\n num = NumEntries(countryList)\r\n for country in countryList:\r\n if country.region == kNoRegionString():\r\n num -= 1\r\n\r\n return num\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -------------------------------------------------------------------------------------------------#\r\ndef FilterForRegion(dictIn, region=\"All\"):\r\n if isinstance(dictIn, tuple):\r\n dictIn = dictIn[0]\r\n\r\n countryList = DictValuesToList(dictIn)\r\n regionCodes = {}\r\n regionCountries = {}\r\n\r\n lst = []\r\n\r\n if region == \"All\" or region ==\"all\":\r\n for country in countryList:\r\n if not country.region == kNoRegionString():\r\n lst += [country]\r\n else:\r\n for country in countryList: # For each <> in <>\r\n if country.region == region: # If <> matches the desired <>\r\n lst += [country]\r\n\r\n for country in lst:\r\n regionCodes[country.code] = country\r\n regionCountries[country.name] = country\r\n\r\n return regionCountries, regionCodes\r\n\r\n\r\ndef FilterForIncomeGroup(dictIn, incomeGroup=\"All\"):\r\n if isinstance(dictIn, tuple):\r\n dictIn = dictIn[0]\r\n\r\n countryList = DictValuesToList(dictIn)\r\n incomeGroupCodes = {}\r\n incomeGroupCountries = {}\r\n\r\n lst = []\r\n\r\n if incomeGroup == \"All\" or incomeGroup == 'all':\r\n for country in countryList:\r\n if not country.incomeGroup == kNoIncomeString():\r\n lst += [country]\r\n else:\r\n for country in countryList: # For each <> in <>\r\n if country.incomeGroup == incomeGroup: # If <> matches the desired <>\r\n lst += [country]\r\n\r\n for country in lst:\r\n incomeGroupCodes[country.code] = country\r\n incomeGroupCountries[country.name] = country\r\n\r\n return incomeGroupCodes, incomeGroupCountries\r\n\r\n\r\ndef FilterToCountries(dictIn):\r\n data = DictValuesToList(dictIn)\r\n countries = {}\r\n codes = {}\r\n\r\n for country in data:\r\n if not country.region == kNoRegionString():\r\n countries[country.name] = country\r\n codes[country.code] = country\r\n\r\n return countries, codes\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -------------------------------------------------------------------------------------------#\r\ndef DictValuesToList(dictionary):\r\n if isinstance(dictionary, tuple):\r\n dictionary = dictionary[0]\r\n\r\n return list(dictionary.values())\r\n\r\n\r\ndef DictKeysToList(dictionary):\r\n if isinstance(dictionary, tuple):\r\n dictionary = dictionary[0]\r\n\r\n return list(dictionary.keys())\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\n# -----------------------------------------------------------------------------------------#\r\ndef PrintValidData(datum):\r\n for year in range(1960, 2016):\r\n data = DataForYear(datum, year)\r\n if data is not None:\r\n print(\"Year:\", year, \"Life expectancy:\", data)\r\n\r\n\r\ndef PrintTop(sortedLst, num=10):\r\n num = min(len(sortedLst), num)\r\n\r\n for i in range(num):\r\n country = sortedLst[i]\r\n print(i + 1, \":\", country.country, country.value)\r\n\r\n\r\ndef PrintBottom(sortedLst, num=10):\r\n num = min(len(sortedLst), num)\r\n\r\n for i in range(num):\r\n i = len(sortedLst) - 1 - i\r\n country = sortedLst[i]\r\n print(i + 1, ':', country.country, country.value)\r\n\r\n\r\n# ----------------------------------------------------------------------------------------------------------#\r\n\r\ndef main():\r\n (countries, codes, regions, incomeGroups) = ReadData()\r\n countryLst = DictValuesToList(countries)\r\n regionLst = DictKeysToList(regions)\r\n incomeGroupLst = DictKeysToList(incomeGroups)\r\n\r\n print(\"Total Number of Entities: \", NumEntries(countryLst))\r\n print(\"Total Number of Countries/Territories: \", NumCountries(countries))\r\n\r\n print(\"\\n\\nRegions and Their Country Count:\")\r\n for region in regionLst:\r\n (filteredCountries, filteredCodes) = FilterForRegion(countries, region)\r\n print(region, ':', NumCountries(filteredCountries))\r\n\r\n print(\"\\n\\nIncome Categories and Their Country Count:\")\r\n for incomeGroup in incomeGroupLst:\r\n (filteredCountries, filteredCodes) = FilterForIncomeGroup(countries, incomeGroup)\r\n print(incomeGroup, ': ', NumCountries(filteredCountries))\r\n\r\n region = input(\"\\n\\nEnter a Region Name: \").strip()\r\n print(\"Countries in the\", region, \"region:\")\r\n (filteredCountries, filteredCodes) = FilterForRegion(countries, region)\r\n for country in filteredCountries.values():\r\n print(country.name, '(', country.code, ')')\r\n\r\n incomeGroup = input(\"\\n\\nEnter an Income Category: \").strip()\r\n print(\"Countries in the '\", incomeGroup, \"' Income Category:\")\r\n (filteredCountries, filteredCodes) = FilterForIncomeGroup(countries, incomeGroup)\r\n for country in filteredCountries.values():\r\n print(country.name, '(', country.code, ')')\r\n\r\n sel = input(\"\\n\\nEnter the Name of a Country or Country Code (Enter to Quit):\").strip()\r\n while sel != '':\r\n if sel in countries:\r\n print(\"Data for\", sel)\r\n sel = countries[sel]\r\n PrintValidData(sel)\r\n\r\n elif sel.upper() in codes:\r\n print(\"Data for\", sel)\r\n sel = codes[sel]\r\n PrintValidData(sel)\r\n else:\r\n print(sel, \"is not a valid country name or code\")\r\n\r\n sel = input(\"\\n\\nEnter the Name of a Country or Country Code (Enter to Quit):\").strip()\r\n\r\n\r\ndef foo():\r\n (countries, codes, regions, incomeGroups) = ReadData()\r\n data = codes[\"RWA\"].data\r\n\r\n minIdx = 0\r\n maxIdx = 0\r\n minimum = data[0]\r\n maximum = data[0]\r\n for i in range(len(data)):\r\n if data[i] < minimum:\r\n minimum = data[i]\r\n minIdx = i\r\n if data[i] > maximum:\r\n maximum = data[i]\r\n maxIdx = i\r\n\r\n print(minIdx + 1960)\r\n print(minimum)\r\n print('\\n')\r\n print(maxIdx + 1960)\r\n print(maximum)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n # foo()\r\n","sub_path":"CS 1/Project/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"121487175","text":"import math\r\n\r\nimport numpy as np\r\nfrom scipy import signal\r\nimport cv2\r\n\r\n\r\ndef gausssmooth(img, sigma):\r\n # Create Gaussian kernel and filter image with it.\r\n x = np.array(list(range(math.floor(-3.0 * sigma + 0.5), math.floor(3.0 * sigma + 0.5) + 1)))\r\n G = np.exp(-x**2 / (2 * sigma**2))\r\n G = G / np.sum(G)\r\n return cv2.sepFilter2D(img, -1, G, G)\r\n\r\n\r\ndef generate_responses_1():\r\n # Generate responses map.\r\n responses = np.zeros((100, 100), dtype=np.float32)\r\n responses[70, 50] = 1\r\n responses[50, 70] = 0.5\r\n return gausssmooth(responses, 10)\r\n\r\n\r\ndef generate_responses_2():\r\n # Generate responses map.\r\n responses = np.zeros((1000, 1000), dtype=np.float32)\r\n val = 1/800\r\n incr = 1/800\r\n gauss_sig = signal.gaussian(1000, std=400)\r\n for idx in np.arange(800):\r\n responses[idx, :] = val*gauss_sig\r\n val += incr\r\n return gausssmooth(responses, 40)\r\n\r\n\r\ndef get_patch(img, center, sz):\r\n \r\n # Crop coordinates.\r\n x0 = round(int(center[0] - sz[0] / 2))\r\n y0 = round(int(center[1] - sz[1] / 2))\r\n x1 = int(round(x0 + sz[0]))\r\n y1 = int(round(y0 + sz[1]))\r\n \r\n # Set padding - how far across the image border is the edge of patch?\r\n x0_pad = max(0, -x0)\r\n x1_pad = max(x1 - img.shape[1] + 1, 0)\r\n y0_pad = max(0, -y0)\r\n y1_pad = max(y1 - img.shape[0] + 1, 0)\r\n\r\n # Crop target.\r\n if len(img.shape) > 2:\r\n # BGR image.\r\n img_crop = img[y0 + y0_pad:y1 - y1_pad, x0 + x0_pad:x1 - x1_pad, :]\r\n else:\r\n # Grayscale image.\r\n img_crop = img[y0 + y0_pad:y1 - y1_pad, x0 + x0_pad:x1 - x1_pad]\r\n \r\n # Cropped and padded image.\r\n im_crop_padded = cv2.copyMakeBorder(img_crop, y0_pad, y1_pad, x0_pad, x1_pad, cv2.BORDER_REPLICATE)\r\n\r\n # Crop mask tells which pixels are within the image (1) and which are outside (0).\r\n m_ = np.ones((img.shape[0], img.shape[1]), dtype=np.float32)\r\n crop_mask = m_[y0 + y0_pad:y1 - y1_pad, x0 + x0_pad:x1 - x1_pad]\r\n crop_mask = cv2.copyMakeBorder(crop_mask, y0_pad, y1_pad, x0_pad, x1_pad, cv2.BORDER_CONSTANT, value=0)\r\n\r\n # Return cropped and padded image and crop mask.\r\n return im_crop_padded, crop_mask\r\n\r\n\r\ndef create_epanechnik_kernel(width, height, sigma):\r\n\r\n # Get floored halves of width and height (should be odd).\r\n w2 = int(math.floor(width / 2))\r\n h2 = int(math.floor(height / 2))\r\n \r\n # Create meshgrid and normalize values to interval [0, 1].\r\n [X, Y] = np.meshgrid(np.arange(-w2, w2 + 1), np.arange(-h2, h2 + 1))\r\n X = X / np.max(X)\r\n Y = Y / np.max(Y)\r\n \r\n # Create kernel.\r\n kernel = (1 - ((X / sigma)**2 + (Y / sigma)**2))\r\n\r\n # Normalize kernel to interval [0, 1] and\r\n # clip negative values.\r\n kernel = kernel / np.max(kernel)\r\n kernel[kernel < 0] = 0\r\n\r\n # Return kernel.\r\n return kernel\r\n\r\n\r\ndef extract_histogram(patch, nbins, weights=None):\r\n\r\n # Note: input patch must be a BGR image (3 channel numpy array).\r\n # Convert each pixel intensity to the one of nbins bins.\r\n channel_bin_idxs = np.floor((patch.astype(np.float32) / float(255)) * float(nbins - 1))\r\n \r\n # Calculate bin index of a 3D histogram.\r\n bin_idxs = (channel_bin_idxs[:, :, 0] * nbins**2 + channel_bin_idxs[:, :, 1] * nbins + channel_bin_idxs[:, :, 2]).astype(np.int32)\r\n\r\n # Count bin indices to create histogram (use per-pixel weights if given).\r\n if weights is not None:\r\n histogram_ = np.bincount(bin_idxs.flatten(), weights=weights.flatten())\r\n else:\r\n histogram_ = np.bincount(bin_idxs.flatten())\r\n \r\n # zero-pad histogram (needed since bincount function does not generate histogram with nbins**3 elements).\r\n histogram = np.zeros((nbins**3, 1), dtype=histogram_.dtype).flatten()\r\n histogram[:histogram_.size] = histogram_\r\n\r\n # Return computed histogram.\r\n return histogram\r\n\r\n\r\ndef backproject_histogram(patch, histogram, nbins):\r\n \r\n # Note: input patch must be a BGR image (3 channel numpy array).\r\n # Convert each pixel intensity to the one of nbins bins.\r\n channel_bin_idxs = np.floor((patch.astype(np.float32) / float(255)) * float(nbins - 1))\r\n \r\n # Calculate bin index of a 3D histogram.\r\n bin_idxs = (channel_bin_idxs[:, :, 0] * nbins**2 + channel_bin_idxs[:, :, 1] * nbins + channel_bin_idxs[:, :, 2]).astype(np.int32)\r\n\r\n # Use histogram as a lookup table for pixel backprojection.\r\n backprojection = np.reshape(histogram[bin_idxs.flatten()], (patch.shape[0], patch.shape[1]))\r\n\r\n # Return computed backprojection.\r\n return backprojection\r\n\r\n\r\n# Base class for tracker.\r\nclass Tracker():\r\n def __init__(self, params):\r\n self.parameters = params\r\n\r\n def initialize(self, image, region):\r\n raise NotImplementedError\r\n\r\n def track(self, image):\r\n raise NotImplementedError\r\n\r\n","sub_path":"assignments/2/src/ex2_utils.py","file_name":"ex2_utils.py","file_ext":"py","file_size_in_byte":4852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"558691576","text":"# calculate the cross section and errors\n\nimport math\n# \n#Full Fits\n# Mu 1.2142e+00 +/- 2.40e-01\n# Ele 1.3489e+00 +/- 2.80e-01\n# Comb 1.2870e+00 +/- 2.21e-01\n\n#Stastical only fits\n# Mu 1.2557e+00 +/- 6.09e-02\n# Ele 1.4135e+00 +/- 7.16e-02\n# Comb 1.3231e+00 +/- 4.65e-02\n#\n\n\nleps=[\"mu\",\"ele\",\"comb\"]\n\n# signal strength\nsss=[1.2142,1.3489,1.2870]\n# signal strength errors\nsserrs=[0.240,0.280,0.221]\n\n# signal strength errors from stat only fit\nstaterrs=[0.0609,0.0716,0.0465]\n\n# theory (5F) xc\nxct=0.51\n# theory uncertainties\nerrxct=0.01\nerracc=0.1\n\nprint(\"\\n\")\nprint(\"Uncertainties calculated relative to xc_theory x signal strength\")\nfor lep,ss,sserr,staterr in zip(leps,sss,sserrs,staterrs):\n print(\" %4s xc: %.4f +- %.4f (stat) +- %.4f (syst) +- %.4f (theo) +- %.4f (lumi) pb \"%( \n lep, # name\n ss*xct, # xc obs\n ss*staterr*xct, # stat error\n math.sqrt( ((ss*sserr*xct)*(ss*sserr*xct)) - ((ss*staterr*xct)*(ss*staterr*xct)) ), # syst err\n ss*xct*math.sqrt( errxct*errxct + erracc*erracc ),\n ss*xct*0.026\n ))\nprint(\"\\n\")\n","sub_path":"Wbb8TeV/scripts/crosssection/xc_calc.py","file_name":"xc_calc.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"418528965","text":"#\n# copyright (c) 2009 Ralf Habacker \n#\n\n\"\"\" \\package BuildSystemBase\"\"\"\nimport EmergeDebug\nfrom EmergeBase import *\nimport compiler\n\nclass BuildSystemBase(EmergeBase):\n \"\"\"provides a generic interface for build systems and implements all stuff for all build systems\"\"\"\n debug = True\n\n def __init__(self, typeName=\"\"):\n \"\"\"constructor\"\"\"\n EmergeBase.__init__(self)\n self.supportsNinja = False\n self.supportsCCACHE = emergeSettings.getboolean(\"Compile\",\"UseCCache\", False ) and compiler.isMinGW()\n self.supportsClang = emergeSettings.getboolean(\"Compile\",\"UseClang\", False )\n self.buildSystemType = typeName\n self.envPath = \"\"\n if self.compiler() == \"mingw\":\n self.envPath = \"mingw/bin\"\n if self.compiler() == \"mingw4\":\n self.envPath = \"mingw4/bin\"\n\n\n def _getmakeProgram(self):\n if self.supportsNinja and emergeSettings.getboolean(\"Compile\",\"UseNinja\", False):\n return \"ninja\"\n makeProgram = emergeSettings.get(\"Compile\", \"MakeProgram\", \"\" )\n if makeProgram != \"\" and self.subinfo.options.make.supportsMultijob:\n EmergeDebug.debug(\"set custom make program: %s\" % makeProgram, 1)\n return makeProgram\n elif not self.subinfo.options.make.supportsMultijob:\n if \"MAKE\" in os.environ:\n del os.environ[\"MAKE\"]\n if compiler.isMSVC() or compiler.isIntel() :\n return \"nmake /NOLOGO\"\n elif compiler.isMinGW():\n return \"mingw32-make\"\n else:\n EmergeDebug.die(\"unknown %s compiler\" % self.compiler())\n makeProgramm = property(_getmakeProgram)\n\n def compile(self):\n \"\"\"convencience method - runs configure() and make()\"\"\"\n configure = getattr(self, 'configure')\n make = getattr(self, 'make')\n return configure() and make()\n\n def configureSourceDir(self):\n \"\"\"returns source dir used for configure step\"\"\"\n # pylint: disable=E1101\n # this class never defines self.source, that happens only\n # in MultiSource.\n if hasattr(self,'source'):\n sourcedir = self.source.sourceDir()\n else:\n sourcedir = self.sourceDir()\n\n if self.subinfo.hasConfigurePath():\n sourcedir = os.path.join(sourcedir, self.subinfo.configurePath())\n return sourcedir\n\n def configureOptions(self, defines=\"\"):\n \"\"\"return options for configure command line\"\"\"\n if self.subinfo.options.configure.defines != None:\n defines += \" %s\" % self.subinfo.options.configure.defines\n \n if self.supportsCCACHE:\n defines += \" %s\" % self.ccacheOptions()\n if self.supportsClang:\n defines += \" %s\" % self.clangOptions()\n return defines\n\n def makeOptions(self, defines=\"\", maybeVerbose=True):\n \"\"\"return options for make command line\"\"\"\n if self.subinfo.options.make.ignoreErrors:\n defines += \" -i\"\n if self.subinfo.options.make.makeOptions:\n defines += \" %s\" % self.subinfo.options.make.makeOptions\n if maybeVerbose and EmergeDebug.verbose() > 1:\n if self.supportsNinja and emergeSettings.getboolean(\"Compile\",\"UseNinja\", False ):\n defines += \" -v \"\n else:\n defines += \" VERBOSE=1 V=1\"\n return defines\n\n def dumpEmergeDependencies( self ):\n \"\"\"dump emerge package dependencies\"\"\"\n output = dependencies.dumpDependencies( self.package )\n outDir = self.buildDir()\n outFile = os.path.join( outDir, self.package + '-emerge.dot' )\n if not os.path.exists( os.path.dirname( outFile ) ):\n os.makedirs( os.path.dirname( outFile ) )\n with open( outFile, \"w\" ) as f:\n f.write( output )\n\n graphviz = GraphViz( self )\n\n if not graphviz.runDot( outFile, outFile + '.pdf', 'pdf' ):\n return False\n\n return graphviz.openOutput()\n\n def dumpDependencies(self):\n \"\"\"dump package dependencies \"\"\"\n return self.dumpEmergeDependencies()\n\n def configure(self):\n return True\n \n def make(self):\n return True\n \n def install(self):\n\n # create post (un)install scripts\n for pkgtype in ['bin', 'lib', 'doc', 'src', 'dbg']:\n script = os.path.join( self.packageDir(), \"post-install-%s.cmd\" ) % pkgtype\n scriptName = \"post-install-%s-%s.cmd\" % ( self.package, pkgtype )\n # are there any cases there installDir should be honored ?\n destscript = os.path.join( self.imageDir(), \"manifest\", scriptName )\n if not os.path.exists( os.path.join( self.imageDir(), \"manifest\" ) ):\n utils.createDir( os.path.join( self.imageDir(), \"manifest\" ) )\n if os.path.exists( script ):\n utils.copyFile( script, destscript )\n script = os.path.join( self.packageDir(), \"post-uninstall-%s.cmd\" ) % pkgtype\n scriptName = \"post-uninstall-%s-%s.cmd\" % ( self.package, pkgtype )\n # are there any cases there installDir should be honored ?\n destscript = os.path.join( self.imageDir(), \"manifest\", scriptName )\n if not os.path.exists( os.path.join( self.imageDir(), \"manifest\" ) ):\n utils.createDir( os.path.join( self.imageDir(), \"manifest\" ) )\n if os.path.exists( script ):\n utils.copyFile( script, destscript )\n return True\n\n def unittest( self ):\n \"\"\"running unittests\"\"\"\n return True\n\n def ccacheOptions(self):\n return \"\"\n\n def clangOptions(self):\n return \"\"\n","sub_path":"bin/BuildSystem/BuildSystemBase.py","file_name":"BuildSystemBase.py","file_ext":"py","file_size_in_byte":5716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"541391650","text":"import asyncio\nfrom asyncio.locks import Condition\nimport time\nfrom aiosqlite.core import LOG\n\nimport discord\nimport sqlite3\n\nfrom datetime import datetime\nfrom discord.ext import commands, tasks\nfrom sqlalchemy import select\nfrom sqlalchemy import update\nfrom sqlalchemy import delete\nfrom sqlalchemy import and_\nfrom sqlalchemy.sql.expression import insert\nfrom sqlalchemy.sql.selectable import Select\nfrom sqlalchemy import inspect\nfrom sqlalchemy import event\n\nfrom random import random\n\nfrom bot import LOGGER\nfrom bot import TESTING\n\nimport sys, os\nsys.path.append(os.path.abspath(os.path.join('..', 'routines')))\n\nfrom routines.tables import Queue, Data, Temp\nfrom routines import sessionmaker\nfrom routines import engine\n\n# TODO: Use an actual settings file for these and channel/message ids.\nRS_GROUPS = {\n 'prod': {\n 'rs_ping': {\n \"RS5\": \"<@&785786197531295755>\",\n \"RS6\": \"<@&785786579826245642>\",\n \"RS7\": \"<@&785786709517795328>\",\n \"RS8\": \"<@&785786792350711808>\",\n \"RS9\": \"<@&785786898920374273>\",\n \"RS10\": \"<@&785786957782319104>\",\n \"RS11\": \"<@&800957912180457494>\"\n },\n 'rs_ping_1more': {\n \"RS5\": \"<@&800958080208732231>\",\n \"RS6\": \"<@&805597027458744321>\",\n \"RS7\": \"<@&805597168849256489>\",\n \"RS8\": \"<@&805597260455870515>\",\n \"RS9\": \"<@&805596918956556308>\",\n \"RS10\": \"<@&805597317856100353>\",\n \"RS11\": \"<@&805598218666770432>\"\n }\n },\n 'testing': {\n 'rs_ping': {\n \"RS5\": \"<@&806018027383422998>\",\n \"RS6\": \"<@&806018102797402122>\",\n \"RS7\": \"<@&806018133835513876>\",\n \"RS8\": \"<@&806018135106519040>\",\n \"RS9\": \"<@&806018147487711313>\",\n \"RS10\": \"<@&806018150256082984>\",\n \"RS11\": \"<@&806261078295183400>\"\n },\n 'rs_ping_1more': {\n \"RS5\": \"<@&806018333517938688>\",\n \"RS6\": \"<@&806018337804910592>\",\n \"RS7\": \"<@&806018340203397140>\",\n \"RS8\": \"<@&806018343696990208>\",\n \"RS9\": \"<@&806018346269016084>\",\n \"RS10\": \"<@&806018349183139890>\",\n \"RS11\": \"<@&806261118158372936>\"\n }\n },\n}\n\nif TESTING:\n LOGGER.debug('Loading testing settings.')\n RS_GROUPS = RS_GROUPS.get('testing')\nelse:\n LOGGER.info('Loading PRODUCTION settings.')\n RS_GROUPS = RS_GROUPS.get('prod')\n\n\n\n\n\n\n\nclass RSQueue(commands.Cog, name='Queue'):\n\n def __init__(self, bot):\n self.bot = bot\n self.index = 0\n self.success = 0\n self.error = 0\n self.check_people.start()\n self.current_mods = [\"croid\", \"influence\", \"nosanc\", \"notele\", \"rse\", \"suppress\", \"unity\", \"veng\", \"barrage\", \"laser\", \"dart\", \"battery\", \"solo\", \"solo2\"]\n self.rs_channel = {\n \"rs5-club\": 5,\n \"rs6-club\": 6,\n \"rs7-club\": 7,\n \"rs8-club\": 8,\n \"rs9-club\": 9,\n \"rs10-club\": 10,\n \"rs11-club\": 11,\n \"bot-spam\": -1\n }\n self.rs_ping = RS_GROUPS['rs_ping']\n self.rs_ping_1more = RS_GROUPS['rs_ping_1more']\n self.emojis = {\n \"1️⃣\": 1,\n \"2️⃣\": 2,\n \"3️⃣\": 3,\n \"4️⃣\": 4\n }\n self.total_info = []\n\n\n\n\n\n\n async def amount(self, level):\n async with sessionmaker.begin() as session:\n people = (await session.execute(select(Queue).where(Queue.level == int(level)))).scalars()\n count = 0\n for person in people:\n count += int(person.amount)\n return count\n \n \n \n\n async def queue_time(self, server_id, user_id, amount, level):\n async with sessionmaker.begin() as session:\n person = (await session.get(Queue, (server_id, user_id, amount, level)))\n data = int((time.time() - int(person.time)) / 60)\n return data\n\n async def check(self):\n async with sessionmaker() as session:\n results = (await session.execute(select(Queue))).scalars()\n for queue in results:\n minutes = int((time.time() - queue.time) / 60)\n if minutes == queue.length:\n # Ping the user\n user = await self.bot.fetch_user(queue.user_id)\n channel = await self.bot.fetch_channel(queue.channel_id)\n message = await channel.send(\n f\"{user.mention}, still in for a RS{queue.level}? React ✅ to stay in the queue, and ❌ to leave the queue\")\n await message.add_reaction('✅')\n await message.add_reaction('❌')\n # Add their user_id and message_id to database\n add_temp = Temp(server_id=queue.server_id, channel_id=queue.channel_id, user_id=queue.user_id, message_id=message.id, amount=queue.amount, level=queue.level)\n session.add(add_temp)\n await session.commit()\n\n #ctx = await self.bot.get_context(message.id)\n #await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n elif minutes >= queue.length + 5:\n User_leave = (await session.get(Queue, (queue.server_id, queue.user_id, queue.amount, queue.level)))\n await session.delete(User_leave)\n await session.commit()\n user = await self.bot.fetch_user(queue.user_id)\n channel = await self.bot.fetch_channel(queue.channel_id)\n await channel.send(f\"{user.display_name} has left RS{queue.level} ({await self.amount(queue.level)}/4)\")\n conditions = and_(Temp.user_id == queue.user_id, Temp.level == queue.level)\n id = (await session.execute(select(Temp).where(conditions))).scalars()\n for i in id:\n if i.channel_id == queue.channel_id:\n message = await channel.fetch_message(i.message_id)\n await message.delete()\n conditions = and_(Temp.server_id == queue.server_id, Temp.user_id == queue.user_id, Temp.level == queue.level)\n await session.execute(delete(Temp).where(conditions))\n await session.commit()\n await session.commit()\n \n\n\n @tasks.loop(minutes=1.0)\n async def check_people(self):\n try:\n await self.check()\n except Exception as e:\n self.error, self.index = self.error+1, self.index+1\n check_embed = discord.Embed(\n title=\"Failure\",\n color=discord.Color.red()\n )\n check_embed.add_field(name=\"Timestamp\", value=f\"{int(time.time())}\")\n check_embed.add_field(name=\"Exception\", value=f\"{e}\")\n check_embed.add_field(name=\"Error/Total\", value=f\"{self.error}/{self.index} -> {(self.error)/(self.index)}\")\n else:\n self.success, self.index = self.success+1, self.index+1\n check_embed = discord.Embed(\n title=\"Success\",\n color=discord.Color.green()\n )\n check_embed.add_field(name=\"Timestamp\", value=f\"{int(time.time())}\")\n check_embed.add_field(name=\"Success/Total\", value=f\"{self.success}/{self.index} -> {(self.success)/(self.index)}\")\n finally:\n channel = await self.bot.fetch_channel(849504307707117578)\n await channel.send(embed=check_embed)\n \n\n\n\n \n @commands.command()\n @commands.has_role(\"mod\")\n async def run_check(self, ctx):\n await self.check_people.__call__()\n message = await ctx.send(\"Ran background task check_people()\")\n await asyncio.sleep(5)\n await ctx.message.delete()\n await message.delete()\n\n @commands.command()\n @commands.has_role(\"mod\")\n async def clear_cache(self, ctx):\n engine.clear_compiled_cache()\n message = await ctx.send(\"Engine's cache has been cleared\")\n await asyncio.sleep(10)\n await ctx.message.delete()\n await message.delete()\n\n\n @commands.command(aliases=[\"r\", \"^\", \"staying\"])\n async def refresh(self, ctx):\n async with sessionmaker() as session:\n conditions = and_(Queue.user_id == ctx.author.id, Queue.level == self.rs_channel[str(ctx.message.channel)])\n times = (await session.execute(select(Queue).where(conditions))).scalars()\n times.first().time = int(time.time())\n rs_level = f'RS{self.rs_channel[str(ctx.message.channel)]}'\n num_players = f'({await self.amount(self.rs_channel[str(ctx.message.channel)])}/4)'\n await ctx.send(f\"{ctx.author.mention}, you are requeued for a {rs_level}! {num_players}\")\n await session.commit()\n\n @commands.command(pass_context=True)\n async def corp(self, ctx, *corp):\n member = await ctx.guild.fetch_member(ctx.author.id)\n LOGGER.debug(member.display_name)\n if member.display_name.startswith(\"[\"):\n name = member.display_name[member.display_name.find(\"]\") + 2:]\n else:\n name = member.display_name\n nick = f\"[{' '.join(corp)}] \" + name\n await member.edit(nick=nick)\n await ctx.send(f\"{ctx.author.display_name}, Your corp has been set to {corp}\")\n\n\n @commands.command()\n async def rsc(self, ctx):\n role = discord.utils.get(ctx.author.guild.roles, name='🌟')\n if role in ctx.author.roles:\n await ctx.author.remove_roles(role)\n msg = await ctx.send(\"The RS Channels have been hidden\")\n await asyncio.sleep(15)\n await ctx.message.delete()\n await msg.delete()\n else:\n await ctx.author.add_roles(role)\n msg = await ctx.send(\"The RS Channels have been restored\")\n await asyncio.sleep(15)\n await ctx.message.delete()\n await msg.delete()\n\n @commands.command()\n @commands.has_role(\"mod\")\n async def clear(self, ctx, limit: int):\n await ctx.channel.purge(limit=limit)\n\n @commands.command()\n @commands.has_role(\"mod\")\n async def clear_database(self, ctx, level=None):\n if level is not None:\n async with sessionmaker() as session:\n #await ctx.send(f\"The RS{level} queue has been cleared\")\n users = (await session.execute(select(Queue).where(Queue.level == int(level)))).scalars()\n for user in users:\n await session.delete(user)\n await session.commit()\n message = await ctx.send(f\"RS{level} Queue cleared\")\n await asyncio.sleep(5)\n await ctx.message.delete()\n await message.delete()\n\n else:\n async with sessionmaker() as session:\n for level in range(5, 12):\n users = (await session.execute(select(Queue).where(Queue.level == int(level)))).scalars()\n for user in users:\n await session.delete(user)\n await session.commit()\n message = await ctx.send(\"All queues cleared\")\n await asyncio.sleep(5)\n await ctx.message.delete()\n await message.delete()\n \n\n @commands.command(name='1', help=\"Type +1/-1, which will add you/remove you to/from a RS Queue\")\n async def _one(self, ctx, length=60):\n await self.everything(ctx, ctx.message.content[0], ctx.message.content[1], length, ctx.channel.id)\n\n @commands.command(name='2', help=\"Type +2/-2, which will add you/remove you and another person to/from a RS Queue\")\n async def _two(self, ctx, length=60):\n await self.everything(ctx, ctx.message.content[0], ctx.message.content[1], length, ctx.channel.id)\n\n @commands.command(name='3', help=\"Type +3/-4, which will add you/remove you and 2 other people to/from a RS Queue\")\n async def _three(self, ctx, length=60):\n await self.everything(ctx, ctx.message.content[0], ctx.message.content[1], length, ctx.channel.id)\n\n async def everything(self, ctx, prefix, count, length, channel_id):\n LOGGER.debug(f\"Running the everything command\")\n LOGGER.debug(f\"Values: Prefix: {prefix}, Count: {count}, length: {length}, channel_id: {channel_id}\")\n count = int(count)\n if prefix == \"+\":\n right_channel = False\n channel = \"\"\n for club_channel in self.rs_channel:\n if club_channel == str(ctx.message.channel):\n right_channel = True\n channel = club_channel\n if right_channel:\n has_right_role = False\n for role in ctx.author.roles:\n if str(role)[2:].isnumeric(): # Checks main role (rs#)\n if int(str(role)[2:]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n elif str(role)[2:-12].isnumeric(): # Checks 3/4 role (rs# 3/4 1more)\n if int(str(role)[2:-12]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n elif str(role)[2:-2].isnumeric(): # Checks silent role (rs# s)\n if int(str(role)[2:-2]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n if has_right_role:\n if length >= 5 and length <= 11:\n length = 60\n # check if adding amount would overfill the queue\n queue_status = await self.amount(self.rs_channel[channel])\n if int(queue_status) + count > 4:\n await ctx.send(f\"{ctx.author.mention}, adding {count} people to the queue would overfill the queue\")\n else:\n # check if they are in any other queues\n async with sessionmaker() as session:\n data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars().all()\n await session.commit()\n if len(data) == 0: # They weren't found in the database, add them\n LOGGER.debug(\"Adding them to the queue\")\n User_entering_queue = Queue(server_id=ctx.guild.id, user_id=ctx.author.id, amount=count, level=self.rs_channel[channel], time=int(time.time()), length=length, channel_id=channel_id)\n session.add(User_entering_queue)\n await session.commit()\n # Check if queue is 4/4\n if await self.amount(self.rs_channel[channel]) == 4:\n LOGGER.debug(\"Queue is 4/4, remove everyone\")\n # Print out the queue\n people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n string_people = \"\"\n print_people = []\n LOGGER.debug(people)\n for person in people:\n string_people += (await self.bot.fetch_user(person.user_id)).mention + \" \"\n print_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n await ctx.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Ready! {string_people}\")\n await ctx.send(\"Meet where?\")\n # Remove everyone from the queue\n async with sessionmaker() as session:\n queue_people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n for person in queue_people:\n await session.delete(person)\n await session.commit()\n try:\n rs_log_channel = await self.bot.fetch_channel(805228742678806599)\n except:\n rs_log_channel = await self.bot.fetch_channel(806370539148541952)\n formated_date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n await rs_log_channel.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \\nUsers: {', '.join(print_people)}\")\n else:\n LOGGER.debug(\"Queue ain't 4/4, print out el queue\")\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n count = await self.amount(self.rs_channel[channel])\n if count == 3:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n LOGGER.debug(\"They were found on multiple queues, find all queues\")\n # see what queue they are on, and either update their current position or new position\n async with sessionmaker.begin() as session:\n current_data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars()\n current_queues = []\n for data in current_data:\n current_queues.append((data.level, data.amount))\n current_queues.append((self.rs_channel[channel], count))\n LOGGER.debug(f'Current Queues: {current_queues}')\n D = {}\n for (x, y) in current_queues:\n if x not in D.keys():\n D[x] = y\n else:\n D[x] += y\n final_queues = [(x, D[x]) for x in D.keys()]\n LOGGER.debug(final_queues)\n LOGGER.debug(\"Above is what should be the final queue status\")\n # append the queue they wanna join to\n for queue in final_queues:\n if queue[0] == self.rs_channel[channel]:\n # Check if adding amount to the queue would make it 4/4\n if await self.amount(self.rs_channel[channel]) + count > 4:\n pass\n else:\n # check to see if we need to update their position or add another position\n async with sessionmaker() as session:\n conditions = and_(Queue.user_id == ctx.author.id, Queue.level == self.rs_channel[channel])\n data = (await session.execute(select(Queue).where(conditions))).scalars().all()\n await session.commit()\n if len(data) == 0:\n # They weren't found elsewhere, add them to the new queue\n LOGGER.debug(\"I have reached this line\")\n user = Queue(server_id=ctx.guild.id, user_id=ctx.author.id, amount=queue[1], level=self.rs_channel[channel], time=int(time.time()), length=length, channel_id=channel_id)\n session.add(user)\n await session.commit()\n else:\n # They were found on another queue, so update their position\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n if(data.level == queue[0]):\n pre_amount = data.amount\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[channel]))\n user.amount = int(queue[1])\n user.time = int(time.time())\n user.length = length\n break\n await session.commit()\n if await self.amount(queue[0]) == 4:\n async with sessionmaker() as session:\n people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n string_people = \"\"\n print_people = []\n for person in people:\n string_people += (await self.bot.fetch_user(person.user_id)).mention + \" \"\n print_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n await ctx.send(f\"RS{self.rs_channel[channel]} Ready! {string_people}\")\n await ctx.send(\"Meet where?\")\n # Remove everyone from the queue\n queue_people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n for person in queue_people:\n await session.delete(person)\n await session.commit()\n # Print out the rs log\n try:\n rs_log_channel = await self.bot.fetch_channel(805228742678806599)\n except:\n rs_log_channel = await self.bot.fetch_channel(806370539148541952)\n formated_date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n await rs_log_channel.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \\nUsers: {', '.join(print_people)}\")\n else:\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n count = await self.amount(self.rs_channel[channel])\n if count == 3:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention}, you aren't RS{self.rs_channel[channel]}\")\n else:\n msg = await ctx.send(\"Command not run in an RS Channel\")\n await asyncio.sleep(10)\n await ctx.message.delete()\n await msg.delete()\n elif prefix == \"-\":\n LOGGER.debug(\"- command run, attempting to remove them from queue\")\n async with sessionmaker.begin() as session:\n conditions = and_(Queue.user_id == ctx.author.id, Queue.level == self.rs_channel[str(ctx.message.channel)])\n result = (await session.execute(select(Queue).where(conditions))).scalars()\n LOGGER.debug(result)\n if result is None: # Didn't find them in any queues\n await ctx.send(f\"{ctx.author.mention}, You aren't in an RS Queues at the moment\")\n else: # Remove count of them from the queue\n # Get the level and amount data\n # Check if removing count would remove more than they are in\n current_data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars()\n current_queues = []\n for data in current_data:\n current_queues.append((data.level, data.amount))\n adding_queue = (self.rs_channel[str(ctx.message.channel)], -count)\n current_queues.append(adding_queue)\n D = {}\n for (x, y) in current_queues:\n if x not in D.keys():\n D[x] = y\n else:\n D[x] += y\n final_queues = [(x, D[x]) for x in D.keys()]\n LOGGER.debug(final_queues)\n LOGGER.debug(\"above is the final queues of that person\")\n for queue in final_queues:\n # Remove only count from the queue they sent the message in\n if queue[0] == self.rs_channel[str(ctx.message.channel)]:\n LOGGER.debug(queue)\n if queue[1] <= 0:\n async with sessionmaker() as session:\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n LOGGER.debug(f\"data.level: {data.level}, {queue[0]}\")\n if(data.level == queue[0]):\n pre_amount = data.amount\n LOGGER.debug(f\"pre_amount {pre_amount}\")\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[str(ctx.message.channel)]))\n LOGGER.debug(f\"User: {user}\")\n await session.delete(user)\n await session.commit()\n break\n else:\n async with sessionmaker() as session:\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n if(data.level == queue[0]):\n pre_amount = data.amount\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[str(ctx.message.channel)]))\n user.amount = int(queue[1])\n await session.commit()\n break\n LOGGER.debug(\"updated the queue they were in\")\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)], False)\n await ctx.send(f\"{ctx.author.display_name} has left the RS{self.rs_channel[str(ctx.message.channel)]} Queue ({await self.amount(self.rs_channel[str(ctx.message.channel)])}/4)\")\n\n @commands.command(aliases=[\"o\"], help=\"type !o or !out, which leaves your current RS Queue\")\n async def out(self, ctx):\n # First check if they are in any RS Queues\n async with sessionmaker() as session:\n results = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars().all()\n if len(results) != 0: # They were found in an RS Queue\n # remove only one (and delete if they only have one in queue)\n async with sessionmaker() as session:\n current_data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars()\n current_queues = []\n for data in current_data:\n current_queues.append((data.level, data.amount))\n adding_queue = (self.rs_channel[str(ctx.message.channel)], -1)\n current_queues.append(adding_queue)\n D = {}\n for (x, y) in current_queues:\n if x not in D.keys():\n D[x] = y\n else:\n D[x] += y\n final_queues = [(x, D[x]) for x in D.keys()]\n for updated_queues in final_queues:\n # Remove only count from the queue they sent the message in\n if updated_queues[0] == self.rs_channel[str(ctx.message.channel)]:\n LOGGER.debug(updated_queues)\n if updated_queues[1] <= 0:\n async with sessionmaker.begin() as session:\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n LOGGER.debug(f\"data.level: {data.level}, {updated_queues[0]}\")\n if(data.level == updated_queues[0]):\n pre_amount = data.amount\n LOGGER.debug(f\"pre_amount {pre_amount}\")\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[str(ctx.message.channel)]))\n LOGGER.debug(f\"User: {user}\")\n await session.delete(user)\n LOGGER.debug(\"Removed them from the queue\")\n break\n else:\n async with sessionmaker.begin() as session:\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n if(data.level == updated_queues[0]):\n pre_amount = data.amount\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[str(ctx.message.channel)]))\n user.amount = int(updated_queues[1])\n LOGGER.debug(\"updated the queue they were in\")\n break\n\n # Print out the new queue\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)], False)\n await ctx.send(f\"{ctx.author.display_name} has left the RS{self.rs_channel[str(ctx.message.channel)]} Queue ({await self.amount(self.rs_channel[str(ctx.message.channel)])}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention}, You aren't in an RS Queues\")\n\n @commands.command(aliases=[\"in\", \"i\"], help=\"Use this command (!i or !in) to join a RS Queue\")\n async def rs(self, ctx, length=60):\n right_channel = False\n channel = \"\"\n add_level = self.rs_channel[str(ctx.message.channel)]\n for club_channel in self.rs_channel:\n if club_channel == str(ctx.message.channel):\n right_channel = True\n channel = club_channel\n if right_channel:\n has_right_role = False\n for role in ctx.author.roles:\n if str(role)[2:].isnumeric(): # Check main rs role\n if int(str(role)[2:]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n elif str(role)[2:-12].isnumeric(): # Check 3/4 role\n if int(str(role)[2:-12]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n elif str(role)[2:-2].isnumeric(): # Checks silent role (rs# s)\n if int(str(role)[2:-2]) >= int(self.rs_channel[channel]):\n has_right_role = True\n break\n # if(str(role) == f'RS{self.rs_channel[channel]}' or int(str(role)[2:]) > self.rs_channel[channel]):\n # has_right_role = True\n if has_right_role:\n # This is where the fun begins\n if length >= 5 and length <= 11:\n length = 60\n async with sessionmaker() as session:\n data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars().all()\n await session.commit()\n if len(data) == 0: # They weren't found in the database, add them\n LOGGER.debug(\"Adding them to the queue\")\n async with sessionmaker() as session:\n User_entering_queue = Queue(server_id=ctx.guild.id, user_id=ctx.author.id, amount=1, level=self.rs_channel[channel], time=int(time.time()), length=length, channel_id=ctx.channel.id)\n session.add(User_entering_queue)\n await session.commit()\n # Print out the queue\n # Check if queue is 4/4\n if await self.amount(self.rs_channel[channel]) == 4:\n LOGGER.debug(\"Queue is 4/4, remove everyone\")\n # Print out the queue\n people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n string_people = \"\"\n print_people = []\n LOGGER.debug(people)\n for person in people:\n string_people += (await self.bot.fetch_user(person.user_id)).mention + \" \"\n print_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n await ctx.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Ready! {string_people}\")\n await ctx.send(\"Meet where?\")\n # Remove everyone from the queue\n queue_people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n for person in queue_people:\n await session.delete(person)\n await session.commit()\n rs_log_channel = await self.bot.fetch_channel(805228742678806599)\n formated_date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n await rs_log_channel.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \\nUsers: {', '.join(print_people)}\")\n else:\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n count = await self.amount(self.rs_channel[channel])\n if count == 3:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n await session.commit()\n else:\n async with sessionmaker() as session:\n # see what queue they are on, and either update their current position or new position\n current_data = (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars()\n # This check is to see if they would be added again to the current queue\n valid = True\n for data in current_data:\n if data.level == self.rs_channel[str(ctx.message.channel)]:\n valid = False\n if valid:\n current_queues = []\n for data in current_data:\n current_queues.append((data.level, data.amount))\n adding_queue = (self.rs_channel[str(ctx.message.channel)], 1)\n current_queues.append(adding_queue)\n D = {}\n for (x, y) in current_queues:\n if x not in D.keys():\n D[x] = y\n else:\n D[x] += y\n final_queues = [(x, D[x]) for x in D.keys()]\n for queue in final_queues:\n if queue[0] == self.rs_channel[channel]:\n # Check if adding amount to the queue would make it 4/4\n if await self.amount(self.rs_channel[channel]) + 1 > 4:\n pass\n else:\n # check to see if we need to update their position or add another position\n async with sessionmaker() as session:\n conditions = and_(Queue.user_id == ctx.author.id, Queue.level == self.rs_channel[channel])\n data = (await session.execute(select(Queue).where(conditions))).scalars().all()\n await session.commit()\n if len(data) == 0:\n # They weren't found elsewhere, add them to the new queue\n async with sessionmaker() as session:\n user = Queue(server_id=ctx.guild.id, user_id=ctx.author.id, amount=queue[1], level=self.rs_channel[channel], time=int(time.time()), length=length, channel_id=ctx.channel.id)\n session.add(user)\n await session.commit()\n else:\n # They were found on another queue, so update their position\n for data in (await session.execute(select(Queue).where(Queue.user_id == ctx.author.id))).scalars():\n if(data.level == queue[0]):\n pre_amount = data.amount\n user = await session.get(Queue, (ctx.guild.id, ctx.author.id, pre_amount, self.rs_channel[channel]))\n user.amount = int(queue[1])\n user.time = int(time.time())\n user.length = length\n await session.commit()\n break\n if await self.amount(queue[0]) == 4:\n async with sessionmaker() as session:\n people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n string_people = \"\"\n print_people = []\n for person in people:\n string_people += (await self.bot.fetch_user(person.user_id)).mention + \" \"\n print_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n await ctx.send(f\"RS{self.rs_channel[channel]} Ready! {string_people}\")\n await ctx.send(\"Meet where?\")\n # Remove everyone from the queue\n queue_people = (await session.execute(select(Queue).where(Queue.level == self.rs_channel[channel]))).scalars()\n for person in queue_people:\n await session.delete(person)\n await session.commit()\n # Print out the rs log\n try:\n rs_log_channel = await self.bot.fetch_channel(805228742678806599)\n except:\n rs_log_channel = await self.bot.fetch_channel(806370539148541952)\n formated_date = datetime.now().strftime(\"%m/%d/%Y, %H:%M:%S\")\n await rs_log_channel.send(f\"RS{self.rs_channel[str(ctx.message.channel)]} Started at {formated_date} PST \\nUsers: {', '.join(print_people)}\")\n else:\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n count = await self.amount(self.rs_channel[channel])\n if count == 3:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping_1more[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention} joined {self.rs_ping[f'RS{self.rs_channel[channel]}']} ({count}/4)\")\n else:\n await ctx.send(f\"{ctx.author.mention}, you are already queued for a RS{self.rs_channel[channel]}, if you want to add another player to the queue, type +1\")\n else:\n await ctx.send(f\"{ctx.author.mention}, you aren't RS{self.rs_channel[channel]}\")\n\n @commands.command(aliases=[\"q\"], help=\"(!queue or !q) will show the current RS Queues\")\n async def queue(self, ctx):\n await self.print_queue(ctx, self.rs_channel[str(ctx.message.channel)])\n\n async def print_queue(self, ctx, level, display=True):\n extras = {\n 'croid': discord.utils.get(self.bot.emojis, name='croid'),\n 'influence': discord.utils.get(self.bot.emojis, name='influence'),\n 'nosanc': discord.utils.get(self.bot.emojis, name='nosanc'),\n 'notele': discord.utils.get(self.bot.emojis, name='notele'),\n 'rse': discord.utils.get(self.bot.emojis, name='rse'),\n 'suppress': discord.utils.get(self.bot.emojis, name='suppress'),\n 'unity': discord.utils.get(self.bot.emojis, name='unity'),\n 'veng': discord.utils.get(self.bot.emojis, name='veng'),\n 'barrage': discord.utils.get(self.bot.emojis, name='barrage'),\n 'laser': discord.utils.get(self.bot.emojis, name='laser'),\n 'dart': discord.utils.get(self.bot.emojis, name='dart'),\n 'battery': discord.utils.get(self.bot.emojis, name='battery'),\n 'solo': discord.utils.get(self.bot.emojis, name='solo'),\n 'solo2': discord.utils.get(self.bot.emojis, name='solo2')\n }\n queue_embed = discord.Embed(color=discord.Color.red())\n async with sessionmaker.begin() as session:\n people = (await session.execute(select(Queue).where(Queue.level == level))).scalars()\n count = 0\n counting = []\n for person in people:\n counting.append(person.amount)\n count += int(person.amount)\n if count > 0:\n list_people = []\n user_ids = []\n rsmods = []\n for person in (await session.execute(select(Queue).where(Queue.level == level))).scalars():\n list_people.append((await ctx.guild.fetch_member(person.user_id)).display_name)\n user_ids.append((await ctx.guild.fetch_member(person.user_id)).id)\n users_mods = (await session.get(Data, person.user_id))\n i = 0\n temp = \"\"\n LOGGER.debug(f\"Here is users_mods: {users_mods}\")\n if users_mods is not None:\n for mod in self.current_mods:\n #await ctx.send(f\"Mod: {mod} {getattr(users_mods, mod)}\")\n if(getattr(users_mods, mod) == True):\n temp += \" \" + (str(extras[self.current_mods[i]]))\n i += 1\n rsmods.append(temp)\n str_people = \"\"\n emoji_count = 0\n i = 0\n LOGGER.debug(f\"List People {list_people}\")\n for person in (await session.execute(select(Queue).where(Queue.level == level))).scalars():\n for j in range(counting[i]):\n str_people += str(list(self.emojis)[emoji_count])\n emoji_count += 1\n # Server_id, user_id, amount, level\n str_people += \" \" + list_people[i] + rsmods[i] + \" 🕒 \" + str(await self.queue_time(ctx.guild.id, user_ids[i], counting[i], self.rs_channel[str(ctx.message.channel)])) + \"m\"\n str_people += \"\\n\"\n i += 1\n queue_embed.add_field(\n name=f\"The Current RS{self.rs_channel[str(ctx.message.channel)]} Queue ({await self.amount(self.rs_channel[str(ctx.message.channel)])}/4)\",\n value=str_people, inline=False)\n await ctx.send(embed=queue_embed)\n else:\n if display:\n await ctx.send(f\"No RS{self.rs_channel[str(ctx.message.channel)]} Queues found, you can start one by typing +1\")\n\ndef setup(bot):\n bot.add_cog(RSQueue(bot))\n LOGGER.debug('RS Queueing loaded')\n","sub_path":"routines/cogs/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":47757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"92574044","text":"from ..torch_core import *\nfrom .transform import *\nfrom ..data import *\n\n__all__ = ['CoordTargetDataset', 'DatasetTfm', 'FilesDataset', 'SegmentationDataset', 'bb2hw', 'denormalize', 'draw_outline', 'draw_rect', \n 'get_image_files', 'image2np', 'image_data_from_folder', 'normalize', 'normalize_batch', 'normalize_funcs', \n 'open_image', 'open_mask', 'pil2tensor', 'show_image', 'show_image_batch', 'show_images', 'show_xy_images',\n 'transform_datasets', 'cifar_norm', 'cifar_denorm', 'imagenet_norm', 'imagenet_denorm']\n\nTfmList = Collection[Transform]\n\nimage_extensions = set(k for k,v in mimetypes.types_map.items() if v.startswith('image/'))\n\ndef get_image_files(c:Path, check_ext:bool=True)->FilePathList:\n \"Return list of files in `c` that are images. `check_ext` will filter to `image_extensions`.\"\n return [o for o in list(c.iterdir())\n if not o.name.startswith('.') and not o.is_dir()\n and (not check_ext or (o.suffix in image_extensions))]\n\ndef pil2tensor(image:NPImage)->TensorImage:\n \"Convert PIL style `image` array to torch style image tensor `get_image_files`\"\n arr = ByteTensor(torch.ByteStorage.from_buffer(image.tobytes()))\n arr = arr.view(image.size[1], image.size[0], -1)\n return arr.permute(2,0,1)\n\ndef open_image(fn:PathOrStr):\n \"Return `Image` object created from image in file `fn`\"\n x = PIL.Image.open(fn).convert('RGB')\n return Image(pil2tensor(x).float().div_(255))\n\ndef open_mask(fn:PathOrStr) -> ImageMask: return ImageMask(pil2tensor(PIL.Image.open(fn)).long())\n\ndef image2np(image:Tensor)->np.ndarray:\n \"Convert from torch style `image` to numpy/matplotlib style\"\n res = image.cpu().permute(1,2,0).numpy()\n return res[...,0] if res.shape[2]==1 else res\n\ndef bb2hw(a:Collection[int]) -> np.ndarray:\n \"Converts bounding box points from (width,height,center) to (height,width,top,left)\"\n return np.array([a[1],a[0],a[3]-a[1],a[2]-a[0]])\n\ndef draw_outline(o:Patch, lw:int):\n \"Outlines bounding box onto image `Patch`\"\n o.set_path_effects([patheffects.Stroke(\n linewidth=lw, foreground='black'), patheffects.Normal()])\n\ndef draw_rect(ax:plt.Axes, b:Collection[int], color:str='white'):\n \"Draws bounding box on `ax`\"\n patch = ax.add_patch(patches.Rectangle(b[:2], *b[-2:], fill=False, edgecolor=color, lw=2))\n draw_outline(patch, 4)\n\ndef _show_image(img:Image, ax:plt.Axes=None, figsize:tuple=(3,3), hide_axis:bool=True, cmap:str='binary',\n alpha:float=None) -> plt.Axes:\n if ax is None: fig,ax = plt.subplots(figsize=figsize)\n ax.imshow(image2np(img), cmap=cmap, alpha=alpha)\n if hide_axis: ax.axis('off')\n return ax\n\ndef show_image(x:Image, y:Image=None, ax:plt.Axes=None, figsize:tuple=(3,3), alpha:float=0.5,\n title:Optional[str]=None, hide_axis:bool=True, cmap:str='viridis'):\n \"Plot tensor `x` using matplotlib axis `ax`. `figsize`,`axis`,`title`,`cmap` and `alpha` pass to `ax.imshow`\"\n ax1 = _show_image(x, ax=ax, hide_axis=hide_axis, cmap=cmap)\n if y is not None: _show_image(y, ax=ax1, alpha=alpha, hide_axis=hide_axis, cmap=cmap)\n if hide_axis: ax1.axis('off')\n if title: ax1.set_title(title)\n\ndef _show(self:Image, ax:plt.Axes=None, y:Image=None, **kwargs):\n if y is not None:\n is_bb = isinstance(y, ImageBBox)\n y=y.data\n if y is None or not is_bb: return show_image(self.data, ax=ax, y=y, **kwargs)\n ax = _show_image(self.data, ax=ax)\n if len(y.size()) == 1: draw_rect(ax, bb2hw(y))\n else:\n for i in range(y.size(0)): draw_rect(ax, bb2hw(y[i]))\n\nImage.show = _show\n\ndef show_images(x:Collection[Image],y:int,rows:int, classes:Collection[str], figsize:Tuple[int,int]=(9,9))->None:\n \"Plot images (`x[i]`) from `x` titled according to classes[y[i]]\"\n fig, axs = plt.subplots(rows,rows,figsize=figsize)\n for i, ax in enumerate(axs.flatten()):\n show_image(x[i], ax)\n ax.set_title(classes[y[i]])\n plt.tight_layout()\n\ndef show_image_batch(dl:DataLoader, classes:Collection[str], rows:int=None, figsize:Tuple[int,int]=(12,15),\n denorm:Callable=None) -> None:\n \"Show a few images from a batch\"\n x,y = next(iter(dl))\n if rows is None: rows = int(math.sqrt(len(x)))\n x = x[:rows*rows].cpu()\n if denorm: x = denorm(x)\n show_images(x,y[:rows*rows].cpu(),rows, classes)\n\nclass FilesDataset(LabelDataset):\n \"Dataset for folders of images in style {folder}/{class}/{images}\"\n def __init__(self, fns:FilePathList, labels:ImgLabels, classes:Optional[Classes]=None):\n self.classes = ifnone(classes, list(set(labels)))\n self.class2idx = {v:k for k,v in enumerate(self.classes)}\n self.x = np.array(fns)\n self.y = np.array([self.class2idx[o] for o in labels], dtype=np.int64)\n\n def __getitem__(self,i): return open_image(self.x[i]),self.y[i]\n\n @staticmethod\n def _folder_files(folder:Path, label:ImgLabel, check_ext=True)->Tuple[FilePathList,ImgLabels]:\n \"From `folder` return image files and labels. The labels are all `label`. `check_ext` means only image files\"\n fnames = get_image_files(folder, check_ext=check_ext)\n return fnames,[label]*len(fnames)\n\n @classmethod\n def from_single_folder(cls, folder:PathOrStr, classes:Classes, check_ext=True):\n \"Typically used for test set. label all images in `folder` with `classes[0]`\"\n fns,labels = cls._folder_files(folder, classes[0], check_ext=check_ext)\n return cls(fns, labels, classes=classes)\n\n @classmethod\n def from_folder(cls, folder:Path, classes:Optional[Classes]=None,\n valid_pct:float=0., check_ext:bool=True) -> Union['FilesDataset', List['FilesDataset']]:\n \"Dataset of `classes` labeled images in `folder`. Optional `valid_pct` split validation set.\"\n if classes is None: classes = [cls.name for cls in find_classes(folder)]\n\n fns,labels = [],[]\n for cl in classes:\n f,l = cls._folder_files(folder/cl, cl, check_ext=check_ext)\n fns+=f; labels+=l\n\n if valid_pct==0.: return cls(fns, labels, classes=classes)\n return [cls(*a, classes=classes) for a in random_split(valid_pct, fns, labels)]\n\nclass SegmentationDataset(DatasetBase):\n \"A dataset for segmentation task\"\n def __init__(self, x:Collection[PathOrStr], y:Collection[PathOrStr]):\n assert len(x)==len(y)\n self.x,self.y = np.array(x),np.array(y)\n\n def __getitem__(self, i:int) -> Tuple[Image,ImageMask]:\n return open_image(self.x[i]), open_mask(self.y[i])\n\ndef show_xy_images(x:Tensor,y:Tensor,rows:int,figsize:tuple=(9,9)):\n \"Shows a selection of images and targets from a given batch.\"\n fig, axs = plt.subplots(rows,rows,figsize=figsize)\n for i, ax in enumerate(axs.flatten()): show_image(x[i], y=y[i], ax=ax)\n plt.tight_layout()\n\n@dataclass\nclass CoordTargetDataset(Dataset):\n \"A dataset with annotated images\"\n x_fns:Collection[Path]\n bbs:Collection[Collection[int]]\n def __post_init__(self): assert len(self.x_fns)==len(self.bbs)\n def __repr__(self) -> str: return f'{type(self).__name__} of len {len(self.x_fns)}'\n def __len__(self) -> int: return len(self.x_fns)\n def __getitem__(self, i:int) -> Tuple[Image,ImageBBox]:\n x = open_image(self.x_fns[i])\n return x, ImageBBox.create(self.bbs[i], *x.size)\n\nclass DatasetTfm(Dataset):\n \"`Dataset` that applies a list of transforms to every item drawn\"\n def __init__(self, ds:Dataset, tfms:TfmList=None, tfm_y:bool=False, **kwargs:Any):\n \"this dataset will apply `tfms` to `ds`\"\n self.ds,self.tfms,self.kwargs,self.tfm_y = ds,tfms,kwargs,tfm_y\n self.y_kwargs = {**self.kwargs, 'do_resolve':False}\n\n def __len__(self)->int: return len(self.ds)\n\n def __getitem__(self,idx:int)->Tuple[ItemBase,Any]:\n \"returns tfms(x),y\"\n x,y = self.ds[idx]\n x = apply_tfms(self.tfms, x, **self.kwargs)\n if self.tfm_y: y = apply_tfms(self.tfms, y, **self.y_kwargs)\n return x, y\n\n def __getattr__(self,k):\n \"passthrough access to wrapped dataset attributes\"\n return getattr(self.ds, k)\n\ndef transform_datasets(train_ds:Dataset, valid_ds:Dataset, test_ds:Optional[Dataset]=None,\n tfms:Optional[Tuple[TfmList,TfmList]]=None, **kwargs:Any):\n \"Create train, valid and maybe test DatasetTfm` using `tfms` = (train_tfms,valid_tfms)\"\n res = [DatasetTfm(train_ds, tfms[0], **kwargs),\n DatasetTfm(valid_ds, tfms[1], **kwargs)]\n if test_ds is not None: res.append(DatasetTfm(test_ds, tfms[1], **kwargs))\n return res\n\ndef normalize(x:TensorImage, mean:float,std:float)->TensorImage: return (x-mean[...,None,None]) / std[...,None,None]\ndef denormalize(x:TensorImage, mean:float,std:float)->TensorImage: return x*std[...,None,None] + mean[...,None,None]\n\ndef normalize_batch(b:Tuple[Tensor,Tensor], mean:float, std:float, do_y:bool=False)->Tuple[Tensor,Tensor]:\n \"`b` = `x`,`y` - normalize `x` array of imgs and `do_y` optionally `y`\"\n x,y = b\n x = normalize(x,mean,std)\n if do_y: y = normalize(y,mean,std)\n return x,y\n\ndef normalize_funcs(mean:float, std, do_y=False, device=None)->[Callable,Callable]:\n \"Create normalize/denormalize func using `mean` and `std`, can specify `do_y` and `device`\"\n if device is None: device=default_device\n return (partial(normalize_batch, mean=mean.to(device),std=std.to(device)),\n partial(denormalize, mean=mean, std=std))\n\ncifar_stats = (tensor([0.491, 0.482, 0.447]), tensor([0.247, 0.243, 0.261]))\ncifar_norm,cifar_denorm = normalize_funcs(*cifar_stats)\nimagenet_stats = tensor([0.485, 0.456, 0.406]), tensor([0.229, 0.224, 0.225])\nimagenet_norm,imagenet_denorm = normalize_funcs(*imagenet_stats)\n\ndef _create_with_tfm(train_ds, valid_ds, test_ds=None,\n path='.', bs=64, ds_tfms=None, num_workers=default_cpus,\n tfms=None, device=None, size=None, **kwargs)->'DataBunch':\n \"`DataBunch` factory. `bs` batch size, `ds_tfms` for `Dataset`, `tfms` for `DataLoader`\"\n datasets = [train_ds,valid_ds]\n if test_ds is not None: datasets.append(test_ds)\n if ds_tfms: datasets = transform_datasets(*datasets, tfms=ds_tfms, size=size, **kwargs)\n dls = [DataLoader(*o, num_workers=num_workers) for o in\n zip(datasets, (bs,bs*2,bs*2), (True,False,False))]\n return DataBunch(*dls, path=path, device=device, tfms=tfms)\n\nDataBunch.create = _create_with_tfm\n\ndef image_data_from_folder(path:PathOrStr, train:PathOrStr='train', valid:PathOrStr='valid',\n test:Optional[PathOrStr]=None, **kwargs:Any):\n \"Create `DataBunch` from imagenet style dataset in `path` with `train`,`valid`,`test` subfolders\"\n path=Path(path)\n train_ds = FilesDataset.from_folder(path/train)\n datasets = [train_ds, FilesDataset.from_folder(path/valid, classes=train_ds.classes)]\n if test: datasets.append(FilesDataset.from_single_folder(\n path/test,classes=train_ds.classes))\n return DataBunch.create(*datasets, path=path, **kwargs)\n\n","sub_path":"fastai/vision/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":11119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"635552164","text":"import re\r\nimport os\r\nfrom colorFixer import fixColor\r\n\r\nclass Feature:\r\n def __init__(self, name='', obvsText='', actionText='', allowedActions=''):\r\n self.name = name\r\n self.obvsText = obvsText\r\n self.actionText = actionText\r\n self.allowedActions = allowedActions\r\n \r\n def __str__(self):\r\n return str(self.__class__) + \": \" + str(self.__dict__)\r\n \r\n def __eq__(self, other):\r\n self.name == other\r\n\r\n def loadFeature(self, gameName, featureName):\r\n featurePath = './saved_games/' + gameName + '/features/' + featureName + '.txt'\r\n if os.path.exists(featurePath) == False:\r\n return -1\r\n else:\r\n inputFeature = open(featurePath, 'r')\r\n for line in inputFeature:\r\n if 'actionText' in line:\r\n words = re.split(\"[:]+\", line)\r\n words = [x.strip() for x in words]\r\n counter = 1\r\n featureData = []\r\n if len(words) > 1:\r\n for x in words[1:]:\r\n if counter & 1 and x != '':\r\n featureData.append((x, fixColor(words[counter+1])))\r\n counter += 1\r\n elif 'allowedActions' in line:\r\n words = re.split(\"[:,]+\", line)\r\n words = [x.strip() for x in words]\r\n featureData = []\r\n if len(words) > 1:\r\n for x in words[1:]:\r\n if x != '':\r\n featureData.append(x)\r\n else:\r\n words = re.split(\"[:]+\", line)\r\n words = [x.strip() for x in words]\r\n featureData = fixColor(words[1])\r\n setattr(self, words[0], featureData)\r\n","sub_path":"feature.py","file_name":"feature.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"499426031","text":"\"\"\"Water refinement with CNS.\"\"\"\nfrom pathlib import Path\n\nfrom haddock.gear.haddockmodel import HaddockModel\nfrom haddock.libs.libcns import prepare_cns_input, prepare_expected_pdb\nfrom haddock.libs.libsubprocess import CNSJob\nfrom haddock.modules import get_engine\nfrom haddock.modules.base_cns_module import BaseCNSModule\n\n\nRECIPE_PATH = Path(__file__).resolve().parent\nDEFAULT_CONFIG = Path(RECIPE_PATH, \"defaults.yaml\")\n\n\nclass HaddockModule(BaseCNSModule):\n \"\"\"HADDOCK3 module for water refinement.\"\"\"\n\n name = RECIPE_PATH.name\n\n def __init__(self, order, path, initial_params=DEFAULT_CONFIG):\n cns_script = Path(RECIPE_PATH, \"cns\", \"mdref.cns\")\n super().__init__(order, path, initial_params, cns_script=cns_script)\n\n @classmethod\n def confirm_installation(cls):\n \"\"\"Confirm if module is installed.\"\"\"\n return\n\n def _run(self):\n \"\"\"Execute module.\"\"\"\n # Pool of jobs to be executed by the CNS engine\n jobs = []\n\n # Get the models generated in previous step\n try:\n models_to_refine = self.previous_io.retrieve_models()\n except Exception as e:\n self.finish_with_error(e)\n\n self.output_models = []\n \n sampling_factor = self.params[\"sampling_factor\"]\n if sampling_factor > 1:\n self.log(f\"sampling_factor={sampling_factor}\")\n if sampling_factor == 0:\n self.log(\"[Warning] sampling_factor cannot be 0, setting it to 1\")\n sampling_factor = 1\n if sampling_factor > 100:\n self.log(\"[Warning] sampling_factor is larger than 100\")\n \n # checking the ambig_fname:\n try:\n prev_ambig_fnames = [mod.restr_fname for mod in models_to_refine]\n except Exception as e: # noqa:F841\n # cannot extract restr_fname info from tuples\n prev_ambig_fnames = [None for mod in models_to_refine]\n\n ambig_fnames = self.get_ambig_fnames(prev_ambig_fnames)\n\n model_idx = 0\n idx = 1\n for model in models_to_refine:\n # assign ambig_fname\n if ambig_fnames:\n ambig_fname = ambig_fnames[model_idx]\n else:\n ambig_fname = self.params[\"ambig_fname\"]\n model_idx += 1\n\n for _ in range(self.params['sampling_factor']):\n inp_file = prepare_cns_input(\n idx,\n model,\n self.path,\n self.recipe_str,\n self.params,\n \"mdref\",\n ambig_fname=ambig_fname,\n native_segid=True,\n )\n out_file = f\"mdref_{idx}.out\"\n\n # create the expected PDBobject\n expected_pdb = prepare_expected_pdb(\n model, idx, \".\", \"mdref\"\n )\n expected_pdb.restr_fname = ambig_fname\n self.output_models.append(expected_pdb)\n\n job = CNSJob(inp_file, out_file, envvars=self.envvars)\n\n jobs.append(job)\n\n idx += 1\n\n # Run CNS Jobs\n self.log(f\"Running CNS Jobs n={len(jobs)}\")\n Engine = get_engine(self.params['mode'], self.params)\n engine = Engine(jobs)\n engine.run()\n self.log(\"CNS jobs have finished\")\n\n # Get the weights from the defaults\n _weight_keys = (\"w_vdw\", \"w_elec\", \"w_desolv\", \"w_air\", \"w_bsa\")\n weights = {e: self.params[e] for e in _weight_keys}\n\n for pdb in self.output_models:\n if pdb.is_present():\n haddock_model = HaddockModel(pdb.file_name)\n pdb.unw_energies = haddock_model.energies\n \n haddock_score = haddock_model.calc_haddock_score(**weights)\n pdb.score = haddock_score\n\n # Save module information\n self.export_output_models(faulty_tolerance=self.params[\"tolerance\"])\n","sub_path":"src/haddock/modules/refinement/mdref/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"403738631","text":"#!/usr/bin/python3\n\nfrom flask import Flask, request\nimport json\nimport re\nimport pymongo\nfrom run import config, app, zbrunk_db, events_collection, searcher_auth_tokens\n\n@app.route('/services/searcher', methods=['POST'])\ndef search():\n if request.method == 'POST':\n status_ok = True\n results = list()\n results_count = 0\n all_results_count = 0\n events = list()\n\n # Example:\n #curl -k https://127.0.0.1:8088/services/searcher \\\n # -d '{\"search\": \"query\", \"output_mode\": \"json\", \"max_count\":\"10000000\",\n # \"auth_token\":\"8DEE8A67-7700-4BA7-8CBF-4B917CE23512\"}'\n\n if request.json:\n try:\n search_params = request.json\n except:\n text = \"Data parsing failure\"\n code = 3\n status_ok = False\n elif request.form:\n search_params = dict()\n data_string = list(request.form)[0]\n print(data_string)\n try:\n search_params = json.loads(data_string)\n except:\n text = \"Data parsing failure\"\n code = 3\n status_ok = False\n\n auth_token = \"\"\n if search_params != dict():\n if 'auth_token' in search_params:\n auth_token = search_params['auth_token']\n if not auth_token in searcher_auth_tokens:\n text = \"Authentication Error\"\n code = 2\n status_ok = False\n if auth_token in searcher_auth_tokens:\n if 'read' not in searcher_auth_tokens[auth_token]['permissions']:\n text = \"Permission Denied\"\n code = 2\n status_ok = False\n\n search_delete = False\n if 'delete' in search_params:\n if search_params['delete'] == \"True\":\n search_delete = True\n if auth_token in searcher_auth_tokens:\n if 'delete' not in searcher_auth_tokens[auth_token]['permissions']:\n text = \"Permission Denied\"\n code = 2\n status_ok = False\n\n get_types = False #requeres read reprmissions\n if 'get_types' in search_params:\n if search_params['get_types'] == \"True\":\n get_types = True\n\n if status_ok == True:\n text = \"Success\"\n events = search_params['search']\n code = 0\n\n if get_types:\n search_request = {\"$and\": [\n {\"time\": {\"$gte\": int(search_params['search'][\"time\"][\"from\"])}},\n {\"time\": {\"$lte\": int(search_params['search'][\"time\"][\"to\"])}}\n ]}\n else:\n search_request = {\"$and\": [\n {\"event_type\": {\"$eq\": search_params['search'][\"event_type\"]}},\n {\"time\": {\"$gte\": int(search_params['search'][\"time\"][\"from\"])}},\n {\"time\": {\"$lte\": int(search_params['search'][\"time\"][\"to\"])}}\n ]}\n\n\n # Defaults\n if not \"max_count\" in search_params:\n search_params['max_count'] = \"100000\"\n if not \"skip\" in search_params:\n search_params['skip'] = \"0\"\n\n if search_delete:\n events_collection.remove(search_request)\n text = \"Events deleted\"\n elif get_types:\n types = events_collection.distinct(key='event_type', filter={\"$and\": [\n {\"time\": {\"$gte\": int(search_params['search'][\"time\"][\"from\"])}},\n {\"time\": {\"$lte\": int(search_params['search'][\"time\"][\"to\"])}}\n ]})\n for type in types:\n results.append(type)\n results_count = len(results)\n text = \"Types found\"\n else:\n search_results = events_collection.find(search_request).sort( [(\"time\", pymongo.DESCENDING)] ).skip(int(search_params['skip'])).limit(int(search_params['max_count']))\n all_results_count = search_results.count()\n for event in search_results:\n event['_id'] = str(event['_id'])\n results.append(event)\n results_count = len(results)\n\n return json.dumps({'results': results, 'results_count':results_count,\n 'all_results_count':all_results_count, 'text':text, 'code':code}) + \"\\n\"","sub_path":"web/searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":4556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"564828245","text":"import numpy\n\nclass LivingCell(object):\n \"\"\" The class is a cell that lives on the map\n It is an object that interacts with the maps,\n consuming some resources and producing others\n\n Attributes:\n \n coordx - x-coord \n coordy - y-coord\n\n dna - (string) describes the atributes in a text string\n \n size - the size of the cell\n foodlimit - how much food it can consume\n sugardigest - the digestion rate of sugar\n lightdigest - the digestion rate of light\n meatdigest - the digestion rate of meat\n sugarsensor - the effectiveness of the sugar sensor (0-10) - pulls the cell against the sugar gradient\n lightsensor - the effectiveness of the light sensor (0-10) - pulls the cell against the light gradient\n meatsensor - the effectiveness of the meat sensor (0-10) - pull towards the closest cell\n flagela - the size of the flagela (sets the movement speed against the gradients\n\n\n\n childdev - (0-1) the % of child development\n\n\n Attributes: single letter, 0.1 contribution to size:\n a - nutrinet digest\n b - light digest\n c - meat digest\n Numbers - interpreted as numbers in a normalized sum (e.g. 11112345 = (1+1+1+1+2+3+4+5)/(8*9)\n\n Small features: double letters, .2 contribution to size\n aa - nutrient sensor\n bb - light sensor\n cc - meat sensor\n Numbers - interpreted as numbers in a normalized sum (e.g. 11112345 = (1+1+1+1+2+3+4+5)/(8*9)\n\n Large features: tripple letters, .5 contribution to size\n abc - flagella - allows to move up gradients\n aaa - nutrinet mouth - additional consumption of a resource\n bbb - light mouth - additional consumption of a resource\n ccc - meat mouth - additional consumption of a resource\n Numbers - interpreted as numbers in a normalized sum (e.g. 11112345 = (1+1+1+1+2+3+4+5)/(8*9)\n \n \"\"\"\n \n def __init__(self, coordx, coordy, dna, attributes=[('a','5')], sfeatures=[('','')], lfeatures=[('','')]):\n\n self.coordx = coordx\n self.coordy = coordy\n self.dna = dna\n for n in attributes:\n if n[0] == 'a':\n self.nutridigest = n[1]\n elif n[0] == 'b':\n self.lightdigest = n[1]\n elif n[0] == 'c':\n self.meatdigest = n[1]\n\n self.nutrisensor = []\n self.lightsensor = []\n self.meatsensor = []\n \n for n in sfeatures:\n if n[0] == 'aa':\n self.nutrisensor += [n[1]]\n elif n[0] == 'bb':\n self.lightsensor += [n[1]]\n elif n[0] == 'cc':\n self.meatsensor += [n[1]]\n\n self.flagella = []\n self.nutrimouth =[]\n self.lightmouth=[]\n self.meatmouth=[]\n for n in lfeatures:\n if n[0] == 'abc':\n self.flagella += [n[1]]\n elif n[0] == 'aaa':\n self.nutrimouth += [n[1]]\n elif n[0] == 'bbb':\n self.lightmouth += [n[1]]\n elif n[0] == 'ccc':\n self.lightmouth += [n[1]]\n \n\n\n self.size = 0.5+sum([a for (q,a) in attributes])*0.1+sum([a for (q,a) in sfeatures])*0.2+sum([a for (q,a) in lfeatures])*0.5\n\n self.radiation = 0\n self.childdev = 0\n self.childdna = ''\n self.food = 0.5 #amount of stored food\n\n\n def brownmove (self, temperature):\n #\"Fake Brownian motion of cell due to local temperature\"\n\n D=temperature/3000/self.size\n direction = numpy.random.randint(0,360)*numpy.pi/180\n dx=D*numpy.cos(direction)\n dy=D*numpy.sin(direction)\n self.coordx=self.coordx+dx\n self.coordy=self.coordy+dy\n\n def swim (self, sugarmap, lightmap, meatmap):\n #\"Motion of cells up the gradients, depending on cell's sensors and flagela\"\n \n x=numpy.round(self.coordx)\n y=numpy.round(self.coordy)\n \n gradsugarx=(sugarmap(x+1,y)-sugarmap(x,y))-(sugarmap(x,y)-sugarmap(x-1,y))\n gradsugary=(sugarmap(x,y+1)-sugarmap(x,y))-(sugarmap(x,y)-sugarmap(x,y-1))\n \n gradlightx=(lightmap(x+1,y)-lightmap(x,y))-(lightmap(x,y)-lightmap(x-1,y))\n gradlighty=(lightmap(x,y+1)-lightmap(x,y))-(lightmap(x,y)-lightmap(x,y-1)) \n\n\n dx=(gradsugarx*self.sugarsensor+gradlightx*self.lightsensor)*self.flagella/self.size\n dy=(gradsugary*self.sugarsensor+gradlighty*self.lightsensor)*self.flagella/self.size\n\n self.coordx=self.coordx+dx\n self.coordy=self.coordy+dy\n \n#\"\"\" def drift (currentdir, currentmag): \"\"\" \n\n def eat (self):\n #\"Eat materials that are on this cell and excrete materials onto this cell\"\n \"\"\" nutrient + O2 = CO2 + energy\n meat + O2 = CO2 + energy*2\n Light + CO2 = O2 + energy\"\"\"\n x=numpy.round(self.coordx)\n y=numpy.round(self.coordy)\n\n\n\n def foodincrease (self, eaten):\n\n if self.food < self.size:\n if self.food + eaten <= self.size:\n self.food = self.food + eaten\n else:\n self.childdev = self.childdev + eaten - (self.size - self.food)\n self.food = self.size\n\n else:\n self.food = self.size\n self.childdev = self.childdev + eaten\n\n def fooddecrease (self):\n consumption = self.size*self.flagella + 0.01\n self.food = self.food - consumption\n\n\n def childgrowth (self, radiationdose):\n if self.childdev > 0:\n self.radiation += radiationdose\n\n def childbirth (self):\n self.childdna = ''\n \n for n in self.dna:\n rand = numpy.random.rand()\n if rand < self.radiation/3000: #add a new letter\n self.childdna+= numpy.random.choice(['a','b','c','d','0','1','2','3','4','5','6','7','8','9'])\n \n elif rand > self.radiation/3000 and rand < self.radiation*2/3000: #remove a letter\n n = ''\n\n elif rand > self.radiation*2/3000 and rand < self.radiation*3/3000: #replace a letter\n n = numpy.random.choice(['a','b','c','d','0','1','2','3','4','5','6','7','8','9']) \n \n self.childdna+=n\n\n return self.childdna\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n","sub_path":"cell1.py","file_name":"cell1.py","file_ext":"py","file_size_in_byte":6546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"99789604","text":"\nimport re\nimport json\nimport csv\nimport os\n\n# Remove punctuation and symbols\ndef clean_str(text, lowering):\n if lowering == \"TRUE\": \n text = text.lower()\n\n text = re.sub('\\n', '', text)\n text = re.sub('\\s+', ' ', text)\n punct = '[,\\.@\\?\\!\\-\\=\\:\\–\\;\\\"]+'\n text = re.sub(punct, '', text)\n text = text.strip()\n return text\n\n\n# Function that takes a texts, collects metadata and writes metadata to the file meta.csv\ndef collect_meta(text):\n\n # Retrieving information\n head = re.search('''Текст (\\d+)\\.\\s(.+)\nЗаписано:\\s(\\d+\\.\\d+\\.\\d+),\\s(.+)\nФайл:\\s(.+)\nПродолжительность:\\s(.+)\nРассказано:\\s(.+)\nРасшифровка_лингвист:\\s(.+)\nРасшифровка_информанты:\\s(.+)\\n''', text)\n \n num = head.group(1)\n name = head.group(2) \n dat = head.group(3)\n loc = head.group(4)\n file = head.group(5)\n length = head.group(6)\n speaker = head.group(7)\n transcript_linguist = head.group(8)\n transcript_consultants = head.group(9)\n\n # Maping speaker names, lingusts ansd consultanst to codes\n with open(\"codes.json\", 'r') as f: \n codes = json.load(f)\n speaker_dict = codes[0]\n ling_dict = codes[1]\n consts_dict = codes[2]\n\n speaker_lastname = speaker.split(' ')[-1]\n speaker_code = speaker_dict[speaker_lastname][\"code\"]\n\n ling_lastname = transcript_linguist.split(\" \")[-1]\n ling_code = ling_dict[ling_lastname]\n \n consts = transcript_consultants.split(', ')\n consts_codes = []\n for c in consts: \n consts_codes.append(consts_dict[c][0])\n\n # Write all the information to the meta.csv file\n\n with open('meta.csv', 'a', newline = '') as metafile:\n metawriter = csv.writer(metafile, delimiter='\\t', quotechar='|')\n metalist = [file, name, speaker_code, length, dat, loc, ling_code, ', '.join(consts_codes)]\n metawriter.writerow(metalist)\n\n return metalist\n \n\n# Function that takes a text and returns a dictionary with sentences, words and glosses. \ndef collect_content(text):\n\n # Group sentences\n sent = re.findall('\\d+\\.\\n[0-9]{1,7}\\s+[0-9]{1,7}\\n.+\\n\\n+.+\\n\\n+.+\\n\\n+.+\\n\\n', text)\n textdict = {}\n # For every sentence\n for se in sent:\n se_list = se.split('\\n')\n se_list = [i for i in se_list if i]\n\n # Retrieve all the information\n se_num = se_list[0].strip('.')\n \n timing = se_list[1].split(' ')\n start_t, end_t = int(timing[0]), int(timing[1])\n\n orth_tier = se_list[2]\n trans_tier = se_list[3]\n gloss_tier = se_list[4]\n trans_ru = se_list[5]\n\n textdict.update({se_num: {\"orth\" : orth_tier,\n \"start_t\": start_t,\n \"end_t\": end_t, \n \"duration\": end_t -start_t,\n \"translation\" : trans_ru,\n \"words\": {}} })\n \n # Identify words in each tier\n orth_list = orth_tier.split(' ')\n orth_list = [clean_str(i, lowering = \"TRUE\") for i in orth_list]\n orth_list = [(i) for i in orth_list if i != '']\n trans_list = trans_tier.split(' ')\n gloss_list = gloss_tier.split(' ')\n\n # Match words with their transcription and glosses\n for w in orth_list:\n indx = orth_list.index(w)\n w_num = 'w' + str(indx)\n\n try:\n w_transcript = trans_list[indx]\n except IndexError: \n (\"mist!\" + w_transcript)\n\n try: \n w_gloss = gloss_list[indx] \n except IndexError: \n w_gloss = ''\n print('>>' + w, se)\n\n textdict[se_num]['words'].update({w_num: {\"w_orth\": w, \n \"w_transcript\": w_transcript, \n \"w_gloss\": w_gloss}})\n return textdict\n\n\n\n\n# Writes the content of the dictionary, generated for the text into a separate csv\ndef dict2csv(textdict, metalist):\n\n # Make 'tiers' to paste it into a .csv file\n\n speaker_code = metalist[2]\n\n tier1_name = speaker_code + \"_Transcription-txt\"\n tier2_name = speaker_code + \"_Words-txt\"\n tier3_name = speaker_code + \"_Morph-txt\"\n tier4_name = speaker_code + \"_Gloss-txt\"\n tier5_name = speaker_code + \"_Translation-gls\"\n\n tier1_annotations = []\n tier2_annotations = []\n tier3_annotations = []\n tier4_annotations = []\n tier5_annotations = []\n\n for se_num in sorted(textdict):\n start = textdict[se_num]['start_t']\n end = textdict[se_num]['end_t']\n duration = textdict[se_num]['duration']\n orth_ann = textdict[se_num]['orth']\n trans_ru_ann = textdict[se_num]['translation']\n \n tier1_annotations.append([tier1_name, start, end, duration, orth_ann])\n tier5_annotations.append([tier5_name, start, end, duration, trans_ru_ann])\n\n for w_num in textdict[se_num]['words']:\n duration_w = round(duration/len(textdict[se_num]['words']))\n start_w = start\n end_w = start_w + duration_w\n \n transcr_w_ann = textdict[se_num]['words'][w_num]['w_transcript']\n gloss_w_ann = textdict[se_num]['words'][w_num]['w_gloss']\n\n tier2_annotations.append([tier2_name, start_w, end_w, duration_w, transcr_w_ann.replace('-', '')])\n tier3_annotations.append([tier3_name, start_w, end_w, duration_w, transcr_w_ann])\n tier4_annotations.append([tier4_name, start_w, end_w, duration_w, gloss_w_ann])\n\n start = end_w\n\n\n # Paste info to the file \n filename = metalist[0].replace(\".wav\", \".csv\")\n \n with open('csv/' + filename, 'a', newline = '') as f: \n fwriter = csv.writer(f, delimiter='\\t', quotechar='|')\n for x in tier1_annotations: fwriter.writerow(x)\n for x in tier2_annotations: fwriter.writerow(x)\n for x in tier3_annotations: fwriter.writerow(x)\n for x in tier4_annotations: fwriter.writerow(x)\n for x in tier5_annotations: fwriter.writerow(x)\n\n\ndef main():\n with open('abaza_oral_corpus_whole.txt', 'r') as f:\n all_texts = f.read()\n texts = all_texts.split('---\\n\\n\\n')\n\n # Form every text: collect metadata, collect data\n for t in texts[2:]:\n\n # Writes metaifo to a file called meta.csv and returns the collected information in a form of list \n try:\n metalist = collect_meta(t)\n except AttributeError: print(t[:20])\n\n # Collects the main body of data and writes it to a .csv file with a name corresponding to the original filename\n textdict = collect_content(t)\n dict2csv(textdict, metalist)\n\n\nmain()\n\n\n\n","sub_path":"txt2csv.py","file_name":"txt2csv.py","file_ext":"py","file_size_in_byte":6891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"127519604","text":"#Imports\r\nimport smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nimport datetime\r\n\r\n#Testing list for email client. -Not currently Used!\r\npeople = [\"pburton\", \"hbarclay\", \"mevans\"]\r\n\r\n#Sends the emails to the correct person.\r\ndef end_emails_sender (staff_name, total_students):\r\n\r\n #email sender and recipiant. will be changed later to a outlook address.\r\n fromaddr = \"mattevans777@gmail.com\"\r\n toaddr = staff_name\r\n \r\n msg = MIMEMultipart()\r\n msg['From'] = fromaddr\r\n msg['To'] = toaddr\r\n msg['Subject'] = \"Role for class ....\"\r\n \r\n #This will eventaully befcome a list of student names that check in and the total number. \r\n #Just using number now for testing.\r\n body = \"here is the total number of students in your class\" , total_students\r\n msg.attach(MIMEText(body, 'plain'))\r\n \r\n #Email deatials. PASSWORD removed for security.\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.starttls()\r\n server.login(fromaddr, \"PASSWORD GOES HERE\")\r\n text = msg.as_string()\r\n server.sendmail(fromaddr, toaddr, text) \r\n \r\n server.quit() \r\n\r\n\r\n#Main function. for now. \r\ndef timer_setup():\r\n \r\n #asks for the staff user name. eg. like the list above. And formats it into an email.\r\n #This will later be upgraded to an ID number - possible a NFC card.\r\n staff_name = input(\"please input your email address before the @ symbol \")\r\n staff_name = staff_name+(\"@stc.school.nz\")\r\n \r\n print(staff_name) #TEST. checks the email is set up correctly\r\n \r\n #counter for the total number of students\r\n total = 0\r\n \r\n #Timer set for 10s for TESTING. will be set for 5 minutes from when a teacher enters thier username.\r\n finish_time = datetime.datetime.now() + datetime.timedelta(seconds = 10)\r\n \r\n print(finish_time) #TESTING\r\n print(\"#####\") #TESTING\r\n \r\n #variable for date time at current point for while loop.\r\n current = datetime.datetime.now()\r\n \r\n #while statement checks current time vs. finish time. \r\n #when false the should pass total onto the email function.\r\n while current <= finish_time: \r\n student = input(\"what is your name\")\r\n total = total + 1\r\n print(total) #TESTING\r\n current = datetime.datetime.now()\r\n print (current)#TESTING\r\n \r\n #Once timer is up display the late msg and sends email to staff. \r\n print(\"time is up. You are now late!\")\r\n end_emails_sender(staff_name,total) \r\n \r\n#Runs MIAN function\r\ntimer_setup()\r\n","sub_path":"Testing-mail.py","file_name":"Testing-mail.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"343820589","text":"# Module & Package\n## 모듈과 패키지 불러오기\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport json\nimport numpy, scipy, pylab, random\nimport re\nfrom pylab import plot, show\nimport csv\nimport scipy.cluster.hierarchy as shc\nimport time\nfrom sklearn.cluster import AgglomerativeClustering\nfrom collections import Counter\npd.set_option(\"display.max_rows\",999)\nget_ipython().run_line_magic('matplotlib', 'inline')\n\n\n# Declare Functions\n## 데이터프레임을 받았을 때, Object 파일형태는 공백을 제거해주는 함수\ndef stripping_dataframe(dataframe):\n for column in dataframe.select_dtypes(include=['object']).columns.tolist():\n print (\"'\"+column+\"'\"+\" 컬럼에 대한 공백제거 작업완료\")\n dataframe[column] = dataframe[column].str.strip()\n\n\n# Read Data\n## 공통되는 경로는 변수로 관리하기 위해서 경로 변수 선언.\n## 각각 파일명은 기존의 인프런에서 제공받은 그대로 유지.\ndata_path='./source_data/'\n### 수강완료 필드 불러오기\nunit_complete_df1 = pd.read_json(data_path+'unit_complete_0.json',encoding='utf-8')\nunit_complete_df2 = pd.read_json(data_path+'unit_complete_1.json',encoding='utf-8')\nunit_complete_df3 = pd.read_json(data_path+'unit_complete_2.json',encoding='utf-8')\nunit_complete_df4 = pd.read_json(data_path+'unit_complete_3.json',encoding='utf-8')\n### 구독완료 필드 불러오기\nsubscribe_df = pd.read_json(data_path+'subscribe_course_0.json',encoding='utf-8')\n### 수강시작 필드 불러오기\nstartcourse_df = pd.read_json(data_path+'start_course_0.json',encoding='utf-8')\n### 신규유저 필드 불러오기 (필요없기 때문에 불러오지 않음)\n#newmember_df = pd.read_json(data_path+'new_member_0.json',encoding='utf-8')\n\n\n# Unique Lecture List from Json files\ndf_all = pd.concat((unit_complete_df1,\n unit_complete_df2,\n unit_complete_df3,\n unit_complete_df4,\n# newmember_df,\n startcourse_df,\n subscribe_df), axis=0)\ndf_all = df_all.reset_index(drop=True)\ndf_Extracted_lecture_A = df_all\ndf_Extracted_lecture_A = df_Extracted_lecture_A.drop(labels=['활동ID','활동시각'],axis=1)\ndf_Extracted_lecture_A = df_Extracted_lecture_A.reset_index(drop=True)\ndf_Extracted_lecture_A['강좌ID'] = df_Extracted_lecture_A['강좌ID'].apply(lambda x: np.nan if x == \"nan\" else x)\ndf_Extracted_lecture_A = df_Extracted_lecture_A.dropna(subset=['강좌ID'])\n\n\n# Unique Lecture List from CSV files\nPayment_df1 =pd.read_csv(data_path+\"./201801.csv\",sep='\\t')\nPayment_df2 = pd.read_csv(data_path+\"./201802.csv\",sep='\\t')\nPayment_df3 = pd.read_csv(data_path+\"./201803.csv\")\nPayment_df4 = pd.read_csv(data_path+\"./201804.csv\")\nPayment_df5 = pd.read_csv(data_path+\"./201805.csv\")\nPayment_df6 = pd.read_csv(data_path+\"./201806.csv\")\nPayment_df7 = pd.read_csv(data_path+\"./201807.csv\")\nPayment_df8 = pd.read_csv(data_path+\"./201808.csv\")\nPayment_df9 = pd.read_csv(data_path+\"./201809.csv\")\nPayment_df10 = pd.read_csv(data_path+\"./201810.csv\")\nPayment_df1['isit_timedata'] = False\nPayment_df1['날짜'] = Payment_df1['날짜'] + \" 00:00\"\nPayment_df2['isit_timedata'] = False\nPayment_df2['날짜'] = Payment_df2['날짜'] + \" 00:00\"\nPayment_df3['isit_timedata'] = True\nPayment_df4['isit_timedata'] = True\nPayment_df5['isit_timedata'] = True\nPayment_df6['isit_timedata'] = True\nPayment_df7['isit_timedata'] = True\nPayment_df8['isit_timedata'] = True\nPayment_df9['isit_timedata'] = True\nPayment_df10['isit_timedata'] = True\ndf_payment_all = pd.concat((Payment_df1,\n Payment_df2,\n Payment_df3,\n Payment_df4,\n Payment_df5,\n Payment_df6,\n Payment_df7,\n Payment_df8,\n Payment_df9,\n Payment_df10), axis=0)\ndf_payment_all = df_payment_all.reset_index(drop=True)\ndf_payment_all['Name'] = df_payment_all['Name'].str.replace('_','-')\n## 오른쪽에서 처음나오는 - 기준으로 스플릿\ndf_payment_all['lecture_name'], df_payment_all['instructor'] = df_payment_all['Name'].str.rsplit('-', 1).str\ndel df_payment_all['Name']\ndf_payment_all['Order Id'], df_payment_all['trash'] = df_payment_all['Order Id'].astype(str,errors='ignore').str.rsplit('.', 1).str\ndf_payment_all['Customer User Id'], df_payment_all['trash'] = df_payment_all['Customer User Id'].astype(str,errors='ignore').str.rsplit('.', 1).str\ndel df_payment_all['trash']\ndf_payment_all['Order Id'] = df_payment_all['Order Id'].apply(lambda x: np.nan if x == \"nan\" else x)\ndf_payment_all['Customer User Id'] = df_payment_all['Customer User Id'].apply(lambda x: np.nan if x == \"nan\" else x)\nstripping_dataframe(df_payment_all)\ndf_payment_all[\"날짜\"] = pd.to_datetime(df_payment_all[\"날짜\"],format='%Y-%m-%d %H:%M')\ndef make_free(row):\n make_free = row['Item Cost']\n if make_free == 0:\n return \"free\"\n else:\n return row['결제방법']\ndf_payment_all['결제방법'] = df_payment_all.apply(make_free, axis=1)\ndef methods(row):\n str_methods = row['결제방법']\n if len(str_methods.split(\"_\")) == 2:\n return str_methods.split(\"_\")[1]\n else:\n return str_methods.split(\"_\")[0]\ndef isit_iamport(row):\n str_methods = row['결제방법']\n if len(str_methods.split(\"_\")) == 2:\n return True\n else:\n return False\n# NULL값은 위에 Order id, 날짜, Customer id, 결제방법 똑같이 해주기\nFill_NA_df_all = df_payment_all.fillna(method='ffill')\nFill_NA_df_all['methods'] = Fill_NA_df_all.apply(methods, axis=1)\nFill_NA_df_all['isit_iamport'] = Fill_NA_df_all.apply(isit_iamport, axis=1)\ndel Fill_NA_df_all['결제방법']\ndf_all_copyed = Fill_NA_df_all\ndf_all_copyed = df_all_copyed.rename(index=str, columns={\"Customer User Id\": \"Customer_User_Id\", \"Item Cost\": \"Item_Cost\", \"Order Id\": \"Order_Id\"})\ndf_Extracted_lecture_B = df_all_copyed\ndf_Extracted_lecture_B = df_Extracted_lecture_B.drop(labels=['Order_Id','날짜','isit_timedata','methods','isit_iamport'],axis=1)\ndf_Extracted_lecture_B = df_Extracted_lecture_B.reset_index(drop=True)\ndf_Extracted_lecture_B = df_Extracted_lecture_B.rename(index=str, columns={\"lecture_name\": \"강좌명\"})\n\n\n# Preprocessing for Merge A, B\ndef trans(row):\n str_methods = row['강좌명']\n if str_methods in instructor_from_lecture:\n return instructor_from_lecture[str_methods]\n else:\n return row[\"instructor\"]\n\na = df_Extracted_lecture_A\nb = df_Extracted_lecture_B\ncsv_path='./source_data/'\ntry:\n b.drop(b[b.강좌명==\"결제 테스트용 2000원\"].index, inplace = True)###########################허구데이터\n b.drop(b[b.강좌명==\"파이어베이스 위치기반서비스 만들기\"].index, inplace = True) ############비공개 강좌\n\n ########################################################################강좌명 통일\n lecture_list={}\n f = open(csv_path+'1.lecture_list.csv', 'r')\n try:\n reader1 = csv.DictReader(f)\n for row in reader1:\n lecture_list=row\n finally:\n f.close()\n\n for i in b[\"강좌명\"]:\n try:\n b['강좌명'] = b['강좌명'].str.replace(i,lecture_list[i])\n except:\n None\n ########################################################################강좌명 통일\n\n ########################################################################instructor 통일\n merge_instructor={}\n f = open(csv_path+'2.merge_instructor.csv', 'r')\n try:\n reader2 = csv.DictReader(f)\n for row in reader2:\n merge_instructor=row\n finally:\n f.close()\n\n for i in b[\"instructor\"]:\n try:\n b['instructor'] = b['instructor'].str.replace(i,merge_instructor[i])\n except:\n None\n ########################################################################instructor 통일\n\n ########################################################################instructor from 강좌명\n instructor_from_lecture={}\n f = open(csv_path+'3.instructor_from_lecture.csv', 'r')\n try:\n reader3 = csv.DictReader(f)\n for row in reader3:\n instructor_from_lecture=row\n finally:\n f.close()\n\n b[\"instructor\"] = b.apply(trans, axis=1)\n ########################################################################instructor from 강좌명\nexcept:\n print(\"Error Occurred When Preprocessing to Merge A,B\")\n\njson_data = a\ncsv_data = b\n\n\n# Merge A, B\nfull_data=pd.merge(json_data, csv_data, on=['강좌명'], how='inner')\nview_data = full_data[full_data['활동타입']=='수업완료']\nhigh_lecture = view_data.groupby(['강좌ID'])['유저ID'].count().sort_values(ascending=False)\nhigh_user = view_data.groupby(['유저ID'])['강좌ID'].count().sort_values(ascending=False)\n\n\n## 유저가 많이 들은 강좌확인\npd.DataFrame(high_lecture).head()\n## 강좌를 많이 들은 유저확인\npd.DataFrame(high_user).head()\n\n\n# 인기강좌10개, 강의많이 들은 유저 10명 제거\ndata_new = full_data[full_data['활동타입']=='수업완료']\ndata_new_lecture = data_new.groupby(by='강좌ID').count()\ndata_new_lecture = data_new_lecture.sort_index(axis=0, by='유저ID',ascending=False)\ntop_10_lecture = data_new_lecture[:10].index.tolist()\ndata_new_user = data_new.groupby(by='유저ID').count()\ndata_new_user = data_new_user.sort_index(axis=0, by='강좌ID',ascending=False)\ntop_10_user = data_new_user[:10].index.tolist()\npreprocessing_data = full_data[full_data['활동타입']=='수업완료']\npreprocessing_data = preprocessing_data[~preprocessing_data['강좌ID'].isin(top_10_lecture)]\npreprocessing_data = preprocessing_data[~preprocessing_data['유저ID'].isin(top_10_user)]\n\n\n# 만든 pivot테이블 넣고 군집화 시각화해서 확인\n## 유저별 강의 수강율 구���기\nuser_lecture = pd.DataFrame(preprocessing_data.groupby(['유저ID','강좌ID']).활동타입.count())\nuser_lecture = user_lecture.rename(index=str, columns={\"활동타입\":\"유저별완료강좌개수\"})\nuser_lecture = user_lecture.reset_index()\nlecture_df = pd.DataFrame(preprocessing_data.groupby(['강좌ID','유저ID']).활동타입.count())\nlecture_max = lecture_df.groupby(level=0).apply(max)\nlecture_max = lecture_max.rename(index=str, columns={\"활동타입\":\"max\"})\nnumber_of_videos_per_lecture = lecture_max.reset_index()\ncomplete_rate = pd.merge(user_lecture,number_of_videos_per_lecture,how = \"left\",on=['강좌ID'])\ncomplete_rate[\"rate\"]=complete_rate[\"유저별완료강좌개수\"]/complete_rate[\"max\"]\ncomplete_rate_pivot = complete_rate.pivot(index = '유저ID', columns ='강좌ID', values = 'rate').fillna(0)\n## 유저가 강의별로 1개라도 들었으면 1 아니면 0\ncomplete_lecture = pd.DataFrame(preprocessing_data.groupby(['유저ID','강좌ID']).Item_Cost.count())\ncomplete_lecture[\"boolean\"]=1\ncomplete_lecture = complete_lecture.reset_index()\ncomplete_lecture_pivot = complete_lecture.pivot(index = '유저ID', columns ='강좌ID', values = 'boolean').fillna(0)\n\n\n# 만든 pivot테이블 넣고 군집화 시각화해서 확인후 저장하기\npivot_table = complete_lecture_pivot\nnow = time.localtime()\ns = \"%04d_%02d_%02d\" % (now.tm_year, now.tm_mon, now.tm_mday)+\"_Clustering_Graph\"\ngraph_path='./graph/Clustering/'\nplt.figure(figsize=(18, 10))\nplt.title(\"Inflearn Customer Clustering\", fontsize=20)\ndend = shc.dendrogram(shc.linkage(pivot_table, method='ward'))\nplt.xlabel('User_Id')\nplt.ylabel('Distance (Ward)')\nplt.savefig(graph_path+s+'.png')\n\n\n# pivot테이블에 군집라벨 붙여주기\nnumber_label_count = len(list(set(dend['color_list'])))-1\ncluster = AgglomerativeClustering(n_clusters=number_label_count, affinity='euclidean', linkage='ward')\npivot_table_label = cluster.fit_predict(pivot_table)\npivot_table_label = pd.Series(pivot_table_label, name='label')\npivot_table = pivot_table.reset_index()\npivot_table_1 = pivot_table.join(pivot_table_label)\npivot_table_1 = pivot_table_1.set_index('유저ID')\n\n\n# 군집 유저들이 전체데이터로 봤을 때는 어떤 강좌를 몇개나 수강했는지 확인\nlabel_1_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 0].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_2_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 1].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_3_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 2].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_4_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 3].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_5_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 4].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_6_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 5].sum(axis=1)).reset_index()['유저ID'].tolist()\nlabel_7_userid = pd.DataFrame(pivot_table_1[pivot_table_1.label == 6].sum(axis=1)).reset_index()['유저ID'].tolist()\n\n\nlen(label_1_userid),len(label_2_userid),len(label_3_userid),len(label_4_userid),len(label_5_userid),len(label_6_userid)\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_1_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_1_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_1_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(full_data[full_data['유저ID'].isin(label_2_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_2_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_2_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_3_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_3_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_3_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_4_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_4_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_4_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_5_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_5_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_5_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\npd.DataFrame(df_all[df_all['유저ID'].isin(label_6_userid)].groupby(['강좌명'])['활동타입'].count().sort_values(ascending=False)).head()\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_6_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = pd.DataFrame(test_df.groupby(['강좌명'])['활동타입'].sum().sort_values(ascending=False))\nlabel_1_df['총유저수']=len(label_6_userid)\nlabel_1_df['들은퍼센트']=label_1_df['활동타입']/label_1_df['총유저수']*100\nlabel_1_df.head()\n\n\n# 군집화된 User들이 어떤 기준으로 군집이 되었는지 강의로 확인해보기\n\npivot_table_1[pivot_table_1.label == 0].sum(axis=0).sort_values().tail()\n\ntesting_df_0 = pivot_table_1[pivot_table_1.label == 0].sum(axis=0).sort_values().tail()\ntemp_df_0 = pd.DataFrame(testing_df_0)\ntemp_df_0 = temp_df_0.reset_index()\ntemp_df_0.rename(columns={temp_df_0.columns[0]:'강좌ID'}, inplace = True)\nsample_0 = pd.merge(full_data, temp_df_0, on=['강좌ID'], how='inner')\npd.DataFrame(sample_0.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 1].sum(axis=0).sort_values().tail()\n\ntesting_df_1 = pivot_table_1[pivot_table_1.label == 1].sum(axis=0).sort_values()\ntesting_df_1 = testing_df_1.drop(\"label\")\ntemp_df_1 = pd.DataFrame(testing_df_1.tail())\ntemp_df_1 = temp_df_1.reset_index()\ntemp_df_1.rename(columns={temp_df_1.columns[0]:'강좌ID'}, inplace = True)\nsample_1 = pd.merge(full_data, temp_df_1, on=['강좌ID'], how='inner')\npd.DataFrame(sample_1.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 2].sum(axis=0).sort_values().tail()\n\ntesting_df_2 = pivot_table_1[pivot_table_1.label == 2].sum(axis=0).sort_values()\ntesting_df_2 = testing_df_2.drop(\"label\")\ntemp_df_2 = pd.DataFrame(testing_df_2.tail())\ntemp_df_2 = temp_df_2.reset_index()\ntemp_df_2.rename(columns={temp_df_2.columns[0]:'강좌ID'}, inplace = True)\nsample_2 = pd.merge(full_data, temp_df_2, on=['강좌ID'], how='inner')\npd.DataFrame(sample_2.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 3].sum(axis=0).sort_values().tail()\n\ntesting_df_3 = pivot_table_1[pivot_table_1.label == 3].sum(axis=0).sort_values()\ntesting_df_3 = testing_df_3.drop(\"label\")\ntemp_df_3 = pd.DataFrame(testing_df_3.tail())\ntemp_df_3 = temp_df_3.reset_index()\ntemp_df_3.rename(columns={temp_df_3.columns[0]:'강좌ID'}, inplace = True)\nsample_3 = pd.merge(full_data, temp_df_3, on=['강좌ID'], how='inner')\npd.DataFrame(sample_3.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 4].sum(axis=0).sort_values().tail()\n\ntesting_df_4 = pivot_table_1[pivot_table_1.label == 4].sum(axis=0).sort_values()\ntesting_df_4 = testing_df_4.drop(\"label\")\ntemp_df_4 = pd.DataFrame(testing_df_4.tail())\ntemp_df_4 = temp_df_4.reset_index()\ntemp_df_4.rename(columns={temp_df_4.columns[0]:'강좌ID'}, inplace = True)\nsample_4 = pd.merge(full_data, temp_df_4, on=['강좌ID'], how='inner')\npd.DataFrame(sample_4.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\npivot_table_1[pivot_table_1.label == 5].sum(axis=0).sort_values().tail()\n\ntesting_df_5 = pivot_table_1[pivot_table_1.label == 5].sum(axis=0).sort_values()\ntesting_df_5 = testing_df_5.drop(\"label\")\ntemp_df_5 = pd.DataFrame(testing_df_5.tail())\ntemp_df_5 = temp_df_5.reset_index()\ntemp_df_5.rename(columns={temp_df_5.columns[0]:'강좌ID'}, inplace = True)\nsample_5 = pd.merge(full_data, temp_df_5, on=['강좌ID'], how='inner')\npd.DataFrame(sample_5.groupby(['강좌명','강좌ID'])['활동타입'].count()).sort_values(by='활동타입').rename(columns={'활동타입':'들은유저수'})\n\n\n# 단어추출로 군집화 특성 확인 (군집별 유저들 기준)\ndef making_list(row):\n if row != np.nan:\n test = row.split()\n else:\n test = False\n return test\n\ndef flatten(x):\n result = []\n basestring = (str)\n for el in x:\n if hasattr(el, \"__iter__\") and not isinstance(el, basestring):\n #스트링형이 아닌 이터러블의 경우 - 재귀한 후, extend\n result.extend(flatten(el)) #재귀 호출\n else:\n #이터러블이 아니거나 스트링인 경우 - 그냥 append\n result.append(el)\n return result\n\nloop_text = [\")\",\"(\",\"[\",\"]\",\"!\",\"?\",\"'\",'\"','.','+','/',\"-\",\",\",\"강좌\",\"만들기\",\"배우는\",\"위한\",\"&\",\"배우기\",\"활용한\",\"이용한\",\"를\",\"및\"]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_1_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_2_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_3_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_4_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n\ntest_df = pd.DataFrame(df_all[df_all['유저ID'].isin(label_5_userid)].groupby(['강좌명','유저ID'])['활동타입'].count().sort_values(ascending=False))\ntest_df['활동타입']=1\nlabel_1_df = test_df.reset_index()\nfor i in loop_text:\n label_1_df['강좌명'] = label_1_df['강좌명'].str.replace(i,' ', regex=False)\nlabel_1_df['강좌명1'] = label_1_df['강좌명'].astype(str).apply(making_list)\ntesting = Counter(flatten(label_1_df['강좌명1'].tolist()))\nsorted(testing.items(), key=lambda t : t[1],reverse=True)[:30]\n","sub_path":"(Machinelearn)Clustering.py","file_name":"(Machinelearn)Clustering.py","file_ext":"py","file_size_in_byte":23930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"346286058","text":"# Collection of the frequently called functions we'll be using for entity linking\n\nfrom wikidata.client import Client\nfrom nltk.corpus import stopwords\n\nimport nltk.tokenize\nimport os\nimport pywikibot\nimport wikipedia\nimport ujson\n\n# Load/generate requisite nltk files\ntokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\nstop_words = set(stopwords.words('english'))\n\nclass EntityLinker(object):\n def __init__(self, *, path='saved_data/entity_files/dict.json'):\n self.path = path\n\n # If file exists\n if os.path.isfile(path):\n # Load json file into dictionary\n self.load_dictionary()\n else:\n self.ent_dict = {}\n # Save dictionary to json file\n self.save_dictionary()\n\n def load_dictionary(self):\n \"\"\"\n :action: Saves dictionary to json file\n :return: None\n \"\"\"\n self.ent_dict = dict(ujson.load(open(self.path)))\n\n def save_dictionary(self):\n \"\"\"\n :action: Loads json file into dictionary\n :return: None\n \"\"\"\n with open(self.path, 'w') as outfile:\n ujson.dump(self.ent_dict, outfile)\n\n @staticmethod\n def identify_entities(comment):\n entities = []\n for sentence in nltk.sent_tokenize(comment):\n pending = None\n tagged_words = nltk.pos_tag(nltk.word_tokenize(sentence))\n for i, chunk in enumerate(nltk.ne_chunk(tagged_words)):\n if hasattr(chunk, 'label'):\n \"\"\"\n Occasionally, names such as Angela Merkel are interpreted by the parser as two named entities,\n Angela and Merkel. To resolve this issue, we hold the most recent entity before adding it to the \n returned list and check to see if the following entity is the next word, in which case we join the\n two. \n \"\"\"\n if pending and pending[2] == i-1:\n pending[0] += ' ' + ' '.join([c[0] for c in chunk])\n else:\n if pending:\n entities.append(tuple(pending[:2]))\n pending = [' '.join(c[0] for c in chunk), chunk.label(), i]\n if pending:\n entities.append(tuple(pending[:2]))\n return entities\n\n @staticmethod\n def page_title_to_political_party(title):\n \"\"\"\n :param title: A string page title.\n :return: A string representing the political party or affiliation of the entity described in the wikipage, if\n available. Otherwise, None.\n \"\"\"\n site = pywikibot.Site(\"en\", \"wikipedia\")\n page = pywikibot.Page(site, title)\n page = pywikibot.ItemPage.fromPage(page).get()\n\n try:\n party_page = page['claims']['P102'][0].getTarget().get()\n except (KeyError, pywikibot.NoPage):\n # No political party listed for this figure, so return None.\n return None\n\n # The English labels are usually a list, but sometimes appear as a string.\n english_labels = party_page['labels']['en']\n if isinstance(english_labels, list):\n return english_labels[0]\n elif isinstance(english_labels, str):\n return english_labels\n else:\n return None\n\n\n def entity_to_political_party(self, entity, building_dict=True, lookup_enabled=True, dict_allowed=True):\n \"\"\"\n Given an entity, return the political affiliation of that entity if one is available. Otherwise, return\n 'None found'.\n :param entity: A tuple of strings containing the name of a detected entity and its type, such as\n ('Barack Obama', 'PERSON')\n :param building_dict: If true, then newly discovered entities will be added to our\n :param lookup_enabled: Allows looking up terms not already in our dictionary of previous viewed\n entities on Wikipedia. Due to the unavoidable delay which comes with pulling data from Wikipedia,\n and the sheer number of entities mentioned in any given comment chain, this variable is here to\n be disabled in a production setting to speed up the final results.\n :param dict_allowed: Allows the dictionary of already seen entities to be used or disallowed, only used\n in testing.\n :return: A tuple of two strings, the full entity discovered and the party of this entity, if a politically\n affiliated full entity was found. Otherwise, None is returned.\n \"\"\"\n\n entity_name, ent_type = entity\n\n # If already in dictionary, return dict entry instead of looking on Wikipedia\n if dict_allowed and entity_name.lower() in self.ent_dict:\n try:\n if \"None\" in self.ent_dict[entity_name.lower()][1]:\n return None\n else:\n return tuple(self.ent_dict[entity_name.lower()])\n except TypeError:\n return None\n elif lookup_enabled:\n pages = wikipedia.search(entity_name)\n\n \"\"\"\n In the present incarnation of this project, we are focused on the political parties of\n only individuals, so other type of entities can be removed. Of course, the mention of\n geopolitical entities does have a certain political connotation, so this feature may be \n examined at a later point. \n \"\"\"\n if ent_type == 'PERSON':\n\n \"\"\"\n It is very rare for the subject of a political discussion to not be in the first five results\n for their name on Wikipedia, in fact in the testing done several months ago that was never the \n case. To save on execution time, we thus limit our exploration to the first five results with\n some semblance to the original query.\n \"\"\"\n # Occasionally, stop-words such as 'the' are in entities, so these are removed.\n entity_name_components = [part for part in entity_name.split(' ')]\n\n page_titles = []\n for title in pages[:20]:\n if len(page_titles) == 5:\n break\n if any(part_of_name in title for part_of_name in entity_name_components):\n page_titles.append(title)\n\n for title in page_titles:\n found_party = self.page_title_to_political_party(title)\n if found_party:\n if building_dict:\n self.ent_dict[entity_name.lower()] = (title, found_party)\n self.save_dictionary()\n return title, found_party\n else:\n if building_dict:\n self.ent_dict[entity_name.lower()] = ('No political figure', 'None found')\n self.save_dictionary()\n return None\n\n @staticmethod\n def political_party_to_value(party):\n \"\"\"\n :param party: A string representing the name of a political party\n :return: An integer value [-1, 1] representing this affiliation.\n \"\"\"\n # TODO: More nuanced approach, use wikipedia API rather than fixed values\n if party is not None:\n if 'republican' in party.lower():\n return 1\n elif 'democrat' in party.lower():\n return -1\n return 0\n","sub_path":"utilities/entity_toolkit.py","file_name":"entity_toolkit.py","file_ext":"py","file_size_in_byte":7538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"112980321","text":"from fractions import gcd\nfrom copy import deepcopy\nA,B=[int(i) for i in input().split()]\n\nedge=[[] for i in range(B-A+1)]\n\nfor i in range(A,B+1):\n\tfor j in range(i+1,B+1):\n\t\tif gcd(i,j)==1:\n\t\t\tedge[i-A].append(j-A)\n\t\t\t#edge[j-A].append(i-A)\nans=1\n\ndef calc(start,cond):\n\t#print(level,end=\" \")\n\t#print(start)\n\t#print(cond)\n\tans=1\n\tfor to in edge[start]:\n\t\tif to in cond:\n\t\t\t_cond=[]\n\t\t\tfor i in edge[to]:\n\t\t\t\tif i in cond:\n\t\t\t\t\t_cond.append(i)\n\t\t\tans+=calc(to,_cond)\n\treturn ans\n\nfor i in range(B-A+1):\n\tcond=[]\n\tfor j in edge[i]:\n\t\tcond.append(j)\n\tans+=calc(i,cond)\nprint(ans)\n\n\n","sub_path":"atcoder/event/colocon/coloC.py","file_name":"coloC.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"641357874","text":"from setuptools import setup, find_packages\nfrom utime import __version__\n\nwith open('README.md') as readme_file:\n readme = readme_file.read()\n\nwith open('HISTORY.rst') as history_file:\n history = history_file.read().replace('.. :changelog:', '')\n\nwith open(\"requirements.txt\") as req_file:\n requirements = list(filter(None, req_file.read().split(\"\\n\")))\n\nsetup(\n name='utime',\n version=__version__,\n description='A deep learning framework for automatic PSG sleep analysis.',\n long_description=readme + \"\\n\\n\" + history,\n author='Mathias Perslev',\n author_email='map@di.ku.dk',\n url='https://github.com/perslev/U-Time',\n license=\"LICENSE.txt\",\n packages=find_packages(),\n package_dir={'utime':\n 'utime'},\n include_package_data=True,\n setup_requires=[\"setuptools_git>=0.3\",],\n entry_points={\n 'console_scripts': [\n 'ut=utime.bin.ut:entry_func',\n ],\n },\n install_requires=requirements,\n classifiers=['Environment :: Console',\n 'Operating System :: POSIX',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'\n 'License :: OSI Approved :: MIT License']\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"270022420","text":"\"\"\" API Tests \"\"\"\nfrom __future__ import unicode_literals\n\nimport unittest\n\nfrom httmock import HTTMock, all_requests\nfrom wordpress.transport import API_Requests_Wrapper\n\n\nclass TransportTestcases(unittest.TestCase):\n def setUp(self):\n self.requester = API_Requests_Wrapper(\n url='https://woo.test:8888/',\n api='wp-json',\n api_version='wp/v2'\n )\n\n def test_api_url(self):\n self.assertEqual(\n 'https://woo.test:8888/wp-json',\n self.requester.api_url\n )\n\n def test_endpoint_url(self):\n self.assertEqual(\n 'https://woo.test:8888/wp-json/wp/v2/posts',\n self.requester.endpoint_url('posts')\n )\n\n def test_request(self):\n @all_requests\n def woo_test_mock(*args, **kwargs):\n \"\"\" URL Mock \"\"\"\n return {'status_code': 200,\n 'content': b'OK'}\n\n with HTTMock(woo_test_mock):\n # call requests\n response = self.requester.request(\n \"GET\", \"https://woo.test:8888/wp-json/wp/v2/posts\")\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.request.url,\n 'https://woo.test:8888/wp-json/wp/v2/posts')\n","sub_path":"tests/test_transport.py","file_name":"test_transport.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"520911308","text":"#-*- coding: utf-8 -*-\nfrom typing import List\nimport math\n\nimport time\ndef timeit(func):\n def wrapped(*args, **kwargs):\n start = time.time()\n ret = func(*args, **kwargs)\n elapsed = time.time() - start\n print(\"elapsed: %s\" % elapsed)\n return ret\n return wrapped\n\n# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:\n curr1 = l1\n curr2 = l2\n head = ListNode('start')\n curr_new = head\n while curr1 or curr2:\n if curr1 and curr2:\n if curr1.val < curr2.val:\n curr_new.next = ListNode(curr1.val)\n curr1 = curr1.next\n else:\n curr_new.next = ListNode(curr2.val)\n curr2 = curr2.next\n elif curr1:\n curr_new.next = ListNode(curr1.val)\n curr1 = curr1.next\n else:\n curr_new.next = ListNode(curr2.val)\n curr2 = curr2.next\n curr_new = curr_new.next\n return head.next","sub_path":"lc/esy/20190928_esy_21_merge_two_sorted_linked_list.py","file_name":"20190928_esy_21_merge_two_sorted_linked_list.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"410896373","text":"#####################################################################\n#@ calculatrice\n#@ 01/02/2017\n#@ SC\n#####################################################################\n#Module import\nfrom Tkinter import * #import Tkinter\n\n#Function and variable creation\ndef print_result(): #function calc\n result = eval(str(entree1.get()) + operator.get() + str(entree2.get()))\n #.get() return value for given key with tkinter form\n print (result)\n #print result\n\n#Body Script\n\n#title\ncalc= Tk() #begenning of the GUI\ncalc.title('Calculatrice') # name of the window\n\n#label's prompt form\nLabel(calc, text=\"Entrez le nombre 1 : \").grid(row=0)\nLabel(calc, text=\"Entrez l'operateur + - * ou / : \").grid(row=1)\nLabel(calc, text=\"Entrez le nombre 2 : \").grid(row=2)\nLabel(calc, text=\"Resultat : \").grid(row=3)\n\n#prompt form\nentree1 = Entry(calc)\noperator = Entry(calc)\nentree2 = Entry(calc)\n\n#result showing box\n#result = print_result()\n\n#grid position\nentree1.grid(row=0, column=1)\noperator.grid(row=1, column=1)\nentree2.grid(row=2, column=1)\n#result.grid(row=3, column=1)\n\n#execution button\nButton(calc, text='Executer', command=print_result).grid(row=4, column=0, sticky=W, pady=4)\n#execute button calls print_result function\nButton(calc, text='Quitter', command=calc.destroy).grid(row=4, column=1, sticky=W, pady=4)\n#Quit button calls window closing\n\n#window end\ncalc.mainloop()","sub_path":"calculatorwithGUI.py","file_name":"calculatorwithGUI.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"27270422","text":"import os\nimport tensorflow as tf\n\nclass CupModel:\n def __init__(self, cup_id, restore=199, weight_path='../../data/cups/models'):\n self.build_config(cup_id, restore, os.path.join(os.path.dirname(__file__), weight_path))\n\n def build_config(self, cup_id, restore, weight_path):\n self.float = tf.float32\n self.cup_id = cup_id\n self.num_layers = 8\n self.restore = restore\n self.weight_path = weight_path\n\n def predict(self, x):\n with tf.variable_scope('cup%d'%self.cup_id):\n h = x\n restore_filename = os.path.join(os.path.dirname(__file__), self.weight_path, 'exp_cup_%d__%d.ckpt'%(self.cup_id, self.restore))\n hand_reader = tf.train.NewCheckpointReader(restore_filename)\n for i in range(self.num_layers):\n if i == 0:\n w = tf.Variable(hand_reader.get_tensor('dense/kernel'), trainable=False)\n b = tf.Variable(hand_reader.get_tensor('dense/bias'), trainable=False)\n else:\n w = tf.Variable(hand_reader.get_tensor('dense_%d/kernel'%i), trainable=False)\n b = tf.Variable(hand_reader.get_tensor('dense_%d/bias'%i), trainable=False)\n h = tf.matmul(h, w) + b\n if i < self.num_layers - 1:\n h = tf.nn.relu(h)\n \n g = tf.gradients(h, x)[0]\n # g = g / tf.norm(g, axis=-1, keepdims=True)\n # out = tf.concat([h, g], axis=-1)\n return h, g\n\nif __name__ == \"__main__\":\n import numpy as np\n cm = CupModel(1, 29999, 'reduce_cup_model')\n axis = np.linspace(-0.3, 0.3, 100) * 5\n pts = np.transpose(np.stack(np.meshgrid(axis, axis, axis), axis=-1), [1,0,2,3]).reshape([-1,3])\n tf_pts = tf.constant(pts, dtype=tf.float32)\n tf_out = cm.predict(tf_pts)\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n dist = sess.run(tf_out)[:,0]\n print(pts.shape, dist.shape)\n # dist = grad[:,0]\n # grad = grad[:,1:]\n\n import mayavi.mlab as mlab\n\n mlab.points3d(pts[dist >= 0,0], pts[dist >= 0,1], pts[dist >= 0,2], scale_factor=0.05)\n # mlab.quiver3d(pts[::10,0], pts[::10,1], pts[::10,2], grad[::10,0], grad[::10,1], grad[::10,2])\n\n mlab.show()\n\n # import matplotlib.pyplot as plt\n # from mpl_toolkits.mplot3d import Axes3D\n\n # ax = plt.subplot(111, projection='3d')\n # ax.scatter(pts[:,0], pts[:,1], pts[:,2], s=1, c=grad)\n # plt.show()","sub_path":"coop.v2/utils/CupModel.py","file_name":"CupModel.py","file_ext":"py","file_size_in_byte":2489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"305256003","text":"#dictionary\r\n#여러 값을 저장해두고 필요한 값을 꺼내 쓰는 기능\r\n#이름표를 이용하여 값을 꺼내 사용\r\n# 딕셔너리명={\r\n# '이름표1':'값1'\r\n# '이름표2':'값2'\r\n# }\r\n\r\nwintable = {\r\n '가위' : '보',\r\n '바위' : '가위',\r\n '보' : '바위',\r\n}\r\n\r\nprint(wintable['가위'])\r\n\r\ndays_in_month = {\r\n #여기에 코드를 완성해 보세요.\r\n '1월' : 31,\r\n '2월' : 28,\r\n '3월' : 31,\r\n \r\n \r\n }\r\n\r\nprint(days_in_month)\r\n\r\n\r\n#↓ 이름표는 문자열 또는 숫자를 주로 사용하지만\r\ndict = { \"이름표\" : [1,2,3] }\r\n#↑ 값은 리스트를 포함해서 무엇이든 올 수 있습니다.\r\n\r\nprint( dict[\"이름표\"] )\r\n\r\n\r\nlist=[1,2,3,4]\r\nlist.append(4) #리스트 추가 \r\nprint(list)\r\nlist[4]=6 #리스트 수정\r\nprint(list)\r\ndel(list[4]) #리스트 삭제\r\nprint(list)\r\nprint(list.pop(3))# 리스트 값 삭제하면서 삭제한 값 리턴 후 출력 pop함수 이용\r\ndec={\r\n'a':1,\r\n'b':2,\r\n'c':3,\r\n\r\n}\r\ndec['d']=4 #딕셔너리 추가 \r\nprint(dec)\r\ndec['d']=5 #딕셔너리 수정\r\nprint(dec)\r\ndel(dec['d']) #딕셔너리 삭제\r\nprint(dec)\r\nprint(dec.pop('c')) # 딕셔너리 삭제하면서 삭제한 값 리턴 후 출력 pop함수 이용\r\n\r\n#이름표=key , 값=value\r\n\r\nages={\r\n 'a':12,\r\n 'b':13,\r\n 'c':14,\r\n}\r\n\r\nfor key in ages.keys(): # keys()=이름표 출력, keys()함수 생략할 경우 이름표 출력으로 나옴 \r\n print(key)\r\nfor value in ages.values(): # values()=값 출력\r\n print(value)\r\n\r\n #딕셔너리 반복문은 순서에 맞게 출력하지 않는다\r\n\r\nfor key,value in ages.items(): #items()=딕셔너리에서 두개의 값(이름표,값)을 넘겨줌 \r\n print(\"{}의 나이는 {}살\".format(key,value))\r\n\r\nages2={\r\n\r\n 'f':4,\r\n}\r\n\r\nages.update( ages2 ) #딕셔너리 결합 ages2를 ages에 결합\r\n\r\nprint(ages)\r\n\r\nages2.clear() #딕셔너리의 내용 모두 삭제\r\n\r\n#튜플 \r\n#한번 정해진 순서를 바꿀 수 없다\r\n#값 변경도 불가능하다\r\ntuple1 = (1, 2, 3, 4)\r\n\r\ntuple2 = 1, 2, 3, 4 #() 안써도 똑같이 적용 \r\n \r\nmylist = [1,2,3,4]\r\ntuple3 = tuple(mylist) #튜플안에 리스트의 값들을 넣는다.\r\n\r\n#packing 하나의 변수에 튜플을 이용하여 여러개의 값을 넣는 것\r\n#unpacking 패킹된 변수에서 여러개의 값을 꺼내오는 것\r\n\r\nc = (3, 4)\r\nd, e = c # c의 값을 언패킹하여 d, e에 값을 넣었다\r\nf = d, e # 변수 d와 e를 f에 패킹\r\n\r\n#튜플의 활용\r\n#두 변수의 값을 바꿀 때 임시변수가 필요 없다.\r\n#함수의 리턴 값으로 여러 값을 전달할 수 있다\r\n# ex) x,y=y,x\r\n\r\nlist3=[1,2,3,4,5]\r\nfor i,v in enumerate(list3): # 인덱스(0번째....)와 값을 리턴 \r\n print('{}번째 수 {}'.format(i,v))\r\n\r\nfor a in enumerate(list3): # 인덱스(0번째....)와 값을 리턴 \r\n print('{}번째 수 {}'.format(a[0],a[1]))\r\n#for문을 거칠때마다 a는 (0,1) -> (1,2) -> (2,3) -> (3,4) -> (4,5)로 바뀝니다.\r\n#따라서 a[0]은 0->1->2->3->4가 될거고, a[1]은 1->2->3->4->5가 되겠지요.\r\n\r\n\r\n\r\nfor a in enumerate(list3): # 인덱스(0번째....)와 값을 리턴 \r\n print('{}번째 수 {}'.format(*a) ) #튜플을 쪼갬 \r\n\r\ndic2={\r\n 'a':10,\r\n 'b':11,\r\n 'c':12\r\n}\r\nfor key,value in dic2.items():\r\n print('{}의 나이는 {}살'.format(key,value))\r\nfor a in dic2.items():\r\n print('{}의 나이는 {}살'.format(a[0],a[1]))\r\n","sub_path":"dic.py","file_name":"dic.py","file_ext":"py","file_size_in_byte":3436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"487704964","text":"import torch\r\nimport numpy as np\r\nimport torch.nn.functional as F\r\n\r\ndef resize_label(labels, w1, h1, w2, h2):\r\n labs = []\r\n for label in labels:\r\n labs.append(np.array([label[0]*w2/w1, label[1]*h2/h1, label[2]*w2/w1, label[3]*h2/h1, 1]))\r\n return labs\r\n\r\n\r\n\r\ndef pyramidAnchors(size):\r\n priors = []\r\n\r\n stride = [4, 8, 16, 32, 64, 128]\r\n anchor = [16, 32, 64, 128, 256, 512]\r\n\r\n for k in range(len(stride)):\r\n fs = int(size/stride[k])\r\n prior = []\r\n for i in range(fs):\r\n for j in range(fs):\r\n x = float(stride[k]*(i+0.5))\r\n y = float(stride[k]*(j+0.5))\r\n w = float(anchor[k])\r\n h = float(anchor[k])\r\n prior.append([x, y, w, h])\r\n priors.extend(prior)\r\n\r\n return priors\r\n\r\n\r\ndef rescale_targets(spa, k, targets):\r\n targets[:, 2:] = targets[:, 2:]/(spa**k)\r\n\r\n\r\ndef point_form(boxes):\r\n return torch.cat((boxes[:, :2] - boxes[:, 2:]/2, # xmin, ymin\r\n boxes[:, :2] + boxes[:, 2:]/2), 1) # xmax, ymax\r\n\r\n\r\ndef center_size(boxes):\r\n return torch.cat((boxes[:, 2:] + boxes[:, :2])/2, # cx, cy\r\n boxes[:, 2:] - boxes[:, :2], 1) # w, h\r\n\r\n\r\ndef intersect(box_a, box_b):\r\n A = box_a.size(0)\r\n B = box_b.size(0)\r\n max_xy = torch.min(box_a[:, 2:].unsqueeze(1).expand(A, B, 2),\r\n box_b[:, 2:].unsqueeze(0).expand(A, B, 2))\r\n min_xy = torch.max(box_a[:, :2].unsqueeze(1).expand(A, B, 2),\r\n box_b[:, :2].unsqueeze(0).expand(A, B, 2))\r\n inter = torch.clamp((max_xy - min_xy), min=0)\r\n return inter[:, :, 0] * inter[:, :, 1]\r\n\r\n\r\ndef jaccard(box_a, box_b):\r\n inter = intersect(box_a, box_b)\r\n area_a = ((box_a[:, 2]-box_a[:, 0]) *\r\n (box_a[:, 3]-box_a[:, 1])).unsqueeze(1).expand_as(inter) # [A,B]\r\n area_b = ((box_b[:, 2]-box_b[:, 0]) *\r\n (box_b[:, 3]-box_b[:, 1])).unsqueeze(0).expand_as(inter) # [A,B]\r\n union = area_a + area_b - inter\r\n return inter / union # [A,B]\r\n\r\n\r\ndef match(spa, k, anchor, threshold, targets, priors, conf_t, loc_t, idx, device):\r\n rescale_targets(spa, k, targets)\r\n\r\n ps_conf = [0]*len(priors)\r\n ps_loc = [0]*len(priors)\r\n\r\n for i in range(len(priors)):\r\n ps_conf[i] = torch.Tensor(len(priors[i])).zero_().to(device)\r\n ps_loc[i] = torch.Tensor(len(priors[i]), 4).zero_().to(device)\r\n\r\n ind = 0\r\n dist = float('inf')\r\n\r\n for target in targets:\r\n for i in range(len(anchor)):\r\n if (abs((0.5*target[2]+0.5*target[3])-anchor[i])) < dist:\r\n dist = abs((0.5*target[2]+0.5*target[3])-anchor[i])\r\n ind = i\r\n dist = float('inf')\r\n\r\n overlaps = jaccard(point_form(target.unsqueeze(0)),\r\n point_form(torch.Tensor(priors[ind]).to(device))) # [1,k]\r\n overlaps = overlaps.gt(threshold).squeeze(0).float()\r\n\r\n ps_conf[ind] = ((ps_conf[ind]+overlaps).gt(0)).float()\r\n\r\n\r\n indice = overlaps.nonzero()\r\n\r\n if indice.size(0) == 0:\r\n continue\r\n\r\n cord = target.unsqueeze(0).expand(indice.size(0), 4)\r\n ps_loc[ind].index_copy_(0, indice.squeeze(1), cord) # not correct\r\n\r\n conf = ps_conf[0]\r\n matched = ps_loc[0]\r\n prs = torch.Tensor(priors[0]).to(device)\r\n\r\n for i in range(1, len(priors)):\r\n conf = torch.cat((conf, ps_conf[i]), 0)\r\n matched = torch.cat((matched, ps_loc[i]), 0)\r\n prs = torch.cat((prs, torch.Tensor(priors[i]).to(device)), 0)\r\n\r\n loc = encode(matched, prs)\r\n\r\n conf_t[idx] = conf\r\n loc_t[idx] = loc\r\n\r\n\r\ndef encode(matched, priors):\r\n\r\n # dist b/t match center and prior's center\r\n g_cxcy = (matched[:, :2] + matched[:, 2:])/2 - priors[:, :2]\r\n # encode variance\r\n g_cxcy /= priors[:, 2:]\r\n # match wh / prior wh\r\n g_wh = (matched[:, 2:] - matched[:, :2]) / priors[:, 2:]\r\n g_wh = torch.log(g_wh)\r\n # return target for smooth_l1_loss\r\n return torch.cat([g_cxcy, g_wh], 1) # [num_priors,4]\r\n\r\n\r\n# Adapted from https://github.com/Hakuyume/chainer-ssd\r\ndef decode(loc, priors):\r\n\r\n boxes = torch.cat((\r\n priors[:, :2] + loc[:, :2] * priors[:, 2:],\r\n priors[:, 2:] * torch.exp(loc[:, 2:])), 1)\r\n boxes[:, :2] -= boxes[:, 2:] / 2\r\n boxes[:, 2:] += boxes[:, :2]\r\n return boxes\r\n\r\n\r\n\r\ndef log_sum_exp(x):\r\n \"\"\"Utility function for computing log_sum_exp while determining\r\n This will be used to determine unaveraged confidence loss across\r\n all examples in a batch.\r\n Args:\r\n x (Variable(tensor)): conf_preds from conf layers\r\n \"\"\"\r\n x_max = x.max()\r\n\r\n x = torch.log(torch.sum(torch.exp(x-x_max))) + x_max\r\n #x = F.log_softmax(x, dim=1)\r\n\r\n return x\r\n\r\n\r\ndef nms(boxes, scores, overlap=0.5, top_k=200):\r\n \"\"\"Apply non-maximum suppression at test time to avoid detecting too many\r\n overlapping bounding boxes for a given object.\r\n Args:\r\n boxes: (tensor) The location preds for the img, Shape: [num_priors,4].\r\n scores: (tensor) The class predscores for the img, Shape:[num_priors].\r\n overlap: (float) The overlap thresh for suppressing unnecessary boxes.\r\n top_k: (int) The Maximum number of box preds to consider.\r\n Return:\r\n The indices of the kept boxes with respect to num_priors.\r\n \"\"\"\r\n\r\n keep = scores.new(scores.size(0)).zero_().long()\r\n if boxes.numel() == 0:\r\n return keep\r\n x1 = boxes[:, 0]\r\n y1 = boxes[:, 1]\r\n x2 = boxes[:, 2]\r\n y2 = boxes[:, 3]\r\n area = torch.mul(x2 - x1, y2 - y1)\r\n v, idx = scores.sort(0) # sort in ascending order\r\n # I = I[v >= 0.01]\r\n idx = idx[-top_k:] # indices of the top-k largest vals\r\n xx1 = boxes.new()\r\n yy1 = boxes.new()\r\n xx2 = boxes.new()\r\n yy2 = boxes.new()\r\n w = boxes.new()\r\n h = boxes.new()\r\n\r\n # keep = torch.Tensor()\r\n count = 0\r\n while idx.numel() > 0:\r\n i = idx[-1] # index of current largest val\r\n # keep.append(i)\r\n keep[count] = i\r\n count += 1\r\n if idx.size(0) == 1:\r\n break\r\n idx = idx[:-1] # remove kept element from view\r\n # load bboxes of next highest vals\r\n torch.index_select(x1, 0, idx, out=xx1)\r\n torch.index_select(y1, 0, idx, out=yy1)\r\n torch.index_select(x2, 0, idx, out=xx2)\r\n torch.index_select(y2, 0, idx, out=yy2)\r\n # store element-wise max with next highest score\r\n xx1 = torch.clamp(xx1, min=x1[i])\r\n yy1 = torch.clamp(yy1, min=y1[i])\r\n xx2 = torch.clamp(xx2, max=x2[i])\r\n yy2 = torch.clamp(yy2, max=y2[i])\r\n w.resize_as_(xx2)\r\n h.resize_as_(yy2)\r\n w = xx2 - xx1\r\n h = yy2 - yy1\r\n # check sizes of xx1 and xx2.. after each iteration\r\n w = torch.clamp(w, min=0.0)\r\n h = torch.clamp(h, min=0.0)\r\n inter = w*h\r\n # IoU = i / (area(a) + area(b) - i)\r\n rem_areas = torch.index_select(area, 0, idx) # load remaining areas)\r\n union = (rem_areas - inter) + area[i]\r\n IoU = inter/union # store result in iou\r\n # keep only elements with an IoU <= overlap\r\n idx = idx[IoU.le(overlap)]\r\n\r\n return keep, count\r\n\r\n\r\n\r\ndef match_temp(threshold, truths, priors, labels, loc_t, conf_t, idx, device):\r\n \"\"\"Match each prior box with the ground truth box of the highest jaccard\r\n overlap, encode the bounding boxes, then return the matched indices\r\n corresponding to both confidence and location preds.\r\n Args:\r\n threshold: (float) The overlap threshold used when mathing boxes.\r\n truths: (tensor) Ground truth boxes, Shape: [num_obj, num_priors].\r\n priors: (tensor) Prior boxes from priorbox layers, Shape: [n_priors,4].\r\n variances: (tensor) Variances corresponding to each prior coord,\r\n Shape: [num_priors, 4].\r\n labels: (tensor) All the class labels for the image, Shape: [num_obj].\r\n loc_t: (tensor) Tensor to be filled w/ endcoded location targets.\r\n conf_t: (tensor) Tensor to be filled w/ matched indices for conf preds.\r\n idx: (int) current batch index\r\n Return:\r\n The matched indices corresponding to 1)location and 2)confidence preds.\r\n \"\"\"\r\n # jaccard index\r\n '''\r\n overlaps = jaccard(\r\n truths,\r\n point_form(priors)\r\n )\r\n '''\r\n\r\n overlaps = jaccard(truths, point_form(torch.Tensor(priors).to(device)))\r\n\r\n # (Bipartite Matching)\r\n # [1,num_objects] best prior for each ground truth\r\n best_prior_overlap, best_prior_idx = overlaps.max(1, keepdim=True)\r\n # [1,num_priors] best ground truth for each prior\r\n best_truth_overlap, best_truth_idx = overlaps.max(0, keepdim=True)\r\n best_truth_idx.squeeze_(0)\r\n best_truth_overlap.squeeze_(0)\r\n best_prior_idx.squeeze_(1)\r\n best_prior_overlap.squeeze_(1)\r\n best_truth_overlap.index_fill_(0, best_prior_idx, 2) # ensure best prior\r\n # TODO refactor: index best_prior_idx with long tensor\r\n # ensure every gt matches with its prior of max overlap\r\n for j in range(best_prior_idx.size(0)):\r\n best_truth_idx[best_prior_idx[j]] = j\r\n matches = truths[best_truth_idx] # Shape: [num_priors,4]\r\n conf = labels[best_truth_idx] # Shape: [num_priors]\r\n conf[best_truth_overlap < threshold] = 0 # label as background\r\n loc = encode(matches, torch.Tensor(priors).to(device))\r\n loc_t[idx] = loc # [num_priors,4] encoded offsets to learn\r\n conf_t[idx] = conf # [num_priors] top class label for each prior\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"460686482","text":"#!/usr/bin/python2.7\n#coding:utf-8\n\n#minimize cost tf optimizer\n#1\nimport tensorflow as tf\ntf.set_random_seed(777)\n\nX=[1,2,3]\nY=[2,4,6]\n\n# W=tf.Variable(-3.0,name='weight')\n#\n# hypothesis=X*W\n# loss=tf.reduce_mean(tf.square(hypothesis-Y))\n#\n#\n# #minimize\n# optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.1)\n# train=optimizer.minimize(loss)\n#\n# #prepare session,initialize\n# sess=tf.Session()\n# sess.run(tf.global_variables_initializer()) #variables initialize\n#\n#\n# for step in range(100):\n# sess.run(train)\n# print(step,sess.run(W))\n\n#2 cost_tf_gradient\n\nW=tf.Variable(5.)\nhypothesis=X*W\ngradient=tf.reduce_mean((W*X-Y)*X)*2 #??the gradient\nloss=tf.reduce_mean(tf.square(hypothesis-Y))\n\n#minimize\noptimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01)\ntrain=optimizer.minimize(loss)\n\n#get gradients\ngvs=optimizer.compute_gradients(loss,[W]) #计算loss的梯度,返回的是梯度和变量W的列表\n\napply_gradients=optimizer.apply_gradients(gvs) #apply gvs\n\n#prepare session\nsess=tf.Session()\nsess.run(tf.global_variables_initializer())\n\n\n#fit the line\n\nfor step in range(1000):\n sess.run(train)\n print(step,sess.run([gradient,W,gvs]))\n\n\n\n","sub_path":"t0024_minimize_cost_tf_optimizer.py","file_name":"t0024_minimize_cost_tf_optimizer.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"250363940","text":"\"\"\"\nUsing names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.\n\nFor example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 ? 53 = 49714.\n\nWhat is the total of all the name scores in the file?\n\"\"\"\nalphabet = \" ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nalphabet = list(alphabet)\ntotal = 0\n\nwith open('d:\\coding\\Python\\Euler\\p022_names.txt') as f:\n names = f.readline()\nf.close()\n\nnames = names.replace('\\\",\\\"', ' ')\nnames = names.replace('\\\"', '')\nnames = names.split()\nnames = sorted(names)\nnames.insert(0, \" \")\n\nfor x in names:\n number = names.index(x)\n sum = 0\n x = list(x)\n for x in x:\n sum += alphabet.index(x)\n total += sum * number\n\nprint(total)\n","sub_path":"22.py","file_name":"22.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"84379925","text":"#_*_ coding: utf8 _*_\nfrom styles.menu_categories_style import MenuCategoryEsthetic as Style\nimport styles.styles_utils as su\nfrom database.categories import Category\n\n\nclass MenuCategory:\n\n def run(self):\n\n while True:\n option = Style().options()\n\n if option['option'] == Style().option_1: # Read/Leer\n Category().read_categories()\n\n elif option['option'] == Style().option_2: # Create/Crear\n new_category = input(Style.new_category)\n Category().create_category(new_category)\n \n Category().read_categories()\n print(\" ↑\")\n\n elif option['option'] == Style().option_3: # Update/Actualizar\n Category().read_categories()\n\n current_category_id = input(Style.current_category_id)\n new_category_name = input(Style.new_category_name)\n Category().update_category(current_category_id, new_category_name)\n\n elif option['option'] == Style().option_4: # Delete/Eliminar\n Category().read_categories()\n\n category_id = input(Style.category_id)\n Category().delete_category(category_id)\n\n elif option['option'] == Style().option_5: # Volver al menu principal\n su.beep(times=2)\n break\n\n su.waiting_user()\n\nif __name__ == '__main__':\n MenuCategory().run()","sub_path":"ProgramaBiblioteca/menu_categories.py","file_name":"menu_categories.py","file_ext":"py","file_size_in_byte":1463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"342543317","text":"# python3\r\n# Given a positive integer num, write a function which returns True if num is a perfect square else False.\r\n\r\n# Note: Do not use any built-in library function such as sqrt.\r\n\r\n# Example 1:\r\n\r\n# Input: 16\r\n# Returns: True\r\n# Example 2:\r\n\r\n# Input: 14\r\n# Returns: False\r\n\r\n\r\n# Use Newton's Method\r\nclass Solution(object):\r\n def isPerfectSquare(self, num):\r\n \"\"\"\r\n :type num: int\r\n :rtype: bool\r\n \"\"\"\r\n i = num\r\n while i*i >= num:\r\n if i*i == num:\r\n return True\r\n i = (i + num/i) / 2\r\n return False\r\n","sub_path":"valid_perfect_square.py","file_name":"valid_perfect_square.py","file_ext":"py","file_size_in_byte":597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"149764662","text":"import re\nimport logging\nimport pendulum\nfrom django.conf import settings\nfrom jnpr import junos\n\nlogger = logging.getLogger(__name__)\n\n\ndef netconf_exception_handler(default=None):\n def decorator(func):\n def inner_function(*args, **kwargs):\n device = args[0].device\n try:\n return func(*args, **kwargs)\n except junos.exception.RpcError as e:\n logger.warning(f\"{e} (host: {device.ip_address}, pk: {device.pk})\")\n return default\n\n return inner_function\n\n return decorator\n\n\nclass NetconfSession(junos.Device):\n def __init__(self, device):\n self.device = device\n super().__init__(\n host=device.ip_address,\n user=settings.NETCONF_USER,\n passwd=settings.NETCONF_PASSWORD,\n port=settings.NETCONF_PORT,\n normalize=True,\n )\n\n @netconf_exception_handler()\n def get_name(self):\n return self.facts[\"hostname\"]\n\n @netconf_exception_handler()\n def get_model(self):\n return self.facts[\"model\"]\n\n @netconf_exception_handler()\n def get_junos_version(self):\n return self.facts[\"version\"]\n\n @netconf_exception_handler()\n def get_chassis_id(self):\n lldp_local = self.rpc.get_lldp_local_info()\n return lldp_local.findtext(\"lldp-local-chassis-id\")\n\n @netconf_exception_handler()\n def get_interface(self, interface_name):\n interface_info = self.rpc.get_interface_information(interface_name=interface_name)\n interface_speed = interface_info.findtext(\"./physical-interface/speed\")\n interface_number = interface_info.findtext(\"./physical-interface/snmp-index\")\n logical_interfaces = []\n for logical_interface in interface_info.findall(\"./physical-interface/logical-interface\"):\n if logical_interface.findtext(\"./address-family/address-family-name\") == \"inet\":\n logical_interface_name = logical_interface.findtext(\"./name\")\n logical_interface_number = logical_interface.findtext(\"./snmp-index\")\n logical_interface_address = logical_interface.findtext(\"./address-family/interface-address/ifa-local\")\n logical_interfaces.append(\n {\n \"name\": logical_interface_name,\n \"number\": int(logical_interface_number),\n \"address\": logical_interface_address,\n }\n )\n if interface_number:\n return {\n \"name\": interface_name,\n \"number\": int(interface_number),\n \"speed\": self._normalize_speed(interface_speed),\n \"logical_interfaces\": logical_interfaces,\n }\n else:\n logger.error(\n f\"unexpected format of rpc response \" f\"(host: {self.device.ip_address}, pk: {self.device.pk})\"\n )\n\n @netconf_exception_handler(default=set())\n def get_lldp_neighbours(self):\n lldp_neighbours = self.rpc.get_lldp_neighbors_information()\n neighbours = set()\n for neighbour in lldp_neighbours.findall(\"lldp-neighbor-information\"):\n local_interface = neighbour.findtext(\"lldp-local-port-id\")\n if not local_interface:\n local_interface = neighbour.findtext(\"lldp-local-interface\")\n remote_chassis_id = neighbour.findtext(\"lldp-remote-chassis-id\")\n if local_interface and remote_chassis_id:\n neighbours.add((local_interface, remote_chassis_id))\n return neighbours\n\n @netconf_exception_handler(default=[])\n def get_lldp_neighbour_details(self, interface):\n lldp_neighbours = self.rpc.get_lldp_interface_neighbors(interface_device=interface)\n neighbour_details = []\n for neighbour in lldp_neighbours.findall(\"lldp-neighbor-information\"):\n local_interface = neighbour.findtext(\"lldp-local-interface\")\n parent_interface = neighbour.findtext(\"lldp-local-parent-interface-name\")\n remote_chassis_id = neighbour.findtext(\"lldp-remote-chassis-id\")\n remote_interface_id = neighbour.findtext(\"lldp-remote-port-id\")\n remote_interface_id_subtype = neighbour.findtext(\"lldp-remote-port-id-subtype\")\n neighbour_details.append(\n {\n \"local_interface\": local_interface,\n \"parent_interface\": None if parent_interface == \"-\" else parent_interface,\n \"remote_chassis_id\": remote_chassis_id,\n \"remote_interface\": remote_interface_id,\n \"is_remote_interface_id_number\": remote_interface_id_subtype == \"Locally assigned\",\n }\n )\n return neighbour_details\n\n @netconf_exception_handler(default=[])\n def get_chassis_alarms(self):\n alarm_information = self.rpc.get_alarm_information()\n return self._parse_alarms(alarm_information)\n\n @netconf_exception_handler(default=[])\n def get_system_alarms(self):\n alarm_information = self.rpc.get_system_alarm_information()\n return self._parse_alarms(alarm_information)\n\n @netconf_exception_handler(default=[])\n def get_ingress_lsp_rsvp_path(self):\n lsp = self.rpc.get_mpls_lsp_information(detail=True, ingress=True)\n lsp_paths = []\n for path in lsp.findall(\"./rsvp-session-data/rsvp-session/mpls-lsp\"):\n name = path.findtext(\"name\")\n source = path.findtext(\"source-address\")\n destination = path.findtext(\"destination-address\")\n received_rro = path.findtext(\"mpls-lsp-path/received-rro\")\n lsp_paths.append(\n {\n \"name\": name,\n \"source\": source,\n \"destination\": destination,\n \"received_rro\": received_rro,\n }\n )\n return lsp_paths\n\n @netconf_exception_handler(default=[])\n def get_ldp_traceroute_paths(self, destination_address):\n ldp = self.rpc.traceroute_mpls_ldp(fec=destination_address)\n ldp_paths = []\n current_path = []\n for path in ldp.findall(\"./tracelsp-node\"):\n address = path.findtext(\"address\")\n current_path.append(address)\n if path.find(\"output\") is not None:\n index = path.findtext(\"path-index\")\n interface = path.findtext(\"interface\")\n ldp_paths.append(\n {\n \"index\": index,\n \"interface\": interface,\n \"path\": current_path,\n }\n )\n current_path = []\n return ldp_paths\n\n @netconf_exception_handler(default=[])\n def get_traceroute(self, destination_address):\n route = []\n traceroute_details = self.rpc.traceroute(host=destination_address)\n if traceroute_details.find(\"traceroute-success\") is not None:\n for hop in traceroute_details.findall(\"./hop\"):\n address = hop.findtext(\"last-ip-address\")\n route.append(address)\n return route\n\n def _parse_alarms(self, alarm_information):\n alarms = []\n for alarm in alarm_information.findall(\"alarm-detail\"):\n time = alarm.findtext(\"alarm-time\").replace(\" CEST\", \" Etc/GMT-2\")\n alarm_class = alarm.findtext(\"alarm-class\")\n description = alarm.findtext(\"alarm-description\")\n try:\n alarms.append(\n {\n \"time\": pendulum.from_format(time, \"YYYY-MM-DD HH:mm:ss z\"),\n \"alarm_class\": alarm_class,\n \"description\": description,\n }\n )\n except ValueError:\n logger.error(\n f\"unexpected format of time: {time}\" f\"(host: {self.device.ip_address}, pk: {self.device.pk})\"\n )\n return alarms\n\n def _normalize_speed(self, speed):\n if not speed or speed == \"Unspecified\" or speed == \"Unlimited\":\n return 0\n r = re.compile(\"([0-9]+)([a-zA-Z]+)\")\n split = r.match(speed)\n if not split:\n logger.error(\n f\"unexpected format of speed: {speed}\" f\"(host: {self.device.ip_address}, pk: {self.device.pk})\"\n )\n return 0\n speed_value = int(split.group(1))\n speed_unit = split.group(2)\n if speed_unit == \"mbps\":\n return speed_value / 1000\n elif speed_unit == \"Gbps\":\n return speed_value\n","sub_path":"router-map/data/collector/netconf_session.py","file_name":"netconf_session.py","file_ext":"py","file_size_in_byte":8664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"329552322","text":"from argparse import ArgumentParser\n\n\ndef get_option(question=\"長所\", wordsLength=300):\n argparser = ArgumentParser()\n argparser.add_argument('-q', '--question', type=str,\n default=question,\n help='Specify keyword of question')\n argparser.add_argument('-l', '--length', type=int,\n default=wordsLength,\n help='Specify length of output words')\n return argparser.parse_args()","sub_path":"src/Luhn/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"389860173","text":"import csv\n\ndef method1():\n with open('data.csv') as file:\n reader = csv.reader(file, delimiter=',')\n\n for row in reader:\n print(row)\n\ndef method2():\n with open('data.csv') as file:\n # For DictReader to work the header column should be available in the file\n reader = csv.DictReader(file, delimiter=',')\n\n for row in reader:\n print(row['country'])\n\nmethod2()\n","sub_path":"12_Python_CSV_Read_Write/read_csv.py","file_name":"read_csv.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"361983043","text":"# Hot seat \"game\" of rock-paper-scissors.\n\nplay_again = True\n\nwhile(play_again is True):\n p1_input = input(\"Player 1, please input rock, paper or scissors: \")\n p2_input = input(\"Player 2, please input rock, paper or scissors: \")\n\n if p1_input == \"rock\" and p2_input == \"scissors\" or p1_input == \"scissors\" and p2_input == \"paper\" or p1_input == \"paper\" and p2_input == \"rock\":\n winner = \"Player 1\"\n elif p2_input == \"rock\" and p1_input == \"scissors\" or p2_input == \"scissors\" and p1_input == \"paper\" or p2_input == \"paper\" and p1_input == \"rock\":\n winner = \"Player 2\"\n elif p1_input == \"rock\" and p2_input == \"rock\" or p1_input == \"scissors\" and p2_input == \"scissors\" or p1_input == \"paper\" and p2_input == \"paper\":\n winner = \"Nobody\"\n\n print(\"The winner is \" + winner + \".\")\n\n\n play_again = input(\"Do you wish to play again y/n?\")\n\n\n if play_again is \"y\":\n play_again = True\n elif play_again is \"n\":\n break","sub_path":"rock_paper_scissors.py","file_name":"rock_paper_scissors.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"81962982","text":"# https://www.interviewbit.com/problems/stocks2/\n\nclass Solution:\n # @param A : tuple of integers\n # @return an integer\n # [10, 7, 5, 8, 11, 9] \n def maxProfit(self, stock_prices):\n \n if not stock_prices:\n return 0\n \n sum_ = 0\n prev_price = stock_prices[0]\n for price in stock_prices[1:]:\n \n sum_ += max(0, price - prev_price)\n prev_price = price\n \n return sum_\n","sub_path":"interviewbit.com/Dynamic Programming/best_time_to_buy_and_sell_stocks_II.py","file_name":"best_time_to_buy_and_sell_stocks_II.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"575736597","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Maziar Raissi\n\"\"\"\n\nimport autograd.numpy as np\nimport matplotlib.pyplot as plt\nfrom RecurrentNeuralNetworks import RecurrentNeuralNetworks\nfrom Utilities import create_dataset\n\nnp.random.seed(1234)\n \nif __name__ == \"__main__\":\n \n # generate the dataset\n def f(x):\n return np.sin(np.pi*x)\n \n dataset = f(np.arange(0,10,0.1)[:,None])\n \n # Training Data\n train_size = int(len(dataset) * (2/3))\n train = dataset[0:train_size,:]\n \n # reshape X and Y\n # X has the form lags x data x dim\n # Y has the form data x dim\n lags = 5\n X, Y = create_dataset(train, lags)\n \n # Model creation\n hidden_dim = 4\n model = RecurrentNeuralNetworks(X, Y, hidden_dim, \n max_iter = 10000, N_batch = 1, \n monitor_likelihood = 10, lrate = 1e-3) \n \n model.train()\n \n # Prediction\n pred = np.zeros((len(dataset)-lags, Y.shape[-1]))\n X_tmp = np.copy(X[:,0:1,:])\n for i in range(0, len(dataset)-lags):\n pred[i] = model.forward_pass(X_tmp, model.hyp)\n X_tmp[:-1,:,:] = X_tmp[1:,:,:] \n X_tmp[-1,:,:] = pred[i]\n \n plt.figure(1)\n plt.rcParams.update({'font.size': 14})\n plt.plot(dataset[lags:], 'b-', linewidth = 2, label = \"Exact\")\n plt.plot(pred, 'r--', linewidth = 3, label = \"Prediction\")\n plt.plot(X.shape[1]*np.ones((2,1)), np.linspace(-1.75,1.75,2), 'k--', linewidth=2)\n plt.axis('tight')\n plt.xlabel('$t$')\n plt.ylabel('$y_t$')\n plt.legend(loc='lower left')\n \n plt.savefig('Example_RNN.eps', format='eps', dpi=1000)","sub_path":"RecurrentNeuralNetworks/Example.py","file_name":"Example.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"9844496","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api\nfrom odoo.exceptions import UserError\n\n\nclass ArkcoSalesIncentive(models.Model):\n _name = 'sales.incentive'\n\n name = fields.Char(string='Name')\n @api.model\n def _get_default_team(self):\n return self.env['crm.team']._get_default_team_id()\n\n team_id = fields.Many2one('crm.team', 'Sales Team', change_default=True, default=_get_default_team)\n target_group_id = fields.Many2one('target.group', 'Target Group', change_default=True)\n incentive_amount = fields.Float(string='Incentive Amount', compute=\"_get_incentive_amount\", store=True)\n\n state = fields.Selection([\n ('draft', 'Draft'),\n ('pending', 'Pending'),\n ('accepted', 'Accepted'),\n ('rejected', 'Rejected'),\n ], string='Status', readonly=True, index=True, copy=False, default='draft', track_visibility='onchange')\n status_target = fields.Char(string='Status Target', compute=\"_get_incentive_amount\")\n incentive_line = fields.One2many('sales.incentive.line', 'incentive_id', copy=True)\n\n @api.multi\n def action_button_confirm(self):\n for rec in self:\n \t rec.write({'state': 'pending'})\n\n @api.multi\n def action_button_cancel(self):\n for rec in self:\n rec.write({'state': 'cancel'})\n\n @api.onchange('team_id')\n def get_sales_executive(self):\n if self.team_id:\n # import pdb; pdb.set_trace()\n r = []\n for person in self.team_id.member_ids:\n r.append({'user_id':person.id})\n self.update({'incentive_line':r})\n\n\n @api.multi\n @api.depends('team_id', 'target_group_id','incentive_line.incentive')\n def _get_incentive_amount(self):\n for rec in self:\n if rec.team_id:\n # import pdb; pdb.set_trace()\n total_sale = 0\n sale_ids = self.env['sale.order'].search([('team_id','=',rec.team_id.id),('state','=','sale')])\n\n for sale in sale_ids:\n total_sale += sale.amount_untaxed\n price_list = []\n\n for line in rec.target_group_id.target_lines:\n price_list.append(line.max_target)\n price_list.append(line.min_target)\n\n if price_list:\n for line in rec.target_group_id.target_lines:\n if (total_sale<=line.max_target) and (total_sale>=line.min_target):\n rec.incentive_amount = line.amount\n elif (total_sale>max(price_list)) and (max(price_list)==line.max_target):\n rec.incentive_amount = line.amount\n if total_sale < min(price_list):\n rec.status_target = 'Not Achieved'\n else:\n rec.status_target = 'Achieved'\n for line in rec.incentive_line:\n if (line.incentive>0) and (line.incentive <= rec.incentive_amount):\n rec.incentive_amount -= line.incentive\n\n # if rec.incentive_line.incentive > 0:\n # import pdb; pdb.set_trace()\n # incentive = rec.incentive_line.incentive\n # if rec.incentive_amount > incentive:\n # rec.incentive_amount -= rec.incentive_amount - incentive\n\n\n\nclass ArkcoSalesIncentiveLine(models.Model):\n _name = 'sales.incentive.line'\n \n incentive_id = fields.Many2one('sales.incentive', string='Incentive Reference', \n ondelete='cascade', index=True, copy=False)\n line_team_id = fields.Integer('Sales Team', index=True, related=\"incentive_id.team_id.id\")\n line_status_target = fields.Char('Status Target', index=True, related=\"incentive_id.status_target\")\n user_id = fields.Many2one('res.users', string='Sales Executive', index=True, \n track_visibility='onchange') \n total_sales = fields.Float(string='Total Sales', compute=\"_get_total_sale\", store=True)\n incentive = fields.Float(string='Incentive')\n\n @api.multi\n @api.depends('user_id')\n def _get_total_sale(self):\n for line in self:\n sale_order = self.env['sale.order'].search([('user_id','=',line.user_id.id),('state', '=', 'sale')])\n total_sale_amt = 0.0\n for order in sale_order:\n total_sale_amt += order.amount_untaxed\n line.total_sales = total_sale_amt\n\n @api.multi\n @api.onchange('incentive')\n def check_incentive_amount(self):\n for rec in self:\n if rec.incentive > 0:\n # import pdb; pdb.set_trace()\n total_incentive_amt = rec.incentive_id.incentive_amount\n if rec.incentive > total_incentive_amt:\n record = rec\n raise UserError(\n _(\"Applied incentive %s has been reached its Total Incentive Amount %s.\" %(\n record.incentive, record.incentive_id.incentive_amount)))\n # else:\n # if (rec.incentive > 0) and (total_incentive_amt >= rec.incentive):\n # total_incentive_amt = total_incentive_amt - rec.incentive\n # rec.incentive_id.update({'incentive_amount': total_incentive_amt})\n\n @api.model\n def create(self, vals):\n res = super(ArkcoSalesIncentiveLine, self).create(vals)\n for rec in res:\n if rec.incentive > 0:\n # import pdb; pdb.set_trace()\n total_incentive_amt = rec.incentive_id.incentive_amount\n if rec.incentive > total_incentive_amt:\n raise UserError(\n _(\"Applied incentive %s has been reached its Total Incentive Amount %s.\" %(\n rec.incentive, rec.incentive_id.incentive_amount)))\n else:\n if (rec.incentive > 0) and (total_incentive_amt >= rec.incentive):\n total_incentive_amt = total_incentive_amt - rec.incentive\n rec.incentive_id.incentive_amount = total_incentive_amt\n return res\n\n\n @api.multi\n def write(self, values):\n res = super(ArkcoSalesIncentiveLine, self).write(values)\n for rec in self:\n if 'incentive' in values and (rec.incentive > 0):\n total_incentive_amt = rec.incentive_id.incentive_amount\n if rec.incentive > total_incentive_amt:\n raise UserError(\n _(\"Applied incentive %s has been reached its Total Incentive Amount %s.\" %(\n rec.incentive, rec.incentive_id.incentive_amount)))\n else:\n if (rec.incentive > 0) and (total_incentive_amt >= rec.incentive):\n total_incentive_amt = total_incentive_amt - rec.incentive\n rec.incentive_id.incentive_amount = total_incentive_amt\n return res\n","sub_path":"beta-dev1/arkco_modifier_sales_incentive/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"94020024","text":"from __future__ import annotations \nimport collections \nimport random \nimport heapq \nimport math\nimport bisect\n\n\nclass Solution:\n def minimumCost(self, N: int, conections: List[List[int]]) -> int:\n # greedy \n if len(conections) < N - 1:\n return -1\n if N == 1:\n return 0\n\n res = 0\n pq = []\n for (p1, p2, cost) in conections:\n heapq.heappush(pq, (cost, p1, p2))\n\n avail = set(range(1, N+1))\n\n n = N\n roots = [i for i in range(N)]\n\n # while avail:\n while n != 1:\n if len(pq) == 0:\n # cant reach \n return -1\n cost, p1, p2 = heapq.heappop(pq)\n # if p1 in avail or p2 in avail:\n # # print(cost)\n \n # if p1 in avail:\n # avail.remove(p1)\n # if p2 in avail:\n # avail.remove(p2)\n\n x = find(roots, p1-1)\n y = find(roots, p2-1)\n if x != y:\n roots[x] = y # union \n res += cost\n n -= 1\n # print(x, y, roots)\n\n # print(avail)\n\n # # check \n # n = N\n # roots = [i for i in range(N)]\n # for p1, p2, _ in conections:\n # x = find(roots, p1-1)\n # y = find(roots, p2-1)\n # if x != y:\n # roots[x] = y # union \n # n -= 1\n # print(x, y, roots)\n # if n > 1:\n # return -1\n\n return res \n\n\ndef find(roots, id):\n while roots[id] != id:\n roots[id] = roots[roots[id]]\n id = roots[id]\n return id\n\n\n\ns = Solution()\n\nN = 3\nconections = [[1,2,5],[1,3,6],[2,3,1]]\nprint(s.minimumCost(N, conections))\n\nN = 4\nconections = [[1,2,3],[3,4,4]]\nprint(s.minimumCost(N, conections))\n\nN = 5\nconections = [[1,2,3],[3,4,4], [4,5,4], [3,5,4]]\nprint(s.minimumCost(N, conections))\n\nN = 1\nconections = []\nprint(s.minimumCost(N, conections))\n\n\nN = 7\nconections = [[2,1,87129],[3,1,14707],[4,2,34505],[5,1,71766],[6,5,2615],[7,2,37352]]\nprint(s.minimumCost(N, conections))\n\n# 24xxxx\n","sub_path":"M_5036_minimumCost.py","file_name":"M_5036_minimumCost.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"257832081","text":"\nimport torch\nimport torch.nn as nn\nimport numpy as np\n\ntorch.set_default_tensor_type(torch.FloatTensor)\ntorch.set_default_dtype(torch.float32)\n\n\n\nclass Kernel(nn.Module):\n def __init__(self):\n super(Kernel, self).__init__()\n\n def check_tensortype(self, x1, x2=None):\n if torch.is_tensor(x1) == False:\n x1 = TensorType(x1)\n if x2 is None:\n return x1, x1\n else:\n if torch.is_tensor(x2) == False:\n x2 = TensorType(x2)\n return x1, x2\n\n\n def K(self, x1, x2 = None):\n return NotImplementedError\n\n def K_diag(self, x1, x2=None):\n return torch.diag(self.K(x1, x2))\n\n\n\n\nclass StationaryKernel(Kernel):\n def __init__(self, device ):\n super(StationaryKernel, self).__init__()\n self.kernel_name = None\n self.ARD = False\n self.input_dim = None\n self.device = torch.device(\"cuda\") if device else torch.device('cpu')\n\n\n def _sq_dist(self,x1,x2 = None):\n x1,x2 = self.check_tensortype(x1,x2)\n\n x1_ = x1.pow(2).sum(-1,keepdim = True)\n x2_ = x2.pow(2).sum(-1,keepdim = True)\n\n #sq_dist = x1.matmul(x2.transpose(-2,-1)).mul_(-2).add_(x2_.transpose(-2,-1)).add_(x1_)\n sq_dist = -2*x1.matmul(x2.transpose(-2, -1)) + (x1_ + x2_.transpose(-2, -1))\n sq_dist.clamp_min(1e-16)\n\n return sq_dist\n\n\n\n def K(self, x1, x2 = None):\n return NotImplementedError\n\n\n def K_diag(self, x1, x2=None):\n return torch.diag(self.K(x1, x2))\n\n\n\nclass Sum_kernel(StationaryKernel):\n\n def __init__(self, kernel_list, device):\n super(Sum_kernel, self).__init__(device)\n self.kernel_name = 'SUM'\n self.kernel_list = kernel_list\n self._set_paramlist()\n\n def _set_paramlist(self):\n param_list = []\n for ith_kernel in self.kernel_list:\n for ith_param in ith_kernel.parameters():\n if ith_param.requires_grad:\n param_list.append(ith_param)\n self.param_list = param_list\n return\n\n\n def K(self, x1, x2=None):\n out = 0\n for ith_kernel in self.kernel_list:\n out += ith_kernel.K(x1, x2)\n return out\n\n\n\nclass Product_kernel(StationaryKernel):\n def __init__(self, kernel_list, device):\n super(Product_kernel, self).__init__(device)\n self.kernel_list = kernel_list\n self._set_paramlist()\n\n def _set_paramlist(self):\n param_list = []\n for ith_kernel in self.kernel_list:\n for ith_param in ith_kernel.parameters():\n if ith_param.requires_grad:\n param_list.append(ith_param)\n self.param_list = param_list\n return\n\n def K(self, x1, x2=None):\n out = 1\n for ith_kernel in self.kernel_list:\n out *= ith_kernel.K(x1, x2)\n return out\n","sub_path":"kernels/.ipynb_checkpoints/kernel-checkpoint.py","file_name":"kernel-checkpoint.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"465970064","text":"import sys\n#\n# >>> Escriba el codigo del mapper a partir de este punto <<<\n#\ncurrentk = None\nvsum = 0\nvcount= 0\n\nfor line in sys.stdin:\n line = line.strip()\n k, v = line.split(\"\\t\")\n v = int(v)\n if k == currentk:\n vsum += v\n vcount += 1\n else:\n if currentk is not None:\n print(currentk + \"\\t\" + str(float(vsum)) + \"\\t\" + str(vsum/vcount))\n currentk = k\n vsum = v\n vcount = 1\n \nprint(currentk + \"\\t\" + str(float(vsum)) + \"\\t\" + str(vsum/vcount))","sub_path":"01-hadoop-50/q08-10/reducer.py","file_name":"reducer.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"485198875","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# BEGIN LICENSE\n# Copyright (c) 2014 Jim Kemp \n# Copyright (c) 2017 Gene Liverman \n\n# Permission is hereby granted, free of charge, to any person\n# obtaining a copy of this software and associated documentation\n# files (the \"Software\"), to deal in the Software without\n# restriction, including without limitation the rights to use,\n# copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be\n# included in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n# OTHER DEALINGS IN THE SOFTWARE.\n# END LICENSE\n\n\"\"\" Fetches weather reports from Dark Sky for displaying on a screen. \"\"\"\n\n__version__ = \"0.0.12\"\n\n###############################################################################\n# Raspberry Pi Weather Display\n# Original By: Jim Kemp 10/25/2014\n# Modified By: Gene Liverman 12/30/2017 & multiple times since\n###############################################################################\n\n# local imports\nfrom weather import *\n\n\nclass Daily(Weather):\n def get_daily(self, last_update_time):\n new_last_update_time = self.get_forecast(last_update_time)\n return new_last_update_time\n\n def disp_daily(self, last_update_time):\n # Fill the screen with black\n self.screen.fill((0, 0, 0))\n xmin = 10\n lines = 5\n line_color = (255, 255, 255)\n text_color = (255, 255, 255)\n font_name = \"freesans\"\n\n self.draw_screen_border(line_color, xmin, lines)\n self.disp_time_date(font_name, text_color)\n self.disp_current_temp(font_name, text_color)\n self.disp_summary()\n self.display_conditions_line(\n 'Feels Like:', int(round(self.weather.apparentTemperature)),\n True)\n\n try:\n wind_bearing = self.weather.windBearing\n wind_direction = deg_to_compass(wind_bearing) + ' @ '\n except AttributeError:\n wind_direction = ''\n wind_txt = wind_direction + str(\n int(round(self.weather.windSpeed))) + \\\n ' ' + get_windspeed_abbreviation()\n self.display_conditions_line(\n 'Wind:', wind_txt, False, 1)\n\n self.display_conditions_line(\n 'Humidity:', str(int(round((self.weather.humidity * 100)))) + '%',\n False, 2)\n\n # Skipping multiplier 3 (line 4)\n\n if self.take_umbrella:\n umbrella_txt = 'Grab your umbrella!'\n else:\n umbrella_txt = 'No umbrella needed today.'\n self.disp_umbrella_info(umbrella_txt)\n\n # Today\n today = self.weather.daily[0]\n today_string = \"Today\"\n multiplier = 1\n self.display_subwindow(today, today_string, multiplier)\n\n # counts from 0 to 2\n for future_day in range(3):\n this_day = self.weather.daily[future_day + 1]\n this_day_no = datetime.datetime.fromtimestamp(this_day.time)\n this_day_string = this_day_no.strftime(\"%A\")\n multiplier += 2\n self.display_subwindow(this_day, this_day_string, multiplier)\n\n # Update the display\n pygame.display.update()\n","sub_path":"daily.py","file_name":"daily.py","file_ext":"py","file_size_in_byte":3828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"37776544","text":"from collections import Counter\n#l = ['a', 'a', 'a', 'a', 'b', 'c', 'c']\n#c = Counter(l)\n#print(c) # Counter({'a': 4, 'c': 2, 'b': 1})\n\nN = int(input())\na = list(map(int, input().split()))\n\nC = Counter(a)\n\nans = 0\nfor k, v in C.items():\n k = int(k)\n \n if kv:\n ans += v\n\nprint(ans)","sub_path":"atcoder/2017/ABC/1216_abc082/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"329641639","text":"from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QGridLayout, QComboBox, QProgressBar\nfrom PyQt5.QtGui import QIcon, QPixmap\nimport sys\n\nPATH_TO_DOLPHIN = \"Dolphin.exe\"\nPATH_TO_GAME = \"\"\n\nclass MainWindow(QWidget):\n def __init__(self):\n super().__init__()\n # We need to instantiate a \"private\" variable and define getters \n # and setters on it for QT databinding to work properly.\n self._n = 0\n self.initUI()\n\n @property\n def n(self):\n return self._n\n\n @n.setter\n def n(self, value):\n self.button.setText(str(value))\n self.progressBar.setValue(value)\n self._n = value\n\n\n \n\n\n def initUI(self):\n self.setGeometry(600,600,600,600)\n layoutGrid = QGridLayout(self)\n\n\n # Basic Button Functionality\n self.button = QPushButton(str(self.n), self)\n self.button.clicked.connect(self.buttonClicked)\n layoutGrid.addWidget(self.button, 1, 1)\n \n # Progress Bar\n self.progressBar = QProgressBar(self)\n self.progressBar.setMinimum(0)\n self.progressBar.setMaximum(100)\n layoutGrid.addWidget(self.progressBar, 1, 2)\n\n # Dropdown \n self.dropDownMenu = QComboBox(self)\n self.entries = [\"qtdemo/screenshot1.png\", \"qtdemo/screenshot2.png\"]\n for i in range(len(self.entries)):\n self.dropDownMenu.insertItem(i, self.entries[i])\n self.dropDownMenu.currentIndexChanged.connect(self.updateImage)\n layoutGrid.addWidget(self.dropDownMenu, 1, 0)\n\n # Images\n self.img = QLabel(self)\n pixmap = QPixmap(self.entries[0])\n self.img.setPixmap(pixmap)\n layoutGrid.addWidget(self.img, 0, 0)\n\n\n\n # Show the window \n self.show()\n\n def buttonClicked(self, event):\n self.n = self.n + 1\n\n def updateImage(self, newIndex):\n pixmap = QPixmap(self.entries[newIndex])\n self.img.setPixmap(pixmap)\n\ndef main():\n app = QApplication([])\n window = MainWindow()\n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tp1/demos/qtdemo.py","file_name":"qtdemo.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"95572634","text":"#!/usr/bin/env python3\n\n# Load of the library that needed\n\n# Import package to scan hyperparameter\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom scipy.stats import randint as sp_randint\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom keras.models import load_model\nfrom sklearn.externals import joblib\n\n# Import package to reprocess the data\nimport numpy as np\nimport random\nimport pandas as pd\n\n# Import keras item\nimport keras\n\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.applications import *\nfrom keras.models import *\nfrom keras.models import Model\nfrom keras.layers import Input, Dense\nfrom keras.wrappers.scikit_learn import KerasClassifier\n\n# Get all of the data and reprocess them\n\n# Get the reprocessed data from .npy file\nx_train = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/x_train_oomycete.npy')\ny_train = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/y_train_oomycete.npy')\nx_dev = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/x_val_oomycete.npy')\ny_dev = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/y_val_oomycete.npy')\nx_test = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/x_test_oomycete.npy')\ny_test = np.load('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/data-oomycete/secreted_non_identical/y_test_oomycete.npy')\n\n# This Section is used to shuffle the data\n# Aggregates elements\ndata_training = list(zip(x_train, y_train))\ndata_development = list(zip(x_dev, y_dev))\ndata_testing = list(zip(x_test, y_test))\n\n# Shuffle the aggragated element on the list\nrandom.shuffle(data_training)\nrandom.shuffle(data_development)\nrandom.shuffle(data_testing)\n\n# Combine data training dan data development become one list of data train\ndata_train = data_training + data_development\n\n# Split the shuffled data\nx_train, y_train = zip(*data_train)\nx_test, y_test = zip(*data_testing)\n\n# Unpack the tuples\nx_train = np.array(list(x_train))\ny_train = np.array(list(y_train))\nx_test = np.array(list(x_test))\ny_test = np.array(list(y_test))\n\n\n# Define the convolutional layer with batch normalization\ndef conv1d_bn(x,\n filters,\n kernel_size,\n padding = 'same',\n strides = 1,\n activation_convolution = 'relu'):\n \"\"\"Utility function to apply conv + BN.\n # Arguments\n x: input tensor.\n filters: filters in `Conv1D`.\n num_row: height of the convolution kernel.\n num_col: width of the convolution kernel.\n padding: padding mode in `Conv1D`.\n strides: strides in `Conv1D`.\n\n # Returns\n Output tensor after applying `Conv2D` and `BatchNormalization`.\n \"\"\"\n\n x = layers.Conv1D(filters,\n \t kernel_size,\n strides = strides,\n padding = padding,\n use_bias = False,\n kernel_regularizer = regularizers.l1(0.001),\n bias_regularizer = regularizers.l1(0.001)\n )(x)\n x = layers.BatchNormalization()(x)\n x = layers.Activation(activation_convolution)(x)\n return x\n\n# Define the base model\ndef build_model_conv1D_lstm(filters,\n\t\t\t\t\t\t\tfilters_LSTM,\n\t\t\t\t\t\t\tstrides,\n\t\t\t\t\t\t\tpadding,\n\t\t\t\t\t\t\tactivation_convolution,\n\t\t\t\t\t\t\tactivation_LSTM,\n\t\t\t\t\t\t\toptimizers,\n\t\t\t\t\t\t\tnumber_hidden_units):\n\n\tinput = Input(shape = x_train.shape[1:])\n\tconvolution_1 = conv1d_bn(x = input,\n\t\t\t\t\t\t\t filters = filters,\n\t\t\t\t\t\t\t kernel_size = 1,\n\t\t\t strides = strides,\n\t\t\t padding = padding,\n\t\t\t activation_convolution = activation_convolution)\n\tconvolution_2 = conv1d_bn(x = input,\n\t\t\t\t\t\t\t filters = filters,\n\t\t\t\t\t\t\t kernel_size = 3,\n\t\t\t strides = strides,\n\t\t\t padding = padding,\n\t\t\t activation_convolution = activation_convolution)\n\tconvolution_3 = conv1d_bn(x = input,\n\t\t\t filters = filters,\n\t\t\t\t\t\t\t kernel_size = 5,\n\t\t\t strides = strides,\n\t\t\t padding = padding,\n\t\t\t activation_convolution = activation_convolution)\n\tmodel = keras.layers.concatenate([convolution_1,\n\t \t convolution_2,\n\t convolution_3], axis=1)\n\tmodel = Conv1D(filters * 2,\n\t \t\t kernel_size = 3,\n\t \t\t strides = 1,\n\t \t\t padding = padding,\n\t \t\t activation = activation_convolution,\n\t \t\t use_bias = True,\n\t \t\t kernel_initializer = 'glorot_uniform',\n\t \t\t bias_initializer = 'zeros',\n\t \t\t kernel_regularizer = regularizers.l1(0.001),\n bias_regularizer = regularizers.l1(0.001)\n )(model)\n\tmodel_lstm_1 = LSTM(filters_LSTM,\n\t \t\t\tactivation = activation_LSTM,\n\t \t\t\trecurrent_activation = 'hard_sigmoid',\n\t \t\t\tuse_bias = True,\n\t \t\t\tkernel_initializer = 'glorot_uniform',\n\t \t\t\trecurrent_initializer = 'orthogonal',\n\t \t\t\tbias_initializer = 'zeros',\n\t \t\t\tgo_backwards = False)(model)\n\n\tmodel_lstm_2 = LSTM(filters_LSTM,\n\t activation = activation_LSTM,\n\t recurrent_activation = 'hard_sigmoid',\n\t use_bias = True,\n\t kernel_initializer = 'glorot_uniform',\n\t \t\t\trecurrent_initializer = 'orthogonal',\n\t \t\t\tbias_initializer = 'zeros',\n\t \t\t\tgo_backwards = True)(model)\n\n\tmodel_final = keras.layers.concatenate([model_lstm_1, model_lstm_2])\n\n\toutput = Dense(number_hidden_units, activation = 'relu')(model_final)\n\tdropout = Dropout(0.5)(output)\n\toutput = Dense(1, activation = 'sigmoid')(dropout)\n\n\tmodel = Model(inputs = input, outputs = output)\n\n\tmodel.compile(loss = 'binary_crossentropy',\n optimizer = optimizers,\n metrics = ['accuracy'])\n\n\tprint(model.summary())\n\treturn model\n\n\n# Pass the model design to KerasClassifier() wrapper\n\nmodel = KerasClassifier(build_fn = build_model_conv1D_lstm, verbose = 1)\n\n# Define the parameters that will be tuned randomly\nkeras_param_options = {'filters' : [4, 8, 16],\n\t\t\t\t\t 'filters_LSTM' : [4, 8, 16],\n\t\t\t\t\t 'strides' : [1],\n\t\t\t\t\t 'padding' : ['valid'],\n\t\t\t\t\t 'activation_convolution' : [None],\n\t\t\t\t\t 'activation_LSTM' : ['tanh'],\n\t\t\t\t\t 'optimizers' : ['Adam', 'Adadelta'],\n\t\t\t\t\t 'number_hidden_units' : [4, 8],\n\t\t\t\t\t 'epochs' : [30],\n\t\t\t\t\t 'batch_size' : [4, 8, 16]}\n\n# Using RandomizedSearchCV to find the best model randomly\nrandom_search = RandomizedSearchCV(model,\n param_distributions = keras_param_options,\n n_iter = 50,\n cv = 5,\n verbose = 10)\n\n# Fit to the training data\nrandom_search.fit(x_train, y_train)\ndf_result_hyper_tuned = pd.DataFrame.from_dict(random_search.cv_results_)\ndf_result_hyper_tuned.to_csv('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/scripts-scan-multiclass/oomycete/results/all_scan_results_cnn_lstm_scan_oomycete_secreted_data.csv')\n\n# Save all of the params to be used to predict on the test data\ndf_result_hyper_tuned['mean_test_score']= pd.to_numeric(df_result_hyper_tuned['mean_test_score'])\nparam_best_model_dict = dict(df_result_hyper_tuned.nlargest(30, 'mean_test_score')['params'])\nparams = list(param_best_model_dict.values())\nprint(params)\n\n# Get info ahead about the best model obtained\nprint('Best score obtained: {0}'.format(random_search.best_score_))\nprint('Parameters:')\nfor param, value in random_search.best_params_.items():\n print('\\t{}: {}'.format(param, value))\n\n\n# Predict the prediction of the best model\nprint('Predict using test data using random_search:')\ny_pred_random_search = random_search.predict(x_test)\nacc_pred_random_search = accuracy_score(y_test, y_pred_random_search)\nprint('acc y_pred_random_search:', acc_pred_random_search)\n\n# Predict the results of hyperparamaters tuning for all parameters\n\n# Define function to fit the model\ndef train_fc_model(batch_sizes = None, num_epochs = None):\n model.fit(x = x_train,\n y = y_train,\n batch_size = batch_sizes,\n epochs = num_epochs,\n verbose = 1,\n shuffle = 1)\n\n# Define the function to calculate sensitivity and specificity\ndef sensitivity_specificity(predictions, y_test, mode='binary'):\n if mode == 'binary':\n # Determine positive class predictions\n index = predictions > 0.5\n predictions = np.zeros(predictions.shape)\n predictions[index] = 1\n # No need to modify y_test since it consists of zeros and ones already\n else:\n y_test = y_test\n predictions = np.argmax(predictions, axis=-1)\n\n # In the binary classification case as we create, we can extract tn, fp, fn, tp as follows\n tn, fp, fn, tp = confusion_matrix(y_test, predictions, labels = [0, 1]).ravel()\n\n # Sensitivity = TP / (TP + FN)\n sensitivity = tp / (tp + fn)\n\n # Specificity = TN / (TN + FP)\n specificity = tn / (tn + fp)\n\n # Precision = TP / (TP + FP)\n precision = tp / (tp + fp)\n\n # Return sensitivity, specificity, precision\n return(sensitivity, specificity, precision)\n\n\n# Define function to evaluate and predict\ndef evaluate_predict_fc_model():\n loss, acc = model.evaluate(x_test, y_test, verbose = 0)\n prediction = model.predict(x_test)\n sensitivity, specificity, precision = sensitivity_specificity(prediction, y_test, mode='binary')\n return acc, sensitivity, specificity, precision\n\n\n# Make prediction of test data\n\nresult_list = []\ncolumns_names = ['Parameters',\n 'Accuracy',\n 'Sensitivity',\n 'Specifity']\n\n\n# For loop to train model and get prediction for each combination of dataset\nfor i in range(len(params)):\n list_par = list(params[i].values())\n # Define the models\n model = build_model_conv1D_lstm(filters = list_par[5],\n\t\t\t\t\t\t\t\t\tfilters_LSTM = list_par[4],\n\t\t\t\t\t\t\t\t\tstrides = list_par[0],\n\t\t\t\t\t\t\t\t\tpadding = list_par[1],\n\t\t\t\t\t\t\t\t\tactivation_convolution = list_par[8],\n\t\t\t\t\t\t\t\t\tactivation_LSTM = list_par[9],\n\t\t\t\t\t\t\t\t\toptimizers = list_par[2],\n\t\t\t\t\t\t\t\t\tnumber_hidden_units = list_par[3])\n\n # Train the model one by one based on the parameters combination\n train_fc_model(batch_sizes = list_par[7], num_epochs = list_par[6])\n acc, sensitivity, specifity, precision = evaluate_predict_fc_model()\n result_line = np.array((params[i],\n acc,\n sensitivity,\n specifity))\n result_list.append(result_line[:])\n result_array = np.asarray(result_list)\n\n df_results = pd.DataFrame(result_array,\n columns = columns_names)\n\ndf_results.to_csv('/hpc-home/kristian/effector-non-effector/scripts-cnn-lstm-separate-group/scripts-scan-multiclass/oomycete/results/df_pred_results_cnn_lstm_scan_oomycete_secreted_data.csv')\n\n\n","sub_path":"scripts/python-scripts/hyperparameter-scan-scripts/oomycete/0001-cnn-lstm-scan-oomycete-secreted.py","file_name":"0001-cnn-lstm-scan-oomycete-secreted.py","file_ext":"py","file_size_in_byte":11383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"563792104","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 13 09:21:06 2019\n\n@author: wenninger\n\"\"\"\nimport numpy as np\nimport sys\n\nsys.path.insert(0, '../../Helper')\nsys.path.insert(0, '../../IV_Mixer_Analysis')\n\nfrom IV_Class import IV_Response,kwargs_IV_Response_rawData\nfrom Read_Filenames import read_Filenames,filenamesstr_of_interest\nfrom Mixer import Mixer,kwargs_Mixer_rawData\nfrom plotxy import plot\n\n# Name: folder/c-[Temperature]-[?const]-[measurment index]-[hot/cold].csv\n#filenamesstr: \n# [1] Physical temperature \n# [3] Measurement Index Missing sometimes\n# [-1] Hot Cold\nfilenames,filenamesstr = read_Filenames(\"\")\n\nfilenamesstrReduced = filenamesstr_of_interest(filenamesstr,[1,3,-1])\n\n#Group the indexes\nindexGroups =[]\nfor temp in np.unique(filenamesstrReduced[:,0]):\n for pump in np.unique(filenamesstrReduced[:,2]):\n indexGroups.append([temp,pump,np.where(np.logical_and(filenamesstrReduced[:,0]==temp, \n filenamesstrReduced[:,2]==pump))[0]])\nindexGroups = np.array(indexGroups)\n\n##filenames[indexGroups[0,2]]\n#IV = []\n#for i in indexGroups[:,2]:\n# if not i.size==0: #'univ' arrays are empty \n# IV.append(IV_Response(filenames[i],filenamesstrReduced[i],numberOfBins=1000))\n#IV = np.array(IV)\n\n#filenames[indexGroups[0,2]]\n\nnbins =1000\n\n#IV_Response and Mixer without kwargs\n#Mixers = []\n#for temp in np.unique(indexGroups[:,0]):\n# IVs =[]\n# for select in ['iv','hot','cold','univ'] :\n# # not all univ, unpumped IV curves are available\n# index= indexGroups[np.where(np.logical_and(indexGroups[:,0]==temp, indexGroups[:,1]==select))[0],2][0]\n# if not index.size==0:\n# #Initialise the IV responses\n# IVs.append(IV_Response(filenames[index],filenamesstrReduced[index],numberOfBins=nbins))\n# #Initialise the Mixer\n# if len(IVs)==3:\n# Mixers.append(Mixer(Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2], description = temp))\n# else: \n# Mixers.append(Mixer(Unpumped=IVs[3],Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],description = temp))\n#\n#With kwargs for testing kwargs input\n#Mixers = []\n#for temp in np.unique(indexGroups[:,0]):\n# IVs =[]\n# for select in ['iv','hot','cold','univ'] :\n# # not all univ, unpumped IV curves are available\n# index= indexGroups[np.where(np.logical_and(indexGroups[:,0]==temp, indexGroups[:,1]==select))[0],2][0]\n# if not index.size==0:\n# #Initialise the IV responses\n# IVs.append(IV_Response(filenames[index],**kwargs_IV_Response_rawData))\n# #Initialise the Mixer\n# if len(IVs)==3:\n# Mixers.append(Mixer(Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],**kwargs_Mixer_rawData))\n# else: \n# Mixers.append(Mixer(Unpumped=IVs[3],Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],**kwargs_Mixer_rawData))\n \n#With kwargs\nMixers = []\nfor temp in np.unique(indexGroups[:,0]):\n IVs =[]\n for select in ['iv','hot','cold','univ'] :\n # not all univ, unpumped IV curves are available\n index= indexGroups[np.where(np.logical_and(indexGroups[:,0]==temp, indexGroups[:,1]==select))[0],2][0]\n if not index.size==0:\n #Initialise the IV responses\n IVs.append(filenames[index])\n #Initialise the Mixer\n if len(IVs)==3:\n Mixers.append(Mixer(Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],**kwargs_Mixer_rawData))\n else: \n Mixers.append(Mixer(Unpumped=IVs[3],Pumped=IVs[0],IFHot=IVs[1], IFCold=IVs[2],**kwargs_Mixer_rawData))\n \n\n","sub_path":"2019_11_12_Alessandro_IF/Alessandro_IF_2019_11_12.py","file_name":"Alessandro_IF_2019_11_12.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"616350350","text":"#!/usr/bin/env python\nfrom __future__ import print_function\nimport matplotlib.pyplot as plt\nfrom os import path\nimport logging\nfrom netcdfstream import stream\n\nlogger = logging.getLogger(__name__)\nlogging.basicConfig(level=logging.DEBUG)\n\n\nhere = path.abspath(path.dirname(__file__))\nsrc = path.join(here, '../data/sresa1b_ncar_ccsm3-example.nc')\n\n#erda_ro = \"/home/niklas/repos/climate/erda_ro\"\n#ctrl_ocn = \"Ocean/GCS_2015_2017/CESM_OUTPUT/ctrl_ocn\"\n#src = path.join(erda_ro, ctrl_ocn, \"ctrl.g.e11.G.T62_t12.002.pop.h.0025-01-03.nc\")\n\n#CESM_niklas = \"Ocean/CESM_output_niklas\"\n#src = path.join(erda_ro, CESM_niklas, \"sresa1b_ncar_ccsm3-example.nc\")\n\nlogger.info(\"Opening stream ...\")\nfin = open(src, 'rb')\nlogger.info(\"Init netCDF stream ...\")\nnc = stream.NetcdfStream(fin)\n\nlogger.info(nc.dimensions)\nimport pprint\nlogger.info(pprint.pformat(nc.meta['TBLT']))\n\nfor i in range(nc.varnr):\n\n name, meta, data = nc.read_dataset()\n logger.info(name)\n logger.info(data)\n\n if len(data.shape) == 1:\n plt.plot(data)\n elif len(data.shape) == 2:\n plt.imshow(data)\n elif len(data.shape) == 3:\n plt.imshow(data[0])\n else:\n print('Unkown data shape:', data.shape)\n plt.title(name)\n plt.show()\n","sub_path":"examples/read_local.py","file_name":"read_local.py","file_ext":"py","file_size_in_byte":1236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"487471583","text":"from djoser.views import UserViewSet\nfrom rest_framework import status\nfrom rest_framework.decorators import action\nfrom rest_framework.generics import get_object_or_404\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.permissions import IsAuthenticatedOrReadOnly\nfrom rest_framework.response import Response\n\nfrom api.serializers import UserFollowSerializer\nfrom users.models import Follow, User\nfrom users.serializers import UserSerializer\n\n\nclass CustomUserViewSet(UserViewSet):\n serializer_class = UserSerializer\n permission_classes = [IsAuthenticatedOrReadOnly]\n pagination_class = LimitOffsetPagination\n\n @action(['get'], detail=False)\n def subscriptions(self, request):\n follower = User.objects.filter(follow__user=request.user)\n page = self.paginate_queryset(follower)\n serializer = UserFollowSerializer(\n page,\n many=True,\n context={'user': request.user})\n return self.get_paginated_response(serializer.data)\n\n @action(['get'], detail=False)\n def me(self, request):\n serializer = UserSerializer(request.user)\n return Response(serializer.data)\n\n @action(['get', 'delete'], detail=True)\n def subscribe(self, request, id=None):\n queryset = User.objects.all()\n follow = get_object_or_404(queryset, id=id)\n if request.method == 'GET':\n Follow.objects.get_or_create(\n user=request.user,\n following=follow,\n )\n elif request.method == 'DELETE':\n try:\n following = Follow.objects.get(\n user=request.user,\n following=follow\n )\n following.delete()\n except ValueError:\n return Response(\n {'errors': 'Вы не подписаны на этого пользователя', },\n status.HTTP_400_BAD_REQUEST\n )\n serializer = self.get_serializer(follow)\n return Response(serializer.data)\n","sub_path":"backend/foodgram/users/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"490676402","text":"from tkinter import *\n\nroot = Tk()\nroot.title('Simple calc')\n\nmath = ''\nf_num = None\nis_operation = False\n\ndef float_or_int(number):\n\tif str(number).find('.') == -1:\n\t\treturn int(number)\n\telif str(number)[str(number).find('.'):] == '.0':\n\t\treturn int(number)\n\telse:\n\t\treturn float(number)\n\ndef solving_equations(second_number):\n\tglobal math\n\tglobal f_num\n\tif math == 'addition':\n\t\treturn float_or_int(f_num + float(second_number))\n\n\tif math == 'substraction':\n\t\treturn float_or_int(f_num - float(second_number))\n\n\tif math == 'multiplication':\n\t\treturn float_or_int(f_num * float(second_number))\n\n\tif math == 'division':\n\t\treturn float_or_int(f_num / float(second_number))\n\ndef button_click(number):\n\tglobal is_operation\n\tbutton_AC['text'] = 'C'\n\tif not(is_operation):\n\t\tinputField.insert(END, number)\n\telse:\n\t\tinputField.delete(0, END)\n\t\tinputField.insert(END, number)\n\t\tis_operation = False\n\ndef button_insert(sign):\n\tinput_number = inputField.get()\n\tif sign == '.':\n\t\tif input_number.find('.') == -1:\n\t\t\tinputField.insert(END, sign)\n\n\tif sign == '-':\n\t\tif input_number[0] == '-':\n\t\t\tinputField.delete(0, END)\n\t\t\tinputField.insert(0, input_number[1:])\n\t\telse:\n\t\t\tinputField.insert(0, sign)\n\ndef button_clear():\n\tglobal math\n\tglobal f_num\n\tglobal is_operation\n\tif button_AC['text'] == 'AC':\n\t\tmath = ''\n\t\tf_num = None\n\t\tis_operation = False\n\t\tinputField.delete(0, END)\n\n\telif button_AC['text'] == 'C':\n\t\tbutton_AC['text'] = 'AC'\n\t\tinputField.delete(0, END)\n\ndef button_add():\n\tfirst_number = inputField.get()\n\tglobal f_num\n\tglobal math\n\tglobal is_operation\n\tis_operation = True\n\tmath = 'addition'\n\tf_num = float(first_number)\n\ndef button_substract():\n\tfirst_number = inputField.get()\n\tglobal f_num\n\tglobal math\n\tglobal is_operation\n\tis_operation = True\n\tmath = 'substraction'\n\tf_num = float(first_number)\n\ndef button_multiply():\n\tfirst_number = inputField.get()\n\tglobal f_num\n\tglobal math\n\tglobal is_operation\n\tis_operation = True\n\tmath = 'multiplication'\n\tf_num = float(first_number)\n\ndef button_divide():\n\tfirst_number = inputField.get()\n\tglobal f_num\n\tglobal math\n\tglobal is_operation\n\tis_operation = True\n\tmath = 'division'\n\tf_num = float(first_number)\n\ndef button_percentage():\n\tinput_number = float(inputField.get())\n\tif f_num == None:\n\t\tinputField.delete(0, END)\n\t\tinputField.insert(0, float_or_int(input_number / 100))\n\telse:\n\t\tinputField.delete(0, END)\n\t\tinputField.insert(0, float_or_int(f_num * (input_number / 100)))\n\ndef button_equal():\n\tif math == '':\n\t\treturn\n\n\tsecond_number = inputField.get()\n\tinputField.delete(0, END)\n\n\tinputField.insert(0, solving_equations(second_number))\n\n\ninputField = Entry(root, width = 28, borderwidth = 5)\n\nbutton_0 = Button(root, text = '0', width = 14, padx = 3, height = 3, command = lambda: button_click(0))\nbutton_1 = Button(root, text = '1', width = 7, height = 3, command = lambda: button_click(1))\nbutton_2 = Button(root, text = '2', width = 7, height = 3, command = lambda: button_click(2))\nbutton_3 = Button(root, text = '3', width = 7, height = 3, command = lambda: button_click(3))\nbutton_4 = Button(root, text = '4', width = 7, height = 3, command = lambda: button_click(4))\nbutton_5 = Button(root, text = '5', width = 7, height = 3, command = lambda: button_click(5))\nbutton_6 = Button(root, text = '6', width = 7, height = 3, command = lambda: button_click(6))\nbutton_7 = Button(root, text = '7', width = 7, height = 3, command = lambda: button_click(7))\nbutton_8 = Button(root, text = '8', width = 7, height = 3, command = lambda: button_click(8))\nbutton_9 = Button(root, text = '9', width = 7, height = 3, command = lambda: button_click(9))\n\nbutton_coma = Button(root, text = ',', width = 7, height = 3, command = lambda: button_insert('.'))\nbutton_plusMinus = Button(root, text = '+/-', width = 7, height = 3, command = lambda: button_insert('-'))\nbutton_AC = Button(root, text = 'AC', width = 7, height = 3, command = button_clear)\nbutton_add = Button(root, text = '+', width = 7, height = 3, command = button_add)\nbutton_substract = Button(root, text = '-', width = 7, height = 3, command = button_substract)\nbutton_multiply = Button(root, text = '*', width = 7, height = 3, command = button_multiply)\nbutton_divide = Button(root, text = '/', width = 7, height = 3, command = button_divide)\nbutton_percentage = Button(root, text = '%', width = 7, height = 3, command = button_percentage)\nbutton_equal = Button(root, text = '=', width = 7, height = 3, command = button_equal)\n\n# Put the buttons on the screen\ninputField.grid(row = 0, column = 0, columnspan = 4)\n\nbutton_AC.grid(row = 1, column = 0)\nbutton_plusMinus.grid(row = 1, column = 1)\nbutton_percentage.grid(row = 1, column = 2)\nbutton_divide.grid(row = 1, column = 3)\n\nbutton_7.grid(row = 2, column = 0)\nbutton_8.grid(row = 2, column = 1)\nbutton_9.grid(row = 2, column = 2)\nbutton_multiply.grid(row = 2, column = 3)\n\nbutton_4.grid(row = 3, column = 0)\nbutton_5.grid(row = 3, column = 1)\nbutton_6.grid(row = 3, column = 2)\nbutton_substract.grid(row = 3, column = 3)\n\nbutton_1.grid(row = 4, column = 0)\nbutton_2.grid(row = 4, column = 1)\nbutton_3.grid(row = 4, column = 2)\nbutton_add.grid(row = 4, column = 3)\n\nbutton_0.grid(row = 5, column = 0, columnspan = 2)\nbutton_coma.grid(row = 5, column = 2)\nbutton_equal.grid(row = 5, column = 3)\n\n\nroot.mainloop()","sub_path":"python/9calculatorInPython/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"576253340","text":"from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.naive_bayes import MultinomialNB\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\n\n''' KAGGLE FILES '''\nTRAIN_FILE = 'train.csv'\ndf = pd.read_csv(TRAIN_FILE)\nKAGGLE_TEST_FILE = 'test.csv'\nkaggle_test_df = pd.read_csv(KAGGLE_TEST_FILE)\n\n''' Renaming Labels '''\ndf.loc[df['author']=='EAP', 'author'] = 0\ndf.loc[df['author']=='HPL', 'author'] = 1\ndf.loc[df['author']=='MWS', 'author'] = 2\n\n''' Extracting Necessary Things '''\nX = df['text']\nX_kaggle = kaggle_test_df['text']\ny = df['author'].astype('int')\n\n''' Transforming Data For Use '''\ntfidf = TfidfVectorizer(stop_words='english')\nX = tfidf.fit_transform(X)\nX_kaggle = tfidf.transform(X_kaggle)\n\n\n''' Grid Search '''\nclf = MultinomialNB(fit_prior=True, alpha=.01)\n\nalpha_range = [i for i in np.arange(0.000,1.0,.015)]\nprior = [True, False] # Taken out after initial grid search so we wcan graph easier\ngrid_clf = GridSearchCV(clf, {'alpha': alpha_range},scoring='accuracy', n_jobs=1, cv=100)\ngrid_clf.fit(X, y)\n\n''' Processing Results '''\nmean_scores = [result.mean_validation_score for result in grid_clf.grid_scores_]\nplt.plot(alpha_range, mean_scores)\nplt.ylabel('Mean Score (CV=100)')\nplt.xlabel('Alpha')\nplt.show()\nprint(grid_clf.best_score_, grid_clf.best_params_)\n\n\n''' One Vs Rest Classification from Grid Search Result '''\nmnb_ovr = OneVsRestClassifier(grid_clf.best_estimator_, n_jobs=1)\nmnb_ovr.fit(X, y)\nkaggle_results = mnb_ovr.predict_proba(X_kaggle)\nprint(kaggle_results)\n","sub_path":"Submissions/Submission4_AlphaPt18_PriorTrue.py","file_name":"Submission4_AlphaPt18_PriorTrue.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"262154132","text":"\ndef expose(obj,names=None,cl=None):\n\n \"\"\" Expose the methods of an object to the specified dictionary.\n (I am not sure whether this is exactly compatible to what does the\n interpreter...)\n\n \"\"\"\n if names is None:\n names = {}\n\n if cl is None:\n cl = obj.__class__\n \n for name in cl.__dict__.keys():\n if not hasattr(names,name):\n names[name] = getattr(obj,name)\n \n for base in cl.__bases__:\n names = expose(obj,names,base)\n\n return names\n\n\n","sub_path":"timtools/misc/expose.py","file_name":"expose.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"575848421","text":"import uuid\nimport json\n\nfrom rentomatic.serializers import room_json_serializer as ser\nfrom rentomatic.domain import room as r\n\ndef test_room_domain_room():\n\n code = uuid.uuid4()\n room = r.Room(code, size=200,price=10, longitude=300, latitude=400)\n\n expected_json = \"\"\"\n {{\n \"code\": \"{}\",\n \"size\": 200,\n \"price\": 10,\n \"longitude\": 300,\n \"latitude\": 400\n }}\n \"\"\".format(code)\n\n json_room = json.dumps(room,cls=ser.RoomJsonEncoder)\n assert json.loads(json_room) == json.loads(expected_json)\n\n\n","sub_path":"chapter_2/rentomatic/tests/serializers/test_room_json-serializer.py","file_name":"test_room_json-serializer.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"180070489","text":"\"\"\"Support to interface with the Plex API.\"\"\"\nimport logging\n\nfrom homeassistant.components.media_player import BrowseMedia\nfrom homeassistant.components.media_player.errors import BrowseError\n\nfrom .const import DOMAIN\n\nEXPANDABLES = [\"album\", \"artist\", \"playlist\", \"season\", \"show\"]\nPLAYLISTS_BROWSE_PAYLOAD = {\n \"title\": \"Playlists\",\n \"media_content_id\": \"all\",\n \"media_content_type\": \"playlists\",\n \"can_play\": False,\n \"can_expand\": True,\n}\nSPECIAL_METHODS = {\n \"On Deck\": \"onDeck\",\n \"Recently Added\": \"recentlyAdded\",\n}\n\n_LOGGER = logging.getLogger(__name__)\n\n\ndef browse_media(\n entity_id, plex_server, media_content_type=None, media_content_id=None\n):\n \"\"\"Implement the websocket media browsing helper.\"\"\"\n\n def build_item_response(payload):\n \"\"\"Create response payload for the provided media query.\"\"\"\n media = plex_server.lookup_media(**payload)\n\n if media is None:\n return None\n\n media_info = item_payload(media)\n if media_info.can_expand:\n media_info.children = []\n for item in media:\n media_info.children.append(item_payload(item))\n return media_info\n\n if media_content_id and \":\" in media_content_id:\n media_content_id, special_folder = media_content_id.split(\":\")\n else:\n special_folder = None\n\n if (\n media_content_type\n and media_content_type == \"server\"\n and media_content_id != plex_server.machine_identifier\n ):\n raise BrowseError(\n f\"Plex server with ID '{media_content_id}' is not associated with {entity_id}\"\n )\n\n if special_folder:\n if media_content_type == \"server\":\n library_or_section = plex_server.library\n title = plex_server.friendly_name\n elif media_content_type == \"library\":\n library_or_section = plex_server.library.sectionByID(media_content_id)\n title = library_or_section.title\n\n payload = {\n \"title\": title,\n \"media_content_id\": f\"{media_content_id}:{special_folder}\",\n \"media_content_type\": media_content_type,\n \"can_play\": False,\n \"can_expand\": True,\n \"children\": [],\n }\n\n method = SPECIAL_METHODS[special_folder]\n items = getattr(library_or_section, method)()\n for item in items:\n payload[\"children\"].append(item_payload(item))\n return BrowseMedia(**payload)\n\n if media_content_type in [\"server\", None]:\n return server_payload(plex_server)\n\n if media_content_type == \"library\":\n return library_payload(plex_server, media_content_id)\n\n if media_content_type == \"playlists\":\n return playlists_payload(plex_server)\n\n payload = {\n \"media_type\": DOMAIN,\n \"plex_key\": int(media_content_id),\n }\n response = build_item_response(payload)\n if response is None:\n raise BrowseError(f\"Media not found: {media_content_type} / {media_content_id}\")\n return response\n\n\ndef item_payload(item):\n \"\"\"Create response payload for a single media item.\"\"\"\n payload = {\n \"title\": item.title,\n \"media_content_id\": str(item.ratingKey),\n \"media_content_type\": item.type,\n \"can_play\": True,\n \"can_expand\": item.type in EXPANDABLES,\n }\n if hasattr(item, \"thumbUrl\"):\n payload[\"thumbnail\"] = item.thumbUrl\n\n return BrowseMedia(**payload)\n\n\ndef library_section_payload(section):\n \"\"\"Create response payload for a single library section.\"\"\"\n return BrowseMedia(\n title=section.title,\n media_content_id=section.key,\n media_content_type=\"library\",\n can_play=False,\n can_expand=True,\n )\n\n\ndef special_library_payload(parent_payload, special_type):\n \"\"\"Create response payload for special library folders.\"\"\"\n title = f\"{special_type} ({parent_payload.title})\"\n return BrowseMedia(\n title=title,\n media_content_id=f\"{parent_payload.media_content_id}:{special_type}\",\n media_content_type=parent_payload.media_content_type,\n can_play=False,\n can_expand=True,\n )\n\n\ndef server_payload(plex_server):\n \"\"\"Create response payload to describe libraries of the Plex server.\"\"\"\n server_info = BrowseMedia(\n title=plex_server.friendly_name,\n media_content_id=plex_server.machine_identifier,\n media_content_type=\"server\",\n can_play=False,\n can_expand=True,\n )\n server_info.children = []\n server_info.children.append(special_library_payload(server_info, \"On Deck\"))\n server_info.children.append(special_library_payload(server_info, \"Recently Added\"))\n for library in plex_server.library.sections():\n if library.type == \"photo\":\n continue\n server_info.children.append(library_section_payload(library))\n server_info.children.append(BrowseMedia(**PLAYLISTS_BROWSE_PAYLOAD))\n return server_info\n\n\ndef library_payload(plex_server, library_id):\n \"\"\"Create response payload to describe contents of a specific library.\"\"\"\n library = plex_server.library.sectionByID(library_id)\n library_info = library_section_payload(library)\n library_info.children = []\n library_info.children.append(special_library_payload(library_info, \"On Deck\"))\n library_info.children.append(\n special_library_payload(library_info, \"Recently Added\")\n )\n for item in library.all():\n library_info.children.append(item_payload(item))\n return library_info\n\n\ndef playlists_payload(plex_server):\n \"\"\"Create response payload for all available playlists.\"\"\"\n playlists_info = {**PLAYLISTS_BROWSE_PAYLOAD, \"children\": []}\n for playlist in plex_server.playlists():\n playlists_info[\"children\"].append(item_payload(playlist))\n return BrowseMedia(**playlists_info)\n","sub_path":"homeassistant/components/plex/media_browser.py","file_name":"media_browser.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"291147633","text":"from nltk.corpus import stopwords\nimport unittest\n\n\ndef in_stoplist(token):\n stop_words = set(stopwords.words('english'))\n stop_words.update(['.', ',', '\"', \"'\", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}'])\n return token in stop_words\n\nclass UTest(unittest.TestCase):\n def setUp(self):\n self.stop_words = set(stopwords.words('english'))\n self.stop_words.update(['.', ',', '\"', \"'\", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}'])\n\n def test_in(self):\n for tok in self.stop_words:\n self.assertTrue(in_stoplist(tok))\n\n def test_not_in(self):\n for line in open('sentiment.txt'):\n for tok in line.strip().split():\n if tok not in self.stop_words:\n self.assertFalse(in_stoplist(tok))\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"ryosuke/chapter08/knock71.py","file_name":"knock71.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"307354573","text":"# -*- coding: utf-8 -*-\n'''\n Tracker groups connections and events into channels.\n'''\nimport logging\n\nfrom channel import Channel\nfrom events import *\n\nfrom serverpush.active_events import active_events\n\nlogger = logging.getLogger('serverpush')\n\n\nclass Tracker(object):\n\n def generate_id(self):\n ids = 1\n while 1:\n yield ids\n ids += 1\n\n def __init__(self):\n\n # mapa: event -> user_id -> connection\n self.channels = {}\n # mapa: user_id -> lista eventow\n self.users = {}\n\n self.id_gen = self.generate_id()\n #historia\n self.history = {}\n self.shared = {}\n for ev in store_history:\n self.history[ev] = EventHistory(ev, active_events[ev]._event_type)\n\n for ev in active_events:\n self.channels[ev] = Channel(ev, tracker=self,\n history=self.history.get(ev, None))\n\n def connect(self, conn):\n '''\n Nawiazywanie polaczenia, inicjalizujace eventy\n '''\n #jesli uzytkonik zalogowany id -> pk usera\n #if conn.request.user.is_authenticated():\n # conn.id = conn.request.user.pk\n\n conn.id = self.id_gen.next()\n user_id = conn.get_user_id()\n\n logger.debug(\"New connection; user %s; path %s; conn_id %s \" % (user_id,\n conn.request.path_info, conn.id))\n\n if user_id not in self.users:\n self.users[user_id] = {}\n\n #tworzymy kanaly dla wspieranych eventow i doklejamy zdarzenia\n for event in conn.events:\n if active_events.has_key(event):\n #niezalogowani uzytkownicy moga odbierac tylko broadcasty\n if active_events[event].is_init_event():\n Channel.init_event(conn, event, shared=self.shared)\n\n if self.history.has_key(event):\n self.history[event].send_history(conn)\n\n if not (active_events[event].is_broadcast_event() or\n conn.request.user.is_authenticated()):\n continue\n\n #XXX: nadmiarowe, w konstruktorze wszystkie kanaly sa inicjalizowane\n if not self.channels.has_key(event):\n logger.error('Brak kanalu %s, to niepowinno miec miejsca' % event)\n self.channels[event] = Channel(event, tracker=self,\n history=self.history.get(event, None))\n\n if not self.users[user_id].has_key(event):\n self.users[user_id][event] = True\n\n self.channels[event].new_connection(conn)\n\n def disconnect(self, conn):\n '''\n Czyszczenie kolekcji po utracie polaczenia\n '''\n user_id = conn.get_user_id()\n\n if not self.users.has_key(user_id):\n #nie powinno sie zdarzyc, ale 'just in case'\n return\n\n #uwzglednia anonimowe polaczenia\n #XXX: moze sprawdzac czy mapowanie istnieje,\n #teoretycznie wieksza szansa ze beda nadmiarowe dane, niz ich nie bedzie\n for event in self.users[user_id].keys():\n try:\n del self.channels[event].connections[user_id][conn.id]\n logger.debug(\"Disconnect: user %s; conn_id %s; event %s\" % (\n user_id, conn.id, event\n ))\n if not self.channels[event].connections[user_id]:\n del self.channels[event].connections[user_id]\n except AttributeError:\n continue\n except KeyError:\n continue\n\n # Caled by notify.py as a callback via server.py on a new event\n # notifies other connections and returns success status\n def event(self, event, gen_timestamp, user=None, **kwargs):\n '''\n Odpalany przez notifier po otrzymaniu requesta\n '''\n if user:\n user = int(user)\n\n if event == ServerPushEvent.SOCKETIO_LOGOUT:\n self.logout_event(user)\n return\n\n channel = self.channels.get(event, None)\n\n if channel:\n if channel.event.is_broadcast_event():\n channel.broadcast_event(gen_timestamp, **kwargs)\n\n elif channel.event.is_user_event():\n channel.user_event(user, **kwargs)\n\n def logout_event(self, user):\n '''\n Zdarzenie wylogowania -> przeladowuje wszystkie\n strony aktualnie zalogowanego uzytkownika\n '''\n logger.debug(\"Logout: user %s\" % user)\n #wysylamy conajwyzej jeden komunikat do polaczenia\n connections_notified = {}\n if user is not None:\n if not self.users.has_key(user):\n return\n\n for event in self.users[user].keys():\n self.channels[event].logout_event(user, connections_notified)\n\n for con_id, con in connections_notified.items():\n self.disconnect(con)\n","sub_path":"serverpush/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":4965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"411438722","text":"\nimport os, sys, re, time\nimport json, logging\nfrom datetime import datetime\nimport traceback\nimport tempfile\nimport multiprocessing\nfrom pprint import pprint as pp\nfrom include.utils import awscreds \nlog=logging.getLogger('cli')\ne=sys.exit\n\nfrom include.utils import create_reader\n\nfrom include.utils import ctimeit, clierr\ntry:\n\timport cStringIO\nexcept ImportError:\n\timport io as cStringIO\n\n\nif sys.version_info[0] >= 3:\n\tunicode=bytes\n\nclass Cli(object):\n\t#@ctimeit\n\tdef __init__(self,*args,**kwargs):\n\t\tself.cli_kwargs=kwargs\n\t\tself.dcf = kwargs.get('db_config_file', None)\n\t\tself.pcf = kwargs.get('proc_config_file', None)\n\t\tself.rte = kwargs.get('runtime_environment', None)\t\n\t\tself.pa = list(kwargs.get('proc_params', None)\t)\n\t\tself.mf = kwargs.get('mock_file', None)\n\t\tself.dump = kwargs.get('dump', None)\n\t\tself.lame_duck = kwargs.get('lame_duck', None)\n\t\tself.dd\t = kwargs.get('dump_dir', None)\n\t\tself.sr\t = kwargs.get('skip_rows', None)\n\t\tself.dop = kwargs.get('degree_of_parallelism', None)\n\t\tself.skew_pct = kwargs.get('skew_pct', None)\n\t\tself.asod= time.strftime(\"%Y-%m-%d %H:%M:%S\") \n\t\tself.csep= b'^'\n\t\tself._source=self._src_class=self._trg_class=self._dmp_class=None\n\t\tassert self.dop< multiprocessing.cpu_count() * 4\n\t\tif 0:\n\t\t\tself.aws_keys=self.get_aws_keys()\n\t\tif 1:\n\t\t\ttemp_name = next(tempfile._get_candidate_names())\n\t\t\tself.tss=datetime.now().strftime('%Y%m%d_%H%M%S')\n\t\t\tself.filter='%s.%s' % (temp_name,self.tss)\n\t\tassert self.dcf, 'Provide db config file name [-dcf]'\n\t\tassert self.dcf, 'Provide proc config file name [-pcf]'\n\t\tself.cfg=self.scfg=self.tcfg=self.dcfg=self.s3cfg=None\n\t\tself.db_config()\n\t\tself.proc_config()\n\t\tif 0:\n\t\t\tself.apx_cmap,self.apx=self.get_appendix()\n\t\telse:\n\t\t\tself.apx_cmap,self.apx = None,None\n\t\tself.start_time = time.time()\n\tdef set_source(self, key):\n\t\tself._source=key\n\t\t\n\t@ctimeit\n\tdef get_aws_keys(self):\n\t\tlog.debug('First try to get keys.')\n\t\taws_keys=awscreds.get_aws_keys(max_tries=1)\n\t\tif not aws_keys[0] or not aws_keys[1]:\n\t\t\tlog.debug('Creating keys.')\n\t\t\taws_keys=awscreds.create_aws_keys()\n\t\t\tlog.debug('Second try to get keys after create.')\n\t\t\taws_keys=awscreds.get_aws_keys(max_tries=10)\n\t\tif not aws_keys[0] or not aws_keys[1]:\n\t\t\tlog.error('Cannot get aws keys')\n\t\t\traise Exception(clierr.E_GET_AWS_KEYS_FAILED[0])\n\t\treturn aws_keys\n\t\t\n\t@ctimeit\n\tdef db_config(self):\n\t\tdcf=self.dcf\n\t\tassert os.path.isfile(dcf), 'DB config file does not exists:\\n%s' % dcf\n\t\twith open(dcf, 'r') as f:\n\t\t\ttry:\n\t\t\t\tself.dbcfg = json.loads(f.read())\n\t\t\texcept:\n\t\t\t\terr_log = cStringIO.StringIO()\n\t\t\t\ttraceback.print_exc(file=err_log)\n\t\t\t\terror = err_log.getvalue()\n\t\t\t\tprint ('#' * 80)\n\t\t\t\tprint ('ERROR when parsing DBconfig json file', dcf)\n\t\t\t\tprint ('#' * 80)\n\t\t\t\tprint(error)\n\t\t\t\tprint ('#' * 80)\n\t\t\t\tprint ('#' * 80)\n\t\t\t\te()\n\t\t\n\t\t\t\t\n\t\t\tself.stores = self.dbcfg[\"stores\"]\n\tdef get_alt_cols(self, cfg):\n\t\treturn {c[\"altColName\"]:c[\"columnName\"] for c in cfg[\"columnMappings\"] if c.get(\"altColName\", None)}\n\tdef header_size(self, cfg):\n\t\treturn cfg[\"writeHeader\"]\n\t\t\n\tdef get_load_cols(self, toDB, cfg, data_files):\n\t\tscfg, dir_scfg = cfg \n\t\tacols= self.get_alt_cols(scfg)\n\t\ttcols=toDB.get_cols()\n\t\tfcols_alt=[]\n\t\tfor data_file in data_files.file_names:\n\t\t\tdataFile \t= create_reader(aname = 'File',\tapp_init=app_init, file_name=data_file, scfg=dir_scfg)\n\t\t\tdataFile.describe()\n\t\t\tfcols_alt=[acols.get(x,x) for x in dataFile.get_header(data_file, dir_scfg)]\n\t\t\tassert not set(fcols_alt) -set(tcols), 'File has columns missing in table.'\n\t\t\tassert not set(tcols) -set(fcols_alt), 'Table has columns missing in file.'\n\t\tassert fcols_alt\n\t\treturn fcols_alt\n\n\t\t\t\t\n\tdef get_store_env_refs(self,db):\n\t\t#db=db.split('_')[0]\n\t\t#print db\n\t\tdbenv=self.dbcfg['env'][self.rte][db]\n\t\treturn self.stores[dbenv]['env_refs']\n\tdef get_runtime_env_vars(self):\n\t\treturn self.dbcfg['env'][self.rte]['env_vars']\n\tdef get_appendix(self):\n\t\tscfg, params=self.scfg, self.pa\n\t\tcolumnMappings = scfg[\"columnMappings\"]\n\t\tapx_pmap={map['sourceParam']: re.sub('[\\'\" ]', '', params[map['sourceParamIndex']]) for map in columnMappings if map['value'].encode() == b'Param'}\n\t\tapx_cmap={map['columnName']: re.sub('[\\'\" ]', '', params[map['sourceParamIndex']]) for map in columnMappings if map['value'].encode() == b'Param'}\n\t\tsep=str(self.csep.decode())\n\t\tapx=sep.join([apx_pmap[map['sourceParam']] if map['value'] == 'Param' else self.asod for map in columnMappings \n\t\t\t\t\t\tif map['value'] == 'Param' or (map['value'] == 'Default' and map['valueType'] == 'TimeStamp') ] )\n\n\t\treturn apx_cmap, apx\n\tdef get_appendix2(self):\n\t\tscfg, params=self.scfg, self.pa\n\t\tif self.scfg.get('columnMappings', None):\n\t\t\tcolumnMappings = scfg[\"columnMappings\"]\n\t\t\tapx_pmap={map['sourceParam']: re.sub('[\\'\" ]', '', params[map['sourceParamIndex']]) for map in columnMappings if map['value'].encode() == b'Param'}\n\t\t\tapx_cmap={map['columnName']: re.sub('[\\'\" ]', '', params[map['sourceParamIndex']]) for map in columnMappings if map['value'].encode() == b'Param'}\n\t\t\tsep=str(self.csep.decode())\n\t\t\tapx=sep.join([apx_pmap[map['sourceParam']] if map['value'] == 'Param' else self.asod for map in columnMappings \n\t\t\t\t\t\t\tif map['value'] == 'Param' or (map['value'] == 'Default' and map['valueType'] == 'TimeStamp') ] )\n\t\t\tapx_cols=[map['columnName'] if map['value'] == 'Param' else map['columnName'] for map in columnMappings \n\t\t\t\t\t\t\tif map['value'] == 'Param' or (map['value'] == 'Default' and map['valueType'] == 'TimeStamp') ] \n\t\t\treturn apx_cmap,apx_cols, apx\n\t\telse:\n\t\t\treturn {}, [], None\n\t\t\n\tdef done(self):\n\t\tsec=round((time.time() - self.start_time),2)\n\t\tlog.info('Total elapsed: %s sec/%s min' % (sec, round(sec/60,2)))\n\tdef set_dcfg(self, cname):\n\t\tassert self._source\n\t\tself.dcfg= self.cfg['dump'][self._source][cname]\n\tdef set_tcfg(self, cname):\n\t\tassert self._source\n\t\tself.tcfg= self.cfg['target'][self._source][cname]\n\tdef set_scfg(self, cname):\n\t\tassert self._source\n\t\tself.scfg= self.cfg['source'][self._source][cname]\n\t\t\t\n\tdef get_scfg(self, cname=None):\n\t\tif not cname:\n\t\t\tif self._source:\n\t\t\t\treturn self.cfg['source'][self._source]\n\t\t\telse:\n\t\t\t\treturn self.cfg['source']\t\t\n\t\telse:\n\t\t\tassert cname\n\t\t\tassert self._source\n\t\t\tself._src_class = cname\n\t\t\treturn self.cfg['source'][self._source][self._src_class]\n\n\tdef get_dcfg(self, cname=None):\n\t\tif not cname:\n\t\t\tif self._source:\n\t\t\t\treturn self.cfg['dump'][self._source]\n\t\t\telse:\n\t\t\t\treturn self.cfg['dump']\t\t\n\t\telse:\n\t\t\tassert cname\n\t\t\tassert self._source\n\t\t\tself._dmp_class = cname\n\t\t\treturn self.cfg['dump'][self._source][self._dmp_class]\n\n\tdef get_tcfg(self, cname=None):\n\t\tif not cname:\n\t\t\tif self._source:\n\t\t\t\treturn self.cfg['target'][self._source]\n\t\t\telse:\n\t\t\t\treturn self.cfg['target']\t\t\n\t\telse:\n\t\t\tassert cname\n\t\t\tassert self._source\n\t\t\tself._trg_class = cname\n\t\t\treturn self.cfg['target'][self._source][self._trg_class]\n\t\t\t\n\tdef get_sval(self, key):\n\t\tscfg=self.scfg\n\t\tif self._source:\n\t\t\treturn scfg[self._source][key]\n\t\telse:\n\t\t\tassert key in scfg.keys(), 'Key \"%s\" is not in %s' % (key, scfg.keys())\n\t\t\treturn scfg[key]\n\n\t\t\n\tdef get_cfg(self, key):\n\n\t\tassert self._source\n\t\tclass_map={'source':self._src_class, 'dump': self._dmp_class, 'target': self._trg_class}\n\t\t#for k,v in class_map.items():\n\t\t#\t\tassert v, 'cli.%s config is not set' %k\n\t\t\n\t\tif self._source:\n\t\t\treturn self.cfg[key][self._source][class_map[key]]\n\t\telse:\n\t\t\tassert key in self.cfg.keys(), 'Key \"%s\" is not in %s' % (key, scfg.keys())\n\t\t\treturn self.cfg[key]\n\n\tdef set_target_table(self, tcfg, acct_date, fmt='%Y/%m/%d'):\n\t\t#//set acct_year, acct_mon for new target table naming\n\t\tif 'accountingDate' in tcfg and 'targetTableFmt' in tcfg:\n\t\t\tassert not tcfg[\"targetTable\"], 'If \"targetTable\" is set - you cannot set \"accountingDate\" and \"targetTableFmt\"'\n\t\t\tassert acct_date\n\t\t\tself.acct_year = self.get_acct_year(acct_date, fmt)\n\t\t\tself.acct_mon = self.get_acct_mon(acct_date, fmt) \n\t\t\tassert len(self.acct_year) == 4 \n\t\t\tassert len(self.acct_mon) == 2\n\t\t\ttcfg[\"targetTable\"] = self.get_parsed(ckey='targetTableFmt', cfg=tcfg)\n\t\t\tassert tcfg[\"targetTable\"]\n\t\telse:\n\n\t\t\tassert \"targetTable\" in tcfg\n\t\t\tassert tcfg[\"targetTable\"] , 'If \"targetTable\" is not set - you have to set \"accountingDate\" and \"targetTableFmt\"'\n\t\t\n\n\tdef get_acct_mon(self, acct_date, fmt):\n\t\tassert acct_date\n\t\tdo = datetime.strptime(acct_date, fmt)\n\t\treturn str(do.month).zfill(2)\n\tdef get_acct_year(self, acct_date, fmt):\n\t\tassert acct_date\n\t\tdo = datetime.strptime(acct_date, fmt)\n\t\treturn str(do.year)\n\tdef get_parsed(self, ckey, cfg):\n\t\tcli=self\n\n\t\tassert ckey\n\t\tassert cfg\n\t\tassert ckey in cfg, 'Key \"%s\" is not in cfg [%s]' % (ckey, cfg.keys())\n\t\tval= cfg.get(ckey, None)\n\t\tassert val , 'Key [%s] is not set in %s' % (ckey, cfg)\n\t\tif isinstance (val, (str, unicode)):\n\t\t\treturn val\n\t\telse:\n\t\t\tassert isinstance (val, list), 'Key [%s] value [%s] is not a list.' % (ckey, val)\n\t\t\tstmt, pcnt = val\n\t\t\tpars = re.findall(\"(\\{[0-9a-zA-Z_\\'\\'\\.\\*\\(\\)]+\\})\", stmt)\n\t\t\tfmt={}\n\t\t\tassert len(pars)==pcnt, '[%s]: Number of params in statement (%s) does not match declared params count (%s).' % (ckey, len(pars), pcnt)\n\t\t\tif pars:\n\t\t\t\tfor p in [p.strip('}').strip('{') for p in pars if p not in [ckey]]:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tassert p in cfg \\\n\t\t\t\t\t\tor p.lower().startswith('cli*') \\\n\t\t\t\t\t\tor p.split('*')[0] in cli.cfg \\\n\t\t\t\t\t\tor (p.lower().startswith('optparam_') and p.split('_')[1].isdigit()), \\\n\t\t\t\t\t\t'[%s]: SQL params should be json section keys or opt/proc param ids (optparam_nnn) or column param names (colparam_xxx) or cli atributes (cli*xxx)' % p\n\t\t\t\t\texcept:\n\t\t\t\t\t\tpp(cfg)\n\t\t\t\t\t\tpp(stmt)\n\t\t\t\t\t\tpp(p)\n\t\t\t\t\t\traise\n\t\t\t\t\tif p in cfg: \n\t\t\t\t\t\t\n\t\t\t\t\t\tfmt[p]= self.get_parsed(p, cfg=cfg); continue\n\t\t\t\t\tif p.lower().startswith('optparam_'): fmt[p]= cli.pa[int(p.split('_')[1])]; continue\n\t\t\t\t\tif p.split('*')[0] in cli.cfg:\n\t\t\t\t\t\tcname, key= p.split('*')\n\t\t\t\t\t\tassert cname\n\t\t\t\t\t\tassert key\n\t\t\t\t\t\tfmt[p]=cli.get_cfg(cname)[key]\n\t\t\t\t\t\tassert fmt[p]\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tif p.lower().startswith('cli*'):\n\t\t\t\t\t\tattr=p.split('*')[1]\n\t\t\t\t\t\tif attr.endswith('()'): #it's a method\n\t\t\t\t\t\t\tapi=attr[:-2]\n\t\t\t\t\t\t\tassert hasattr(cli, api), 'Cli has no attribute \"%s\" used in \"%s\":\\n%s' % (api, ckey,stmt)\n\t\t\t\t\t\t\tfmt[p]=eval('self.%s()' % api)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tassert hasattr(cli, attr), 'Cli has no attribute \"%s\" used in \"%s\":\\n%s' % (attr, ckey,stmt)\n\t\t\t\t\t\t\tfmt[p]=getattr(cli, attr)\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\n\t\t\t\tstmt = stmt.format(**fmt) \n\t\t\t\t\n\t\t\telse:\n\t\t\t\tpass\n\t\t\t\n\t\t\treturn stmt\n\n","sub_path":"include/cli/common/Cli.py","file_name":"Cli.py","file_ext":"py","file_size_in_byte":10419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"561659705","text":"import json\nimport urllib.request\nimport urllib.parse\nimport urllib.error\n\n\nclass ServerError(Exception):\n def __init__(self, code=None, msg=None):\n self.code = code\n self.msg = None\n\nclass Server:\n def __init__(self, base_url):\n self.base = base_url\n\n def query(self, url, parameters=None ):\n \"\"\"Charge l'url demandée. Si aucun paramètre n'est spécifié, une requête\n HTTP GET est envoyée. Si des paramètres sont présents, ils sont encodés\n en JSON, et une requête POST est envoyée.\n\n La méthode préconisée pour envoyer des paramètres consiste à les stocker\n dans un dictionnaire. Ceci permet de nommer les champs. Par exemple :\n\n # sans paramètres\n >>> server = Server(\"http://pac.bouillaguet.info/TP1/\")\n >>> response = server.query('client-demo')\n >>> print(response)\n Je n'ai pas reçu de paramètres\n\n # avec paramètres\n >>> parameters = {'login': 'toto', 'id': 1337}\n >>> response = server.query('client-demo', parameters)\n >>> print(response)\n Dans les paramètres j'ai trouvé :\n *) ``login'' : ``toto''\n *) ``id'' : ``1337''\n \n \"\"\"\n url = self.base + url\n try:\n request = urllib.request.Request(url)\n data = None\n if parameters is not None:\n data = json.dumps(parameters).encode()\n request.add_header('Content-type', 'application/json')\n with urllib.request.urlopen(request, data) as connexion:\n result = connexion.read().decode()\n if connexion.info()['Content-Type'] == \"application/json\":\n result = json.loads(result)\n return result\n except urllib.error.HTTPError as e:\n raise ServerError(e.code, e.read().decode()) from None\n\n","sub_path":"Master/S2/PAC_TP3/PS3/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"261513229","text":"#!/usr/bin/env python3\nimport numpy as np\nimport tensorflow as tf\nimport sys\nsys.path.append('.')\nfrom utils import dataset as data\n\n\nclass Network:\n def __init__(self, threads, seed=541):\n # Create an empty graph and a session\n graph = tf.Graph()\n graph.seed = seed\n self.session = tf.Session(\n graph=graph,\n config=tf.ConfigProto(\n inter_op_parallelism_threads=threads,\n intra_op_parallelism_threads=threads))\n\n def construct(self, args, num_tokens, num_labels):\n with self.session.graph.as_default():\n # Inputs\n self.tokens_ids = tf.placeholder(\n tf.int32, [None, None], name=\"tokens_ids\")\n self.terms_lens = tf.placeholder(\n tf.int32, [None], name=\"terms_lens\")\n self.labels = tf.placeholder(tf.int32, [None], name=\"labels\")\n\n # Token embeddings\n self.token_embeddings = tf.get_variable(\n \"token_embeddings\",\n shape=[num_tokens, args.embed_dim],\n dtype=tf.float32)\n inputs = tf.nn.embedding_lookup(self.token_embeddings,\n self.tokens_ids)\n\n # Computation\n # rnn_cell = tf.nn.rnn_cell.BasicLSTMCell\n rnn_cell = tf.nn.rnn_cell.GRUCell\n\n with tf.variable_scope('bi_rnn'):\n _, (state_fwd, state_bwd) = \\\n tf.nn.bidirectional_dynamic_rnn(\n rnn_cell(args.rnn_cell_dim),\n rnn_cell(args.rnn_cell_dim),\n inputs,\n sequence_length=self.terms_lens,\n dtype=tf.float32)\n\n state = tf.concat([state_fwd, state_bwd], axis=-1)\n #print('state shape :', state.get_shape())\n layers = [state] # TODO is it OK?\n for _ in range(args.num_dense_layers):\n layers.append(\n tf.layers.dense(layers[-1],\n args.dense_layer_units,\n activation=tf.nn.relu)\n )\n self.logits = tf.layers.dense(layers[-1], num_labels, name='logits')\n self.logits = tf.nn.softmax(self.logits)\n self.logits_0 = self.logits[:0] # TODO nicer\n self.predictions = tf.argmax(self.logits, axis=1, name='predictions')\n #predictions_shape = tf.shape(self.predictions)\n #print('self.predictions shape: ', self.predictions.get_shape())\n\n # Training\n loss = tf.losses.sparse_softmax_cross_entropy(\n self.labels, self.logits)\n global_step = tf.train.create_global_step()\n self.training = tf.train.AdamOptimizer().minimize(\n loss, global_step=global_step, name=\"training\")\n\n # Summaries\n self.current_accuracy, self.update_accuracy = tf.metrics.accuracy(\n self.labels, self.predictions)\n self.current_loss, self.update_loss = tf.metrics.mean(loss)\n self.reset_metrics = tf.variables_initializer(\n tf.get_collection(tf.GraphKeys.METRIC_VARIABLES))\n\n summary_writer = tf.contrib.summary.create_file_writer(\n args.logdir, flush_millis=10 * 1000)\n self.summaries = {}\n with summary_writer.as_default(), \\\n tf.contrib.summary.record_summaries_every_n_global_steps(10):\n self.summaries['train'] = [\n tf.contrib.summary.scalar(\n 'train/loss',\n self.update_loss),\n tf.contrib.summary.scalar(\n 'train/accuracy',\n self.update_accuracy)]\n with summary_writer.as_default(), \\\n tf.contrib.summary.always_record_summaries():\n self.summaries['valid'] = [\n tf.contrib.summary.scalar(\n 'valid/loss',\n self.current_loss),\n tf.contrib.summary.scalar(\n 'valid/accuracy',\n self.current_accuracy)]\n\n # Initialize variables\n self.session.run(tf.global_variables_initializer())\n with summary_writer.as_default():\n tf.contrib.summary.initialize(\n session=self.session, graph=self.session.graph)\n\n # Saver\n tf.add_to_collection('end_points/tokens_ids',\n self.tokens_ids)\n tf.add_to_collection('end_points/terms_lens',\n self.terms_lens)\n tf.add_to_collection('end_points/predictions',\n self.predictions)\n tf.add_to_collection('end_points/logits',\n self.logits)\n\n self.saver = tf.train.Saver()\n\n def save(self, path):\n return self.saver.save(self.session, path)\n\n def train_epoch(self, train_set, batch_size):\n while not train_set.epoch_finished():\n tokens_ids, terms_lens, labels = train_set.next_batch(batch_size)\n self.session.run(self.reset_metrics)\n self.session.run([self.training, self.summaries[\"train\"]],\n {self.terms_lens: terms_lens,\n self.tokens_ids: tokens_ids,\n self.labels: labels})\n\n def train_batch(self, batch):\n tokens_ids, terms_lens, labels = batch\n self.session.run(self.reset_metrics)\n self.session.run([self.training, self.summaries[\"train\"]],\n {self.terms_lens: terms_lens,\n self.tokens_ids: tokens_ids,\n self.labels: labels})\n\n def evaluate(self, dataset_name, dataset, batch_size):\n self.session.run(self.reset_metrics)\n while not dataset.epoch_finished():\n tokens_ids, terms_lens, labels = dataset.next_batch(batch_size)\n self.session.run([self.update_accuracy, self.update_loss],\n {self.terms_lens: terms_lens,\n self.tokens_ids: tokens_ids,\n self.labels: labels})\n return self.session.run(\n [self.current_accuracy, self.summaries[dataset_name]])[0]\n\n def embeddings(self):\n return self.session.run(self.token_embeddings)\n\nclass NetworkPredict:\n def __init__(self, threads=1, seed=541):\n # Create an empty graph and a session\n graph = tf.Graph()\n graph.seed = seed\n self.session = tf.Session(\n graph=graph,\n config=tf.ConfigProto(\n inter_op_parallelism_threads=threads,\n intra_op_parallelism_threads=threads))\n\n def load(self, path):\n # Load the metagraph\n with self.session.graph.as_default():\n self.saver = tf.train.import_meta_graph(path + '.meta')\n\n # Attach the end points\n self.tokens_ids = tf.get_collection(\n 'end_points/tokens_ids')[0]\n self.terms_lens = tf.get_collection(\n 'end_points/terms_lens')[0]\n self.predictions = tf.get_collection(\n 'end_points/predictions')[0]\n\n # Load the graph weights\n self.saver.restore(self.session, path)\n\n def predict(self, dataset_name, dataset):\n tokens_ids, terms_lens, = dataset.test()\n return self.session.run(self.predictions,\n {self.terms_lens: terms_lens,\n self.tokens_ids: tokens_ids})\n\nif __name__ == \"__main__\":\n import argparse\n import datetime\n import os\n import re\n\n # Fix random seed\n np.random.seed(541)\n\n # Parse arguments\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"--vocab\",\n type=str,\n help=\"Path to a vocabulary file.\")\n parser.add_argument(\n \"--train_set\",\n default='data/split/equiv.train',\n type=str,\n help=\"Path to a training set.\")\n parser.add_argument(\n \"--valid_set\",\n default='data/split/equiv.valid',\n type=str,\n help=\"Path to a validation set.\")\n parser.add_argument(\n \"--test_set\",\n default='',\n type=str,\n help=\"Path to a testing set.\")\n parser.add_argument(\n \"--model_path\",\n default='',\n type=str,\n help=\"Path where to save the trained model.\")\n parser.add_argument(\n \"--batch_size\",\n default=8,\n type=int,\n help=\"Batch size.\")\n parser.add_argument(\n \"--epochs\",\n default=8,\n type=int,\n help=\"Number of epochs.\")\n parser.add_argument(\n \"--embed_dim\",\n default=8,\n type=int,\n help=\"Token embedding dimension.\")\n parser.add_argument(\n \"--rnn_cell_dim\",\n default=8,\n type=int,\n help=\"RNN cell dimension.\")\n parser.add_argument(\n \"--num_dense_layers\",\n default=2,\n type=int,\n help=\"Number of dense layers.\")\n parser.add_argument(\n \"--dense_layer_units\",\n default=8,\n type=int,\n help=\"Number of units in each dense layer.\")\n parser.add_argument(\n \"--threads\",\n default=1,\n type=int,\n help=\"Maximum number of threads to use.\")\n parser.add_argument(\n \"--logdir\",\n default='',\n type=str,\n help=\"Logdir.\")\n args = parser.parse_args()\n\n if args.model_path:\n args.logdir = args.model_path\n else:\n if not args.logdir:\n # Create dir for logs\n if not os.path.exists(\"logs\"):\n os.mkdir(\"logs\")\n\n # Create logdir name\n args.logdir = \"logs/{}--{}--{}\".format(\n os.path.basename(__file__),\n datetime.datetime.now().strftime(\"%Y-%m-%d-%H%M%S\"),\n \",\".join(\n (\"{}={}\".format(\n re.sub(\"(.)[^_]*_?\", r\"\\1\", key), value) \\\n for key, value in sorted(vars(args).items()) \\\n if not '/' in str(value) \\\n and not 'threads' in key\n and not 'logdir' in key\n )\n )\n )\n\n print(\"The logdir is: {}\".format(args.logdir))\n\n # Load the data\n train_set = data.Dataset(args.train_set, args.vocab, shuffle_batches=True)\n valid_set = data.Dataset(args.valid_set, args.vocab, shuffle_batches=False)\n\n # Construct the network\n network = Network(threads=args.threads)\n network.construct(args, train_set.num_tokens, train_set.num_labels)\n\n # Train, batches\n print(\"Training started.\")\n for i in range(args.epochs):\n while not train_set.epoch_finished():\n batch = train_set.next_batch(args.batch_size)\n network.train_batch(batch)\n\n # Saving embeddings\n #embeddings = network.embeddings()\n #time = datetime.datetime.now().strftime(\"%H%M%S\")\n #file_name = args.logdir + '/embeddings_' + time + '.csv'\n #embeddings_to_write = '\\n'.join(\n # [','.join([str(round(j, 6)) for j in i]) for i in embeddings])\n #with open(file_name, 'w') as f:\n # f.write(embeddings_to_write + '\\n')\n accuracy = network.evaluate('valid', valid_set, args.batch_size)\n print(\"Accuracy on valid set after epoch {}: {:.2f}\".format(\n i + 1, 100 * accuracy))\n print(\"Training finished.\")\n\n # Save model\n model_path = network.save(args.logdir + '/model')\n print('Saved model path: ', model_path)\n\n if args.test_set:\n network = NetworkPredict()\n network.load(model_path)\n test = data.Dataset(args.test_set, args.vocab, test=True)\n p = network.predict('test', test)\n for i in p[:10]:\n print(i)\n\n\n","sub_path":"models_definitions/r-nn.py","file_name":"r-nn.py","file_ext":"py","file_size_in_byte":12168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"357167496","text":"#! usr/bin/python3\n# coding:utf-8\n\nimport os\n\nfile_dir=\"D:\\Python\\Python-master\\Python-master\"\nfor filename in os.listdir(file_dir):\n split_file =os.path.splitext(filename) #pathon.splitext(filename)返回的是元组,(filename,后缀名)\n print(split_file)\n file_ext=split_file[0]\n print(file_ext)","sub_path":"exercise_github/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"318913946","text":"\"\"\"\n==Task ==\nYou are given the year, and you have to write a function to check if the year is leap or not.\n\n==Input Format==\nRead y, the year that needs to be checked.\n\n==Constraints==\n1900 <= y <= 10^5\n\n==Output Format==\nOutput is taken care of by the template. Your function must return a boolean value (True/False)\n\"\"\"\n\ndef is_leap(year):\n leap = False\n \n if year % 4 == 0:\n if year % 100 == 0:\n if year % 400 == 0:\n leap = True\n else:\n leap = False\n else:\n leap = True\n \n return leap\n\nyear = int(input())\nprint(is_leap(year))","sub_path":"Python_Proficiency/Introduction/write_a_function.py","file_name":"write_a_function.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"126379553","text":"__author__ = 'jiangzhou xu'\nimport operator\nimport collections\ndef bull_and_cow(secret, guess):\n bull = sum(map(operator.eq, secret, guess))\n sa = collections.Counter(secret)\n sb = collections.Counter(guess)\n cow = sum((sa & sb).values()) - bull\n return str(bull) + 'A' + str(cow) + 'B'\n\nsecret = \"abcd\"\nguess = \"dbac\"\ntest = bull_and_cow(secret, guess)\nprint(test)\n","sub_path":"299_bull_and_cow.py","file_name":"299_bull_and_cow.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"399690379","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('falta', '0006_auto_20171109_1853'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='motivo',\n options={'verbose_name_plural': 'Motivos de falta'},\n ),\n ]\n","sub_path":"falta/migrations/0007_auto_20171111_1401.py","file_name":"0007_auto_20171111_1401.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"483274971","text":"class Solution:\n def countConsistentStrings(self, allowed: str, words: List[str]) -> int:\n allowedChars = set([char for char in allowed])\n\n goodWords = 0\n for word in words:\n isWordBad = False\n \n for char in word:\n \n if char not in allowedChars:\n isWordBad = True\n break\n if not isWordBad:\n goodWords += 1\n return goodWords","sub_path":"leetcode/1684.count-the-number-of-consistent-strings/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"363121674","text":"from pandas_datareader import data\nfrom datetime import date, timedelta\nfrom datetime import datetime\nimport datetime\nfrom dateutil.parser import parse\nimport csv\nimport sys\n\ncsv_file_path = \"data/stock_prices.csv\"\n\nprint(\"\\nSTOCK PRICE LOOKUP APPLICATION\")\nprint(\"Welcome! Today's date is: \" + str(datetime.date.today()))\nprint(\"\\nSelect one of the following options by inputting the corresponding number: \")\nprint(\"\\n1 - STOCK PRICE\")\nprint(\"2 - STOCK PERFORMANCE\")\n\noperation = input(\"\\nPlease make a selection: \")\n\nstock_symbols = []\n\ndef price_lookup():\n while True:\n symbol = input(\"\\nPlease select a stock by symbol or 'DONE' if there are no more items: \")\n symbol = symbol.upper()\n if symbol == \"DONE\":\n break\n else:\n stock_symbols.append(symbol)\n if len(stock_symbols) > 0:\n date_start = input(\"Please select an open-market start date in the format yyyy-mm-dd: \")\n end_date = input(\"Please select an open-market end date in the format yyyy-mm-dd: \")\n try:\n date_start = datetime.datetime.strptime(date_start, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n except ValueError:\n print(\"\\nIncorrect Date Format!\\n\")\n date_start = input(\"Please select an open-market start date in the format yyyy-mm-dd: \")\n end_date = input(\"Please select an open-market end date in the format yyyy-mm-dd: \")\n try:\n date_start = datetime.datetime.strptime(date_start, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n except ValueError:\n print(\"\\nIncorrect Date Format Again! Program Ending. \\n\")\n sys.exit()\n\n# COMPILE REQUEST PARAMS\n data_source = 'google'\n# ISSUE REQUEST\n response = data.DataReader(stock_symbols, data_source, date_start, end_date)\n# PARSE RESPONSE\n daily_closing_prices = response.ix[\"Close\"] # ix() is a pandas DataFrame function\n if daily_closing_prices.empty:\n print(\"\\nThe market was closed that day. Try a different date.\\n \")\n else:\n print(\"\\nHere are the Stock Prices for the days you indicated:\\n\")\n print(daily_closing_prices)\n confirmation = input(\"\\nWould you like to save this data to a file? (Y/N) \")\n confirmation = confirmation.upper()\n if confirmation == \"Y\":\n prices = daily_closing_prices.to_csv(csv_file_path)\n print(\"\\nGreat! The data has been saved to data/stock_prices.csv\\n\")\n else:\n print(\"\\nOK. The data is not saved\\n\")\n else:\n print(\"\\nOperation not selected. Ending program.\\n\")\n\ndef performance():\n symbol =input(\"Please select a stock by symbol: \")\n symbol = symbol.upper()\n stock_symbols.append(symbol)\n\n date_start = input(\"When did you buy the stock? Please select an open-market date and input in the format yyyy-mm-dd: \")\n end_date = input(\"When did you sell the stock? Please select an open-market date and input in the format yyyy-mm-dd: \")\n\n try:\n date_start = datetime.datetime.strptime(date_start, '%Y-%m-%d')\n end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n except ValueError:\n print(\"\\nIncorrect Date Format!\\n\")\n sys.exit()\n # date_start = input(\"Please select a start date in the format yyyy-mm-dd: \")\n # end_date = input(\"Please select an end date in the format yyyy-mm-dd: \")\n # date_start = datetime.datetime.strptime(date_start, '%Y-%m-%d')\n # end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')\n\n number_of_stocks = input(\"Please input quantity of shares owned: \")\n number_of_stocks = float(number_of_stocks)\n data_source = 'google'\n\n response = data.DataReader(stock_symbols, data_source, date_start, date_start)\n response2 = data.DataReader(stock_symbols, data_source, end_date, end_date)\n\n daily_closing_prices = response.ix[\"Close\"]\n daily_closing_prices2 = response2.ix[\"Close\"]\n if daily_closing_prices.empty or daily_closing_prices2.empty:\n print(\"\\nThe market was closed one or both of those days. Try a different date.\\n \")\n else:\n print(daily_closing_prices)\n print(daily_closing_prices2)\n\n difference = daily_closing_prices2.values-daily_closing_prices.values\n difference = float(difference)\n\n perform = number_of_stocks*difference\n\n if daily_closing_prices2.values > daily_closing_prices.values:\n print(\"\\nYour gain is: \" + str('${0:.2f}'.format(perform)))\n else:\n print(\"\\nYour loss is: \" + str('${0:.2f}'.format(abs(perform))))\n\nif operation == \"1\": price_lookup()\nelif operation == \"2\": performance()\nelse:\n print(\"PLEASE CHOOSE ONE OF THE AVAILABLE OPERATIONS\")\n","sub_path":"app/freestyle.py","file_name":"freestyle.py","file_ext":"py","file_size_in_byte":4863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"496449189","text":"# -*- coding: utf-8 -*-\nfrom flask import Flask, render_template, g, abort, jsonify\nimport sqlite3\nimport json\nimport os\nimport sys\n\n# configuration\nDATABASE = os.path.abspath(os.path.dirname(__file__)) + '/schema.db'\nDEBUG = True\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n\ndef connect_db():\n return sqlite3.connect(app.config['DATABASE'])\n\n@app.before_request\ndef before_request():\n g.db = connect_db()\n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close()\n\n@app.route(\"/recommendation/\")\ndef recommendation(id):\n result = g.db.execute('select reccomendation from game where id = ?', (id, ))\n recommendation_json = result.fetchone()\n if recommendation_json is None:\n abort(404)\n\n recommendation = json.loads(recommendation_json[0])\n result = g.db.execute('select id, name, image_url from game where id = ? or id = ? or id = ? or id = ? or id = ?',\n (recommendation[0], recommendation[1], recommendation[2], recommendation[3], recommendation[4]))\n recommendation = result.fetchall()\n return render_template('recommendation.html', recommendation=recommendation)\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"Web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"196617372","text":"from operator import itemgetter\nfrom itertools import count\nfrom collections import Counter, defaultdict\nimport random\nimport dynet as dy\nimport numpy as np\nimport re\nimport os\nimport pickle\nimport pdb\nimport copy\nimport time\nfrom reader import Reader, Vocab\nfrom tp import TransitionParser, LSTM, BiLSTM_CRF, TransitionParser2, TransitionParser_RBT, BiLSTM_SEMICRF\n\nfrom optparse import OptionParser\nimport random\n#from PYEVALB import scorer\n#from PYEVALB import parser as evalbparser\n#from termcolor import colored\nimport util\n\n\nusage = \"addr.py --train [inputfile] --test\"\n\nparser = OptionParser(usage=usage)\nparser.add_option(\"--data\", type=\"string\", help=\"data\", default=\"data\", dest=\"data\")\nparser.add_option(\"--train\", type=\"string\", help=\"train\", default=\"train.txt\", dest=\"train\")\nparser.add_option(\"--dev\", type=\"string\", help=\"dev\", default=\"dev.txt\", dest=\"dev\")\nparser.add_option(\"--test\", type=\"string\", help=\"test\", default=\"test.txt\", dest=\"test\")\nparser.add_option(\"--outputdir\", type=\"string\", help=\"outputdir\", default=\"output\", dest=\"outputdir\")\nparser.add_option(\"--emb\", type=\"string\", help=\"emb\", default=\"glove\", dest=\"emb\")\nparser.add_option(\"--task\", type=\"string\", help=\"task\", default=\"train\", dest=\"task\")\nparser.add_option(\"--epoch\", type=\"int\", help=\"epoch\", default=50, dest=\"epoch\")\nparser.add_option(\"--trial\", type=\"int\", help=\"trial\", default=0, dest=\"trial\")\nparser.add_option(\"--numtrain\", type=\"int\", help=\"numtrain\", default=-1, dest=\"numtrain\")\nparser.add_option(\"--numtest\", type=\"int\", help=\"numtest\", default=-1, dest=\"numtest\")\nparser.add_option(\"--debug\", type=\"int\", help=\"debug\", default=0, dest=\"debug\")\nparser.add_option(\"--os\", type=\"string\", help=\"os\", default=\"osx\", dest=\"os\")\nparser.add_option(\"--check_every\", type=\"int\", help=\"check_every\", default=1000, dest=\"check_every\")\nparser.add_option(\"--decay_patience\", type=\"int\", help=\"decay_patience\", default=3, dest=\"decay_patience\")\nparser.add_option(\"--lr_patience\", type=\"int\", help=\"lr_patience\", default=2, dest=\"lr_patience\")\nparser.add_option(\"--lr\", type=\"float\", help=\"lr\", default=0.1, dest=\"lr\")\nparser.add_option(\"--optimizer\", type=\"string\", help=\"optimizer\", default=\"sgd\", dest=\"optimizer\")\nparser.add_option(\"--dropout\", type=\"float\", help=\"dropout\", default=0.2, dest=\"dropout\")\nparser.add_option(\"--pretrain\", type=\"string\", help=\"pretrain\", default=\"none\", dest=\"pretrain\")\n\nparser.add_option(\"--WORD_DIM\", type=\"int\", help=\"WORD_DIM\", default=100, dest=\"WORD_DIM\")\nparser.add_option(\"--LSTM_DIM\", type=\"int\", help=\"LSTM_DIM\", default=200, dest=\"LSTM_DIM\")\nparser.add_option(\"--ACTION_DIM\", type=\"int\", help=\"ACTION_DIM\", default=200, dest=\"ACTION_DIM\")\nparser.add_option(\"--NUM_LAYER\", type=\"int\", help=\"NUM_LAYER\", default=2, dest=\"NUM_LAYER\")\n\nparser.add_option(\"--expname\", type=\"string\", help=\"expname\", default=\"default\", dest=\"expname\")\n\nparser.add_option(\"--trainsample\", type=\"int\", help=\"trainsample\", default=-1, dest=\"trainsample\")\nparser.add_option(\"--autolr\", type=\"int\", help=\"autolr\", default=0, dest=\"autolr\")\nparser.add_option(\"--normalize\", type=\"int\", help=\"normalize\", default=1, dest=\"normalize\")\nparser.add_option(\"--model\", type=\"string\", help=\"model\", default=\"TP\", dest=\"model\")\nparser.add_option(\"--lexicon\", type=\"string\", help=\"lexicon\", default=\"lexicon.txt\", dest=\"lexicon\")\nparser.add_option(\"--lexiconepoch\", type=\"int\", help=\"lexiconepoch\", default=0, dest=\"lexiconepoch\")\nparser.add_option(\"--syntactic_composition\", type=\"int\", help=\"syntactic_composition\", default=1, dest=\"syntactic_composition\")\nparser.add_option(\"--singleton\", type=\"int\", help=\"singleton\", default=1, dest=\"singleton\")\nparser.add_option(\"--MAXL\", type=\"int\", help=\"MAXL\", default=7, dest=\"MAXL\")\nparser.add_option(\"--MAXLLIMIT\", type=\"int\", help=\"MAXLLIMIT\", default=12, dest=\"MAXLLIMIT\")\n\n(options, args) = parser.parse_args()\n\nprint('Args:', options)\nemb_path = {'giga': 'giga.vec' + str(options.WORD_DIM)}\n\nif options.trial == 1:\n options.train = \"trial.txt\"\n options.dev = \"trial.txt\"\n options.test = \"trial.txt\"\n\n\nReader.load_lexicon(options.data, options.lexicon)\n\nlabel_list = Vocab.read_vocab_label()\n\nif options.model == 'TP_RBT':\n label_list = label_list + [x + \"'\" for x in label_list]\n\nlabel_opening_list = ['(' + x for x in label_list]\nvocab_label = Vocab.from_list(label_list)\nvocab_char, vocab_char_count = Vocab.read_vocab_char_from_list([os.path.join(options.data, options.train), os.path.join(options.data, options.dev), os.path.join(options.data, options.test), os.path.join(options.data, options.lexicon)]) #os.path.join(options.data, options.train)\n\nvocab_label_opening = Vocab.from_list(label_opening_list)\naction_list = ['APPEND', 'SEPARATE'] + ['LABEL(' + x + ')' for x in label_list]\nif options.model == 'TP2':\n action_list = ['APPEND'] + ['LABEL(' + x + ')' for x in label_list]\nvocab_action = Vocab.from_list(action_list)\nNUM_ACTIONS = vocab_action.size()\n\n\nif options.model == 'LSTM':\n label_list = ['B-' + x.lower() for x in label_list] + ['I-' + x.lower() for x in label_list]\n vocab_label = Vocab.from_list(label_list)\nelif options.model == 'CRF':\n label_list = ['B-' + x.lower() for x in label_list] + ['I-' + x.lower() for x in label_list] + ['', '']\n vocab_label = Vocab.from_list(label_list)\nelif options.model == 'SEMICRF':\n #label_list += ['', '']\n #label_list = ['town', 'community']\n vocab_label = Vocab.from_list(label_list)\n\nprint('label_list:',label_list)\nreader = Reader(vocab_char, vocab_label, vocab_action, options)\n\n\n\n# mylist = ['B-prov', 'I-prov', 'B-city', 'I-city', 'B-district', 'B-road']\n# print('mylist:',mylist)\n# print(colored('vocab_action:', 'red'),vocab_action.w2i[\"LABEL(prov')\"])\n# action_seq = util.get_action_seq_rbt(mylist, vocab_action)\n# action_seq = [vocab_action.i2w[x] for x in action_seq]\n# print('action_seq:',action_seq)\n#\n# print(colored('action2chunk_rbt:', 'red'), util.action2chunk_rbt(action_seq))\n# exit()\n\ntrain = reader.read_file(os.path.join(options.data, options.train), 'train')\ndev = reader.read_file(os.path.join(options.data, options.dev),'eval')\ntest = reader.read_file(os.path.join(options.data, options.test),'eval')\n\nif options.lexiconepoch > 0:\n lexicon = reader.read_file(os.path.join(options.data, options.lexicon),'train')\n\ntrain = train[:options.numtrain]\ndev = dev[:options.numtest]\ntest = test[:options.numtest]\n\nprint('Data Reading completed.')\nprint('len(train):', len(train), ' MAXL:', options.MAXL, end='')\nprint(' len(dev):', len(dev),' len(test):', len(test), end='')\nif options.lexiconepoch > 0:\n print(' len(lexicon):', len(lexicon), end='')\nprint()\n\npretrain_emb = None\nif options.pretrain != 'none':\n pretrain_emb = reader.load_pretrain(os.path.join(options.data, emb_path[options.pretrain]), True)\n\n\nmodel_filename = os.path.join(options.outputdir, 'addr_' + options.expname + '.model')\ndev_output = model_filename.replace('.model', '.dev.out')\ntest_output = model_filename.replace('.model', '.test.out')\n\nprint('The model/output will be saved as ', model_filename, dev_output, test_output)\n\nmodel = dy.ParameterCollection() # dy.Model()\n\nif options.optimizer == 'adam':\n trainer = dy.AdamTrainer(model)\nelse:\n trainer = dy.SimpleSGDTrainer(model) #dy.AdamTrainer(model)\n\ntrainer.set_learning_rate(options.lr)\n\nif options.model == 'TP' :\n parser = TransitionParser(model, options, vocab_char, vocab_char_count, vocab_label, vocab_label_opening, vocab_action, pretrain_emb)\nelif options.model == 'TP2':\n parser = TransitionParser2(model, options, vocab_char, vocab_char_count, vocab_label, vocab_label_opening, vocab_action, pretrain_emb)\nelif options.model == 'TP_RBT':\n parser = TransitionParser_RBT(model, options, vocab_char, vocab_char_count, vocab_label, vocab_label_opening, vocab_action, pretrain_emb)\n\nelif options.model == 'LSTM':\n parser = LSTM(model, options, vocab_char, vocab_char_count, vocab_label, pretrain_emb)\nelif options.model == 'CRF':\n parser = BiLSTM_CRF(model, options, vocab_char, vocab_char_count, vocab_label, pretrain_emb)\nelif options.model == 'SEMICRF':\n options.MAXL = reader.options.MAXL\n print('MAXL is set to ', options.MAXL)\n parser = BiLSTM_SEMICRF(model, options, vocab_char, vocab_char_count, vocab_label, pretrain_emb)\nelse:\n print('Model ' + options.model + ' is not specified.')\n exit()\n\n\ndef train_lexicon(lexicon, max_epoch, sample = 1000):\n i = 0\n for epoch in range(max_epoch):\n words = 0\n total_loss = 0.0\n\n random.shuffle(lexicon)\n\n for inst in lexicon[:sample]:\n i += 1\n\n loss = parser.parse(inst, inst[\"action\"])\n words += len(inst[\"raw_char\"])\n if loss is not None:\n total_loss += loss.scalar_value()\n loss.backward()\n trainer.update()\n e = float(i) / sample\n\n if i % sample == 0:\n print('lexicon epoch {}: per-inst loss: {}'.format(e, total_loss / words), flush=True)\n words = 0\n total_loss = 0.0\n\n\n\n\ndef sampletrain(train, dev, test, sample = 100, shuffle = True):\n early_counter = 0\n decay_counter = 0\n\n best_f1 = 0\n # best_model = copy.deepcopy(model)\n\n i = 0\n print('Training starts...', flush=True)\n\n for epoch in range(options.epoch):\n words = 0\n total_loss = 0.0\n if shuffle:\n random.shuffle(train)\n totrain = train[:sample]\n for inst in totrain:\n i += 1\n\n loss = parser.parse(inst, inst[\"action\"])\n words += len(inst[\"raw_char\"])\n if loss is not None:\n total_loss += loss.scalar_value()\n loss.backward()\n trainer.update()\n e = float(i) / len(totrain)\n\n if i % len(totrain) == 0:\n print('epoch {}: per-inst loss: {}'.format(e, total_loss / words), flush=True)\n words = 0\n total_loss = 0.0\n\n if i >= len(totrain) * 2 and i % options.check_every == 0:\n p, r, f1 = parser.predict(dev, dev_output)\n if best_f1 < f1:\n best_f1 = f1\n # best_model = model\n print('Better F1:', best_f1)\n # best_model = copy.deepcopy(model)\n print('Saving model to ', model_filename, '...')\n model.save(model_filename)\n early_counter = 0\n\n print('On Test:')\n p, r, f1 = parser.predict(test, test_output)\n\n else:\n early_counter += 1\n if early_counter > options.lr_patience:\n decay_counter += 1\n early_counter = 0\n if decay_counter > options.decay_patience:\n break\n else:\n # adjust_learning_rate(trainer)\n cur_lr = trainer.learning_rate\n # adj_lr = cur_lr / 2\n adj_lr = cur_lr * 0.7\n if options.autolr == 1:\n trainer.set_learning_rate(adj_lr)\n print(\"Adjust lr to \", adj_lr)\n\nif options.task == 'train':\n\n if options.lexiconepoch > 0:\n train_lexicon(lexicon, options.lexiconepoch)\n\n sample = len(train) if options.trainsample == -1 else options.trainsample\n sampletrain(train, dev, test, sample, True)\n\nprint('Loading model from ',model_filename, ' ...')\nmodel.populate(model_filename)\nprint('The model is loaded.')\n\nprint('Dev ', end='')\np, r, f1 = parser.predict(dev, dev_output)\n#print('F1:', f1)\nutil.eval_by_script(dev_output)\n\nprint('Test ', end='')\np, r, f1 = parser.predict(test, test_output)\n#print('F1:', f1)\nutil.eval_by_script(test_output)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"155707614","text":"from abc import ABC\n\n\nclass Setting(ABC):\n \"\"\"\n Abstract Base class for settings. It's here to potentially extend the setting functionality in future.\n \"\"\"\n def __init__(self):\n pass\n\n\nclass MetaDictSetting(Setting):\n \"\"\"\n Implements an interface for a default meta_dict with optional mandatory fields\n \"\"\"\n def __init__(self, meta_dict: dict, mandatory_fields: list = []):\n self.meta_dict = meta_dict\n self.mandatory_fields = mandatory_fields\n\n\nDEFAULT_SETTING_INVARIANT_NET = MetaDictSetting(\n meta_dict={\n 'n_dense_s1': 2,\n 'n_dense_s2': 2,\n 'n_dense_s3': 2,\n 'n_equiv': 2,\n 'dense_s1_args': {'activation': 'relu', 'units': 32},\n 'dense_s2_args': {'activation': 'relu', 'units': 64},\n 'dense_s3_args': {'activation': 'relu', 'units': 32}\n },\n mandatory_fields=[]\n)\n\n\nDEFAULT_SETTING_INVERTIBLE_NET = MetaDictSetting(\n meta_dict={\n 'n_coupling_layers': 4,\n 's_args': {\n 'units': [128, 128],\n 'activation': 'elu',\n 'initializer': 'glorot_uniform',\n },\n 't_args': {\n 'units': [128, 128],\n 'activation': 'elu',\n 'initializer': 'glorot_uniform',\n },\n 'alpha': 1.9,\n 'permute': True\n },\n mandatory_fields=[\"n_params\"]\n)","sub_path":"bayesflow/default_settings.py","file_name":"default_settings.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"368018006","text":"import crnt4sbml\n\nnetwork = crnt4sbml.CRNT(\"../sbml_files/double_insulin_binding.xml\")\n\nnetwork.basic_report()\n\nnetwork.print_c_graph()\n\nldt = network.get_low_deficiency_approach()\nldt.report_deficiency_zero_theorem()\nldt.report_deficiency_one_theorem()\n\nopt = network.get_mass_conservation_approach()\n\nprint(\"Decision Vector:\")\nprint(opt.get_decision_vector())\nprint(\"\")\n\nprint(\"Species for concentration bounds:\")\nprint(opt.get_concentration_bounds_species())\n\nbounds = [(1e-8, 1e-4), (1e-5, 1e-3), (1e-8, 1e-4), (1e-5, 1e-3), (1e-8, 1e-4), (1e-5, 1e-3), (1e-3, 1.0), (1e-8, 1e-4),\n (1e-5, 1e-3), (1e-3, 1.0), (1e-3, 1.0), (5e-1, 5e5), (5e-1, 5e5), (5e-1, 5e5)]\nconcentration_bounds = [(5e-1, 5e5)]*5\n\nparams_for_global_min, obj_fun_val_for_params = opt.run_optimization(bounds=bounds,\n concentration_bounds=concentration_bounds,\n iterations=100)\n\nmultistable_param_ind, plot_specifications = opt.run_continuity_analysis(species=\"s5\",\n parameters=params_for_global_min,\n auto_parameters={'DSMAX': 1e3,\n 'PrincipalContinuationParameter': \"C2\",\n 'RL0': 1e2, 'RL1': 1e6,\n 'A0': 0, 'A1': 5e6})\n\nopt.generate_report()\n","sub_path":"example_scripts/run_double_insulin_binding.py","file_name":"run_double_insulin_binding.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"145906603","text":"# import necessary libraries\nimport os\nimport numpy as np\nfrom sqlalchemy.sql import text\nfrom sqlalchemy import bindparam\nfrom flask import (\n Flask,\n render_template,\n jsonify,\n request,\n redirect)\n\n#################################################\n# Flask Setup\n#################################################\napp = Flask(__name__)\n\n#################################################\n# Database Setup\n#################################################\n\nfrom flask_sqlalchemy import SQLAlchemy\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://postgres:Yas.123@localhost:5432/Parking_db'\n# Remove tracking modifications\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\ndb = SQLAlchemy(app)\n\n\n# create route that renders index.html template\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n@app.route(\"/map\")\ndef map():\n return render_template(\"map.html\")\n\n@app.route(\"/visualize\")\ndef plot():\n return render_template(\"visualize.html\") \n\n@app.route(\"/data\")\ndef data():\n return render_template(\"loaddata.html\")\n\n@app.route(\"/filter\")\ndef filter():\n results = db.engine.execute(text(\"\"\"\n SELECT area_name\n FROM \"Area\"\n \"\"\")\n )\n return jsonify([dict(row) for row in results]) \n\n\n@app.route(\"/api/\")\ndef area(area):\n results = db.engine.execute(text(\"\"\"\n SELECT p.bay_id, d.durationminutes\n FROM \"Parking_bay\" as p\n LEFT JOIN \"Parking_duration\" as d\n ON p.bay_id = d.bay_id\n LEFT JOIN \"Area\" as y\n ON p.areaname_id = y.area_id\n where y.area_name = :area\n \"\"\").bindparams(\n area=area.lower()\n ))\n return jsonify([dict(row) for row in results])\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"300360405","text":"\"\"\"Desafio 054: Crie um programa que leia o ano de nascimento de sete pessoas.\nNo final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.\"\"\"\nfrom datetime import date\natual = date.today().year\ntotalmaior = 0\ntotalmenor = 0\nfor pess in range(1, 8):\n nasc = int(input('Em que ano a {}ª pessoa nasceu? '.format(pess)))\n idade = atual - nasc\n print('A {}ª pessoa tem {} anos!' .format(pess, idade))\n if idade >= 21:\n totalmaior += 1\n else:\n totalmenor += 1\nprint('Ao todo tivemos {} pessoa(s) maior/maiores de idade!'.format(totalmaior))\nprint('E também tivemos {} pessoa(s) menor/menores de idade!'.format(totalmenor))","sub_path":"Desafio 054.py","file_name":"Desafio 054.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"88579200","text":"\n\nfrom xai.brain.wordbase.nouns._bathrobe import _BATHROBE\n\n#calss header\nclass _BATHROBES(_BATHROBE, ):\n\tdef __init__(self,): \n\t\t_BATHROBE.__init__(self)\n\t\tself.name = \"BATHROBES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"bathrobe\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_bathrobes.py","file_name":"_bathrobes.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"243590169","text":"from numpy import append, ones, exp, sqrt, mean, square\nfrom gpkit.nomials import (Posynomial, Monomial, PosynomialInequality,\n MonomialEquality)\nfrom implicit_softmax_affine import implicit_softmax_affine\nfrom softmax_affine import softmax_affine\nfrom max_affine import max_affine\nfrom LM import LM\nfrom generic_resid_fun import generic_resid_fun\nfrom max_affine_init import max_affine_init\nfrom print_fit import print_ISMA, print_SMA, print_MA\n\ndef fit(xdata, ydata, K, ftype=\"ISMA\", varNames=None):\n '''\n Fits a log-convex function to multivariate data and returns a GP-compatible constraint\n\n INPUTS\n xdata: Independent variable data \n 2D numpy array [nDim, nPoints]\n [[<--------- x1 ------------->]\n [<--------- x2 ------------->]]\n\n ydata: Dependent variable data\n 1D numpy array [nPoints,]\n [<---------- y ------------->]\n\n K: Number of terms in the fit\n integer > 0\n\n ftype: Fit type\n one of the following strings: \"ISMA\" (default), \"SMA\" or \"MA\"\n\n varNames: List of variable names strings\n Independent variables first, with dependent variable at the end\n Default value: ['u_1', 'u_2', ...., 'u_d', 'w']\n\n OUTPUTS\n cstrt: GPkit PosynomialInequality object\n For K > 1, this will be a posynomial inequality constraint\n If K = 1, this is automatically made into an equality constraint\n If MA fit and K > 1, this is a list of constraint objects\n\n rmsErr: RMS error\n Root mean square error between original (not log transformed)\n data and function fit.\n '''\n\n # Check data is in correct form\n if ydata.ndim > 1:\n raise ValueError('Dependent data should be in the form of a 1D numpy array')\n\n # Transform to column vector\n ydata = ydata.reshape(ydata.size,1)\n\n if xdata.ndim == 1:\n xdata = xdata.reshape(xdata.size,1)\n else:\n xdata = xdata.T\n\n # Dimension of function (number of independent variables)\n d = xdata.shape[1]\n\n # Create varNames if None\n if varNames == None:\n varNames = []\n for i in range(d):\n varNames.append('u_{0:d}'.format(i+1))\n varNames.append('w')\n\n # Initialize fitting variables\n alphainit = 10\n bainit = max_affine_init(xdata, ydata, K)\n\n if ftype == \"ISMA\":\n\n def rfun (p):\n return generic_resid_fun(implicit_softmax_affine, xdata, ydata, p)\n [params, RMStraj] = LM(rfun, append(bainit.flatten('F'), alphainit*ones((K,1))))\n\n # Approximated data\n y_ISMA, _ = implicit_softmax_affine(xdata, params)\n w_ISMA = exp(y_ISMA)\n\n # RMS error\n w = (exp(ydata)).T[0]\n #rmsErr = sqrt(mean(square(w_ISMA-w)))\n rmsErr = sqrt(mean(square(y_ISMA-ydata.T[0])))\n\n alpha = 1./params[range(-K,0)]\n\n # A: exponent parameters, B: coefficient parameters\n A = params[[i for i in range(K*(d+1)) if i % (d + 1) != 0]]\n B = params[[i for i in range(K*(d+1)) if i % (d + 1) == 0]]\n\n print_str = print_ISMA(A, B, alpha, d, K)\n\n # Calculate c's and exp's for creating GPkit objects\n cs = []\n exps = []\n for k in range(K):\n cs.append(exp(alpha[k] * B[k]))\n expdict = {}\n for i in range(d):\n expdict[varNames[i]] = alpha[k] * A[k*d + i]\n expdict[varNames[-1]] = -alpha[k]\n exps.append(expdict)\n \n cs = tuple(cs)\n exps = tuple(exps)\n\n # Create gpkit objects\n # ISMA returns a constraint of the form 1 >= c1*u1^exp1*u2^exp2*w^(-alpha) + ....\n posy = Posynomial(exps, cs)\n cstrt = (posy <= 1)\n\n # # If only one term, automatically make an equality constraint\n if K == 1:\n cstrt = MonomialEquality(cstrt, \"=\", 1)\n\n elif ftype == \"SMA\":\n\n def rfun (p):\n return generic_resid_fun(softmax_affine, xdata, ydata, p)\n [params, RMStraj] = LM(rfun, append(bainit.flatten('F'), alphainit))\n\n # Approximated data\n y_SMA, _ = softmax_affine(xdata, params)\n w_SMA = exp(y_SMA)\n\n # RMS error\n w = (exp(ydata)).T[0]\n #rmsErr = sqrt(mean(square(w_SMA-w)))\n rmsErr = sqrt(mean(square(y_SMA-ydata.T[0])))\n\n alpha = 1./params[-1]\n\n A = params[[i for i in range(K*(d+1)) if i % (d + 1) != 0]]\n B = params[[i for i in range(K*(d+1)) if i % (d + 1) == 0]]\n\n print_str = print_SMA(A, B, alpha, d, K)\n\n # Calculate c's and exp's for creating GPkit objects\n cs = []\n exps = []\n for k in range(K):\n cs.append(exp(alpha * B[k]))\n expdict = {}\n for i in range(d):\n expdict[varNames[i]] = alpha * A[k*d + i]\n exps.append(expdict)\n \n cs = tuple(cs)\n exps = tuple(exps)\n\n # Creates dictionary for the monomial side of the constraint\n w_exp = {varNames[-1]: alpha}\n\n # Create gpkit objects\n # SMA returns a constraint of the form w^alpha >= c1*u1^exp1 + c2*u2^exp2 +....\n posy = Posynomial(exps, cs)\n mono = Monomial(w_exp, 1)\n cstrt = (mono >= posy)\n\n # # If only one term, automatically make an equality constraint\n if K == 1:\n cstrt = MonomialEquality(cstrt, \"=\", 1)\n\n\n elif ftype == \"MA\":\n\n def rfun(p):\n return generic_resid_fun(max_affine, xdata, ydata, p)\n [params, RMStraj] = LM(rfun, bainit.flatten('F'))\n\n # Approximated data\n y_MA, _ = max_affine(xdata, params)\n w_MA = exp(y_MA)\n\n # RMS error\n w = (exp(ydata)).T[0]\n #rmsErr = sqrt(mean(square(w_MA-w)))\n rmsErr = sqrt(mean(square(y_MA-ydata.T[0])))\n\n A = params[[i for i in range(K*(d+1)) if i % (d + 1) != 0]]\n B = params[[i for i in range(K*(d+1)) if i % (d + 1) == 0]]\n\n print_str = print_MA(A, B, d, K)\n\n w_exp = {varNames[-1]: 1}\n mono1 = Monomial(w_exp,1)\n\n cstrt = []\n for k in range(K):\n cs = exp(B[k])\n\n exps = {}\n for i in range(d):\n exps[varNames[i]] = A[k*d + i]\n mono2 = Monomial(exps, cs)\n cstrt1 = PosynomialInequality(mono2, \"<=\", mono1)\n cstrt.append(cstrt1)\n\n if K == 1:\n cstrt = MonomialEquality(mono2, \"=\", mono1)\n\n return cstrt, rmsErr\n\n","sub_path":"gpfit/fit.py","file_name":"fit.py","file_ext":"py","file_size_in_byte":6730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"498199647","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 26 14:21:24 2018\n\n@author: iris\n\"\"\"\n\n\nfrom Traitement_fich import*\n\ntime=60 #Au debut\n\nchemin ='/Users/iris/Desktop/Projet_Rech/Exemple/EEG_58_Sig/Donnes_signaux/' #à changer selon les ordinateurs\n\nT=[round(i/512,6) for i in range(1,time*512+1)]\n\ncharB=chemin+\"B3-B2N3_60s.txt\"\ncharO=chemin+\"O'9-O'8N3_60s.txt\"\n##Afin de pouvoir étudier les motifs sur un nouvel alogrithme, on veut avoir \n\n#On extrait la série temporelle brut : #\n#Pour B\n#YB=open_data(charB)[0:time*512]\n#YO=open_data(charO)[0:time*512]\n\n#On extrait la série en puissance il faut qu'elle soit de la même longueur\nPB=calc_puiss(charB,T,h=1,opt='ripples')[0] #on choisit de faire un pas de 1\nPO=calc_puiss(charO,T,h=1,opt='delta')[0]\n#aff_puiss(chemin+charB,T,h=5,opt='ripples')\n\nfich1=open(\"puiss\"+charB[66:-4]+\".txt\",\"w\")\nfich1.write('Puissance du signal\\n')\nfich1.write(charB[66:-4]+'\\n')\nfor elem in PB : \n fich1.write(str(elem)+'\\n')\nfich1.close()\n\nfich2=open(\"puiss\"+charO[66:-4]+\".txt\",\"w\")\nfich2.write('Puissance du signal\\n')\nfich2.write(charO[66:-4]+'\\n')\nfor elem in PO : \n fich2.write(str(elem)+'\\n')\nfich2.close()\n\n#Construction D'un vecteur de 0 et de 1 correspondant à l'apparition de sharpw\n\nVB=vect_detect_pic(charB,T,'ripples',3,15)\nprint(len(VB))\nfich3=open(\"Vect_pic\"+charB[66:-4]+\".txt\",\"w\")\nfich3.write('Detection de pic en amplitude \\n')\nfich3.write(charB[66:-4]+'\\n')\nfor elem in VB : \n fich3.write(str(elem)+'\\n')\nfich3.close()\n#Construction d'un vecteur de 0 et de 1 caractérisant la présence de pic delta\n##Detection des pics delta de la même manière que l'on a détecté les sharp waves ripples\nVO=vect_detect_pic(charO,T,'delta',2,100)\nfich4=open(\"Vect_pic\"+charO[66:-4]+\".txt\",\"w\")\nfich4.write('Detection de pic en amplitude \\n')\nfich4.write(charO[66:-4]+'\\n')\nfor elem in VO : \n fich4.write(str(elem)+'\\n')\nfich4.close()\n#Construction d'un vecteur de 0 et de 1 caractérisant la présence de pic delta\n\n\n#vecteur pour la phase : \nphi=phase_delta(charB,charO,T,1)\nfich5=open(\"Phase_\"+charO[66:-4]+\".txt\",\"w\")\nfich5.write('Phase \\n')\nfich5.write(charO[66:-4]+'\\n')\nfor elem in phi : \n fich5.write(str(elem)+'\\n')\nfich5.close()\n","sub_path":"Creation_serieT.py","file_name":"Creation_serieT.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"525251873","text":"# Copyright 2018 Jetperch 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\nclass Parameter:\n \"\"\"Define a single parameter accessible by the application.\n\n :param name: The parameter name.\n :param permission: The parameter permission which is either\n 'r' (read-only) or 'rw' (read-write).\n :param path: None if the parameter is only changed at the streaming start.\n 'setting' if the parameter is part of the settings packet.\n :param default: The default value.\n :param values: The list of acceptable values as ('name', value, ['alias1', ...]) tuples.\n :param units: The units string for the parameter.\n \"\"\"\n def __init__(self, name, permission, path, default, values, units=None):\n self.name = name\n self.permission = permission\n self.default = default\n self.path = path\n self.values = []\n self.str_to_value = {}\n self.units = units\n if permission not in ['rw', 'r']:\n raise ValueError('Parameter %s, invalid permission %r' % (name, permission))\n if values is None:\n return\n for idx, value in enumerate(values):\n if len(value) < 2 or len(value) > 3:\n raise ValueError('Parameter %s, value %d invalid: %r' % (name, idx, value))\n vname = value[0]\n vvalue = value[1]\n if not isinstance(vname, str):\n raise ValueError('Parameter %s, value %d invalid name %r' % (name, idx, vname))\n if len(value) == 2:\n value = (vname, vvalue, [])\n self.values.append(value)\n self._insert(vname, vvalue)\n for alias in value[2]:\n self._insert(alias, vvalue)\n\n if default not in [x[0] for x in values]:\n raise ValueError('Parameter %s, default %r not in ' % (name, permission))\n\n def _insert(self, key, value):\n if key in self.str_to_value:\n raise ValueError('Parameter %s: key %s already exists' % (self.name, key))\n self.str_to_value[key] = value\n","sub_path":"joulescope/parameter.py","file_name":"parameter.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"232449182","text":"#!/usr/bin/python3\n# -*- coding:utf-8 -*-\n#Author:lyf\n#Datetime:2020-8-16\n#Filename:main.py\n\n\nimport time\nfrom movie_db_ctl import movie_db\nfrom get_movie_url import get_movie_url\nfrom setting import web_site, web_site_dir\n\n'''\n简易电影天堂最新电影爬虫\n可以从第二页开始自动翻页爬取\n待解决问题:1,补充下载链接类型(解决)\n 2,抽取常量字符串(解决)\n 3,需要改为多线程版本增加效率 \n 4,爬取下一页时应改为正则表达式匹配下一页!\n'''\n\ndef main():\n start = time.time()\n i = 2 #设置开始页数\n\n while True:\n website_url = f'{web_site}{web_site_dir}/index_{i}.html'\n # print(website_url)\n print(f'第{i}页开始。。。')\n #获取字典\n movie_info_dict = get_movie_url(website_url)\n mb = movie_db()\n \n #循环插入数据库\n for k in movie_info_dict:\n if not mb.is_exist(k, movie_info_dict[k]):\n mb.movie_insert(k, movie_info_dict[k])\n else:\n continue\n print(f'已完成第{i}页')\n print('*'*100)\n print('\\n')\n i += 1\n if i > 312:\n break\n print(f'总共{i}页已完成')\n mb.db_close()\n end = time.time()\n print(str(end - start))\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"简易爬虫电影天堂最新电影/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"405075787","text":"from pyowm import OWM\nfrom datetime import datetime, date, time\n\nowm = OWM('c7ad9f76285435e69219354c33a7f859')\n\n'''reg = owm.city_id_registry()\nobs = owm.weather_at_id(5107152)\nprint(owm.weather_at_id(5107152))'''\n\n'''fc = owm.daily_forecast('Moscow, ru', limit=5)\n\nf = fc.get_forecast()\n\nlst = f.get_weathers()'''\n\nreg = owm.city_id_registry()\n\nlist = reg.ids_for('London')\nfor country in list:\n print(country[2])\n\nprint(' ')\n\nu_city = []\nfor city in list:\n f = 1\n if len(u_city) == 0:\n u_city.append(city)\n continue\n for obj_city in u_city:\n if city[2] == obj_city[2]:\n f = 0\n\n if f == 1:\n u_city.append(city)\n\nfor country in u_city:\n print(country[2])\n\n'''weather = obs.get_weather()\nprint(weather.get_temperature(unit='celsius')['temp'])'''","sub_path":"weather/Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"109852300","text":"\"\"\"Control your mrj3 via serial port.\n\n.. moduleauthor:: John Brodie \n\n\"\"\"\nfrom time import sleep\nimport json\nimport os\nimport logging\n\nimport serial\n\nimport array\nimport re\nimport shlex\n\nPATH = os.path.abspath(os.path.dirname(__file__)) + '/mrj3_configs/'\n\n\nBLU = '\\u001b[44;1m'\nCYN = '\\u001b[46;1m'\nGRN = '\\u001b[42;1m'\nMGT = '\\u001b[45;1m'\nRED = '\\u001b[41;1m'\nYEL = '\\u001b[43;1m'\nREVERSE = '\\u001b[7m'\nNORM = '\\u001b[0m'\n\nsSOH = '\\\\x01'\nsSTX = '\\\\x02'\nsETX = '\\\\x03'\nsEOT = '\\\\x04'\nuSOH = BLU + \"\\u210f\" + NORM # h-bar character w/ red background\nuSTX = BLU + \"\\u03b1\" + NORM # Greek alpha character w/ red background\nuETX = BLU + '\\u03c9' + NORM;\nrePatternSoh = sSOH + '(\\\\w)' + '([\\\\w ]+)' + sSTX + '(\\\\w.)' + '([\\\\w ]*)' + sETX + '([\\\\w ]+)'\nreSubStrSoh =\\\n uSOH + REVERSE + \"\\\\1\" + NORM + GRN + \"\\\\2\" + NORM + uSTX + GRN + '\\\\3' + NORM + \"\\\\4\" + uETX + YEL + \"\\\\5\" + NORM\n\"\"\"STX+Sta+Err+[Data]+ETX+Chk\"\"\" \"\"\"Data field is optional\"\"\"\nrePatternStx = sSTX + '(\\\\w)' + '(\\\\w)' + '(.*)' + sETX + '(\\\\w+)'\nreSubStrStx = uSTX + REVERSE + \"\\\\1\" + NORM + YEL + \"\\\\2\" + NORM + \"\\\\3\" + uETX + YEL + \"\\\\4\" + NORM\n\nclass CommandFailedError(Exception):\n \"\"\"A command failed, usually due to an invalid state change.\"\"\"\n\n\nclass CommandExceptionError(Exception):\n \"\"\"An executed command caused the device to return an error.\"\"\"\n\n\nclass InvalidConfigError(Exception):\n \"\"\"Loading the configuration failed as it is invalid.\"\"\"\n\n\nclass DeviceConfigMissingError(Exception):\n \"\"\"The specified device has no associated config file.\"\"\"\n\n\nclass InvalidCommandError(Exception):\n \"\"\"The given command or action is invalid for the specified device.\"\"\"\n\n\nclass Mrj3(object):\n\n possible_pyserial_settings = [\n 'port', 'baudrate', 'bytesize', 'parity', 'stopbits', 'timeout',\n 'xonxoff', 'rtscts', 'dsrdtr', 'writeTimeout', 'InterCharTimeout',\n ]\n pyserial_config_converter = {\n 'bytesize': {\n 5: serial.FIVEBITS,\n 6: serial.SIXBITS,\n 7: serial.SEVENBITS,\n 8: serial.EIGHTBITS,\n },\n 'parity': {\n 'none': serial.PARITY_NONE,\n 'even': serial.PARITY_EVEN,\n 'odd': serial.PARITY_ODD,\n 'mark': serial.PARITY_MARK,\n 'space': serial.PARITY_SPACE,\n },\n 'stopbits': {\n 1: serial.STOPBITS_ONE,\n 1.5: serial.STOPBITS_ONE_POINT_FIVE,\n 2: serial.STOPBITS_TWO,\n },\n\n }\n\n def __init__(\n self,\n port=None,\n device_id='benq',\n **kwargs\n ):\n \"\"\"Initialize a new Mrj3 object.\n\n :param port: The device name or port number your device is connected\n to. If left as ``None``, you must call :func:`open` with the port\n before issuing commands.\n\n :param device_id: The string which identifies the command set to use\n with your device.\n\n .. note::\n\n Currently, only the default value, 'benq', is supported. Please\n fill in a config file for your mrj3 and make a pull\n request!\n\n :param **kwargs: Any extra keyword args will be passed to the internal\n :mod:`pyserial` :class:`serial.Serial` object, and will override\n any device settings specified in the command set.\n\n \"\"\"\n self.port = port\n self.device_id = device_id\n self.get_config(device_id, kwargs)\n self.serial = self._initialize_pyserial(port)\n self._create_commands()\n\n def get_config(self, device_id, overrides):\n \"\"\"Get configuration for :mod:`pyserial` and the device.\n\n Any configuration values for the internal:mod:`pyserial`\n :class:`serial.Serial` specified will override the defaults from\n the device configuration. Any config values not specified will\n be left at the device default.\n\n :param device_id: The string which identifies the command set to use\n with your device.\n\n :param overrides: A dict of configuration values.\n\n \"\"\"\n self.available_configs = self._populate_configs()\n self.config = self.get_device_config_from_id(device_id)\n self._apply_overrides(overrides)\n self._validate_config()\n self.pyserial_config = self.get_pyserial_config()\n\n def _validate_config(self):\n \"\"\"Do basic sanity-checking on the loaded `config`.\"\"\"\n if 'serial' not in self.config:\n raise InvalidConfigError(\n 'Configuration file for {0} does not contain needed serial'\n 'config values. Add a `serial` section to the config.'.format(\n self.device_id)\n )\n if ('command_list' not in self.config or\n len(self.config['command_list']) == 0):\n raise InvalidConfigError(\n 'Configuration file for {0} does not define any commands. '\n 'Add a `serial` section to the config.'.format(\n self.device_id)\n )\n\n def _populate_configs(self):\n \"\"\"Load all json config files for devices.\n\n :returns: dict -- All available configs.\n\n \"\"\"\n configs = {}\n for f in os.listdir(PATH):\n if f.endswith('.json'):\n data = open(PATH + f)\n json_data = json.loads(data.read())\n name = os.path.splitext(f)[0]\n configs[name] = json_data\n return configs\n\n def _apply_overrides(self, overrides):\n \"\"\"Override specified values of the default configuration.\"\"\"\n self.config.update(overrides)\n\n def get_device_config_from_id(self, device_id):\n \"\"\"Get device configuration.\n\n :param device_id: The string which identifies the command set to use.\n\n :returns: dict -- The device configuration, including default\n :mod:`pyserial` settings, as well as the command set.\n\n :raises: DeviceConfigMissingError\n\n \"\"\"\n try:\n config = self.available_configs[device_id]\n except KeyError:\n raise DeviceConfigMissingError(\n 'Could not find device config with name {0}. '\n 'Check that the file exists in '\n ' `mrj3/mrj3_configs/`'.format(device_id)\n )\n return config\n\n def get_pyserial_config(self):\n \"\"\"Get the :mod:`pyserial` config values from the device config.\n\n This also checks that config values are sane, and casts them to\n the appropriate type, as needed.\n\n :func:`get_device_config_from_id` must be called before this method.\n\n :returns: dict -- The config values for :class:`serial.Serial`.\n :raises: InvalidConfigError\n\n \"\"\"\n serial_config = self.config['serial']\n for key, value in serial_config.items():\n if key not in self.possible_pyserial_settings:\n raise InvalidConfigError(\n 'Configuration file for {0} specifies a serial '\n 'setting \"{1}\" not recognized by pyserial. Check '\n 'http://pyserial.sourceforge.net/pyserial_api.html'\n 'for valid settings'.format(\n self.device_id, key)\n )\n if key in self.pyserial_config_converter:\n try:\n serial_config[key] = (\n self.pyserial_config_converter[key][value])\n except KeyError:\n raise InvalidConfigError(\n 'Configuration file for {0} specifies a serial '\n 'setting for \"{1}\" for key \"{2}\" not recognized '\n 'by pyserial. Check '\n 'http://pyserial.sourceforge.net/pyserial_api.html'\n 'for valid settings'.format(\n self.device_id, value, key)\n )\n return serial_config\n\n def _initialize_pyserial(self, port):\n \"\"\"Initialize the internal :class:`serial.Serial` object.\"\"\"\n return serial.Serial(port=port, **self.pyserial_config)\n\n def _send(self, data):\n logging.debug(\"_send: \" + repr(data))\n self.serial.write(data.encode())\n\n def _recv(self, size=1):\n data = self.serial.read(size).decode()\n if data:\n logging.debug(\"_recv: \" + repr(data))\n return data\n\n def _do_handshake(self):\n h = self.config.get('handshake')\n if h == None:\n return\n self._send(h['send'])\n sleep(h['wait'])\n expected = h['expect']\n resp = self._recv(len(expected))\n if resp != expected:\n logging.error(\"unexpected response to handshake \" + repr(resp))\n\n # def _command_handler(self, command, action, data):\n def _command_handler(self, station, command, action, data, error, xcommand):\n \"\"\"Send the `command` and `action` to the device.\n\n :param command: The command to send, for example, \"power\".\n :param action: The action to send, for example, \"on\".\n\n :returns: str -- The response from the device.\n\n :raises: InvalidCommandError if `action` is not valid for `command`.\n\n \"\"\"\n if command!='x':\n if action not in self.get_actions_for_command(command):\n raise InvalidCommandError(\n '{0} is not a valid action for comand {1}'.format(\n action, command)\n )\n command_string = self._create_command_string(station, command, action, data, error, xcommand)\n logging.info(\"send: \" + repr(command_string))\n logging.info(\"------ \" + re.sub(rePatternSoh, reSubStrSoh, command_string))\n self._do_handshake()\n self._send(command_string)\n sleep(self.config.get('wait_time', 1))\n response = self.get_response()\n logging.info(\"recv: \" + repr(response))\n logging.info(\"------ \" + re.sub(rePatternStx, reSubStrStx, response))\n\n self._check_response(response)\n return response\n\n def _strip_response(self, response):\n rs = right_surround=self.config.get('right_surround', '')\n ls = left_surround=self.config.get('left_surround', '')\n return response.rstrip(rs).lstrip(ls)\n\n def _check_response(self, response):\n \"\"\"Check for errors in the response.\"\"\"\n if response is None:\n return\n known_responses = self.config.get('known_responses')\n if known_responses:\n response = self._strip_response(response)\n if response in known_responses:\n print (known_responses[response])\n return\n else:\n raise CommandFailedError(\n 'Received an unknown response',\n response\n )\n failed_message = self.config.get('command_failed_message')\n if failed_message is not None and failed_message in response:\n raise CommandFailedError(\n 'Command failed! This is likely due to an invalid state '\n 'change.'\n )\n exception_message = self.config.get('exception_message')\n if exception_message is not None and exception_message in response:\n raise CommandExceptionError(\n 'Command caused an exception on the device. Your command '\n 'is likely invalid, check your json mrj3 config!'\n )\n\n def _create_commands(self):\n \"\"\"Add commands to class.\"\"\"\n # TODO: Clean this up.\n def _create_handler(command):\n def handler(station, action, data, error, xcommand):\n return self._command_handler(station, command, action, data, error, xcommand)\n return handler\n for command in self.command_spec:\n setattr(self, command, _create_handler(command))\n\n def get_response(self):\n \"\"\"Get any message waiting in the serial port buffer.\n\n :returns: str -- Response from the device, empty string if no response.\n\n \"\"\"\n response = ''\n # while self.serial.inWaiting() > 0:\n while self.serial.in_waiting > 0:\n response += self._recv(1)\n return response\n\n def _create_command_string(self, station, command, action, data, error, xcommand):\n \"\"\"Create a command string ready to send to the device.\n\n .. note:: The `command` param will be translated from english\n to the proper command for the device.\n\n \"\"\"\n try:\n stationValue = int(station.upper(), 10)\n \"\"\"Keep 0,1,...,8,9 as is\"\"\"\n \"\"\"Convert 10,11,...,30,31 to A,B,...,U,V\"\"\"\n if 0 <= stationValue <= 9:\n serial_station = chr(stationValue + (ord('0')-0))\n elif 10 <= stationValue <= 31:\n serial_station = chr(stationValue + (ord('A')-10))\n except:\n \"\"\"Allow g,h,...,u,v or G,H,...,U,V\"\"\"\n serial_station = station.upper()\n\n if command == 'x':\n serial_command = xcommand\n serial_action = action\n serial_data = data\n else:\n serial_command = self.command_spec[command]['command']\n serial_action = self.command_spec[command]['actions'][action]\n if 'data' in self.command_spec[command]:\n try:\n \"\"\"data is expected to be a string of hex bytes separated by white-space(s) or comma(s) ex: '0 9 2a f'\"\"\"\n \"\"\"for literal space character(s), bracket it with quotes ex. ' '\"\"\"\n serial_data = \"\".join(shlex.split(data))\n except:\n print(\"Error: Missing parameter!\")\n print(\"\\t...\" + \" \" + command + \" \" + serial_action + \" data(as string of hex bytes ex: '0 11 2a')\")\n exit()\n else:\n serial_data = \"\"\n\n if 'error' in self.command_spec[command]:\n try:\n \"\"\"data is expected to be an ascii coded hex byte \"\"\"\n serial_error = error\n except:\n print(\"Error: Missing parameter!\")\n print(\"\\t...\" + \" \" + command + \" \" + serial_action + \" error(as string of hex bytes ex: '0 11 2a')\")\n exit()\n else:\n serial_error = \"\"\n\n if command == \"slave\":\n command_without_chksum_string = (\n '{sta}{error}'\n '{data}{etx}'.format(\n sta=serial_station,\n error=serial_error,\n data=serial_data,\n etx=self.config.get('etx', '')\n )\n )\n command_string = (\n '{stx}{chksumed}{chksum}'.format(\n stx=self.config.get('stx', ''),\n chksumed = command_without_chksum_string,\n chksum = self.calc_chksum(command_without_chksum_string)\n )\n )\n elif command == \"eot\":\n command_string = (\n '{eot}'.format(\n eot=self.config.get('eot', ''),\n )\n )\n else:\n command_without_chksum_string = (\n '{sta}{command}{stx}'\n '{action}{data}{etx}'.format(\n sta=serial_station,\n command=serial_command,\n stx=self.config.get('stx', ''),\n action=serial_action,\n data=serial_data,\n etx=self.config.get('etx', '')\n )\n )\n command_string = (\n '{soh}{chksumed}{chksum}'.format(\n soh=self.config.get('soh', ''),\n chksumed = command_without_chksum_string,\n chksum = self.calc_chksum(command_without_chksum_string)\n )\n )\n return command_string\n\n def calc_chksum(self, s):\n \"\"\"Return the checksum in ascii code of the bytes represented in string s.\"\"\"\n b = bytearray()\n b.extend(map(ord, s))\n total_chksum = sum(b)\n \"\"\"The desired chksum value is the last 2-digits in ascii code of the total_chksum\"\"\"\n total_chksum_in_ascii = \"{0:0{1}x}\".format(total_chksum, 2).upper()\n return total_chksum_in_ascii[-2:]\n\n def get_actions_for_command(self, command):\n \"\"\"Get a list of all valid actions for a given command.\"\"\"\n return self.command_spec.get(command, {}).get('actions').keys()\n\n @property\n def command_list(self):\n \"\"\"Get a list of all commands.\n\n :returns: dict -- List of valid commands.\n\n \"\"\"\n return self.config['command_list'].keys()\n\n @property\n def command_spec(self):\n \"\"\"Return all command specifications.\n\n :returns: dict -- All command specs, with the pattern:\n \"\": {\n \"command\": \"\",\n \"actions\": {\n \"\": \"\",\n ...,\n },\n },\n ...\n \"\"\"\n return self.config['command_list']\n","sub_path":"mrj3/Mrj3.py","file_name":"Mrj3.py","file_ext":"py","file_size_in_byte":17254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"211427264","text":"import itertools\nimport datetime\n# a = itertools.permutations(range(1,10),9)\n#\n# for i in a:\n# if i[0] + i[1] + i[2] == \\\n# i[3] + i[4] + i[5] == \\\n# i[6] + i[7] + i[8] == \\\n# i[0] + i[4] + i[8] == \\\n# i[2] + i[4] + i[6] == \\\n# i[0] + i[3] + i[6] == \\\n# i[1] + i[4] + i[7] == \\\n# i[2] + i[5] + i[8]:\n# print([i[0],i[1],i[2]],[i[3],i[4],i[5]], \\\n# [i[6], i[7], i[8]],sep='\\n')\n# print()\nprint(datetime.datetime.now())\nn = 4\nl = itertools.permutations([i+1 for i in range(n*n)])\n\n# l = [[i+1 for i in range(9)],[9,3,1,2,5,6,7,8,4]]\nfor a in l:\n sum_oblique_left = sum((a[0 : n*n : n+1]))\n if sum_oblique_left == 34 :\n sum_oblique_right = sum(a[n-1 : n*(n-1)+1 : n-1])\n if sum_oblique_right == 34:\n\n\n sum_horizon = []\n sum_vertical = []\n\n for i in range(n):\n sum_horizon.append(sum(a[i*n : (i+1)*n]))\n sum_vertical.append(sum(a[i : n*(n-1)+i+1 : n]))\n\n sum_line = set(sum_horizon + sum_vertical)\n if len(sum_line) == 1:\n print(a)\n print(sum_line)\n\nprint(datetime.datetime.now())\n","sub_path":"jiugongge.py","file_name":"jiugongge.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"164493649","text":"def reconfigure_vm(vsphere_client, vm, module, esxi, resource_pool, cluster_name, guest, vm_extra_config, vm_hardware, vm_disk, vm_nic, state, force):\n spec = None\n changed = False\n changes = {\n \n }\n request = None\n shutdown = False\n poweron = vm.is_powered_on()\n devices = []\n memoryHotAddEnabled = bool(vm.properties.config.memoryHotAddEnabled)\n cpuHotAddEnabled = bool(vm.properties.config.cpuHotAddEnabled)\n cpuHotRemoveEnabled = bool(vm.properties.config.cpuHotRemoveEnabled)\n (changed, changes) = update_disks(vsphere_client, vm, module, vm_disk, changes)\n vm.properties._flush_cache()\n request = VI.ReconfigVM_TaskRequestMsg()\n if vm_extra_config:\n spec = spec_singleton(spec, request, vm)\n extra_config = []\n for (k, v) in vm_extra_config.items():\n ec = spec.new_extraConfig()\n ec.set_element_key(str(k))\n ec.set_element_value(str(v))\n extra_config.append(ec)\n spec.set_element_extraConfig(extra_config)\n changes['extra_config'] = vm_extra_config\n if ('memory_mb' in vm_hardware):\n if (int(vm_hardware['memory_mb']) != vm.properties.config.hardware.memoryMB):\n spec = spec_singleton(spec, request, vm)\n if vm.is_powered_on():\n if force:\n if (not memoryHotAddEnabled):\n shutdown = True\n elif (int(vm_hardware['memory_mb']) < vm.properties.config.hardware.memoryMB):\n shutdown = True\n elif (not memoryHotAddEnabled):\n module.fail_json(msg='memoryHotAdd is not enabled. force is required for shutdown')\n elif (int(vm_hardware['memory_mb']) < vm.properties.config.hardware.memoryMB):\n module.fail_json(msg='Cannot lower memory on a live VM. force is required for shutdown')\n spec.set_element_memoryMB(int(vm_hardware['memory_mb']))\n changes['memory'] = vm_hardware['memory_mb']\n if vm_nic:\n changed = reconfigure_net(vsphere_client, vm, module, esxi, resource_pool, guest, vm_nic, cluster_name)\n if ('num_cpus' in vm_hardware):\n if (int(vm_hardware['num_cpus']) != vm.properties.config.hardware.numCPU):\n spec = spec_singleton(spec, request, vm)\n if vm.is_powered_on():\n if force:\n if (not cpuHotAddEnabled):\n shutdown = True\n elif (int(vm_hardware['num_cpus']) < vm.properties.config.hardware.numCPU):\n if (not cpuHotRemoveEnabled):\n shutdown = True\n elif (not cpuHotAddEnabled):\n module.fail_json(msg='cpuHotAdd is not enabled. force is required for shutdown')\n elif (int(vm_hardware['num_cpus']) < vm.properties.config.hardware.numCPU):\n if (not cpuHotRemoveEnabled):\n module.fail_json(msg='Cannot lower CPU on a live VM without cpuHotRemove. force is required for shutdown')\n spec.set_element_numCPUs(int(vm_hardware['num_cpus']))\n changes['cpu'] = vm_hardware['num_cpus']\n if ('vm_cdrom' in vm_hardware):\n spec = spec_singleton(spec, request, vm)\n (cdrom_type, cdrom_iso_path) = get_cdrom_params(module, vsphere_client, vm_hardware['vm_cdrom'])\n cdrom = None\n current_devices = vm.properties.config.hardware.device\n for dev in current_devices:\n if (dev._type == 'VirtualCdrom'):\n cdrom = dev._obj\n break\n if (cdrom_type == 'iso'):\n iso_location = cdrom_iso_path.split('/', 1)\n (datastore, ds) = find_datastore(module, vsphere_client, iso_location[0], None)\n iso_path = iso_location[1]\n iso = VI.ns0.VirtualCdromIsoBackingInfo_Def('iso').pyclass()\n iso.set_element_fileName(('%s %s' % (datastore, iso_path)))\n cdrom.set_element_backing(iso)\n cdrom.Connectable.set_element_connected(True)\n cdrom.Connectable.set_element_startConnected(True)\n elif (cdrom_type == 'client'):\n client = VI.ns0.VirtualCdromRemoteAtapiBackingInfo_Def('client').pyclass()\n client.set_element_deviceName('')\n cdrom.set_element_backing(client)\n cdrom.Connectable.set_element_connected(True)\n cdrom.Connectable.set_element_startConnected(True)\n else:\n vsphere_client.disconnect()\n module.fail_json(msg=('Error adding cdrom of type %s to vm spec. cdrom type can either be iso or client' % cdrom_type))\n dev_change = spec.new_deviceChange()\n dev_change.set_element_device(cdrom)\n dev_change.set_element_operation('edit')\n devices.append(dev_change)\n changes['cdrom'] = vm_hardware['vm_cdrom']\n if vm_disk:\n spec = spec_singleton(spec, request, vm)\n dev_list = [d for d in vm.properties.config.hardware.device if (d._type == 'VirtualDisk')]\n if (len(vm_disk) > len(dev_list)):\n vsphere_client.disconnect()\n module.fail_json(msg=\"Error in vm_disk definition. Too many disks defined in comparison to the VM's disk profile.\")\n disk_num = 0\n dev_changes = []\n disks_changed = {\n \n }\n for disk in sorted(vm_disk):\n try:\n disksize = int(vm_disk[disk]['size_gb'])\n disksize = ((disksize * 1024) * 1024)\n except (KeyError, ValueError):\n vsphere_client.disconnect()\n module.fail_json(msg=(\"Error in '%s' definition. Size needs to be specified as an integer.\" % disk))\n dev = dev_list[disk_num]\n if (disksize < int(dev.capacityInKB)):\n vsphere_client.disconnect()\n module.fail_json(msg=(\"Error in '%s' definition. New size needs to be higher than the current value (%s GB).\" % (disk, ((int(dev.capacityInKB) / 1024) / 1024))))\n elif (disksize > int(dev.capacityInKB)):\n dev_obj = dev._obj\n dev_obj.set_element_capacityInKB(disksize)\n dev_change = spec.new_deviceChange()\n dev_change.set_element_operation('edit')\n dev_change.set_element_device(dev_obj)\n dev_changes.append(dev_change)\n disks_changed[disk] = {\n 'size_gb': int(vm_disk[disk]['size_gb']),\n }\n disk_num = (disk_num + 1)\n if dev_changes:\n spec.set_element_deviceChange(dev_changes)\n changes['disks'] = disks_changed\n if len(changes):\n if (shutdown and vm.is_powered_on()):\n try:\n vm.power_off(sync_run=True)\n vm.get_status()\n except Exception:\n e = get_exception()\n module.fail_json(msg=('Failed to shutdown vm %s: %s' % (guest, e)))\n if len(devices):\n spec.set_element_deviceChange(devices)\n request.set_element_spec(spec)\n ret = vsphere_client._proxy.ReconfigVM_Task(request)._returnval\n task = VITask(ret, vsphere_client)\n status = task.wait_for_state([task.STATE_SUCCESS, task.STATE_ERROR])\n if (status == task.STATE_SUCCESS):\n changed = True\n elif (status == task.STATE_ERROR):\n module.fail_json(msg=('Error reconfiguring vm: %s' % task.get_error_message()))\n if (vm.is_powered_off() and poweron):\n try:\n vm.power_on(sync_run=True)\n except Exception:\n e = get_exception()\n module.fail_json(msg=('Failed to power on vm %s : %s' % (guest, e)))\n vsphere_client.disconnect()\n if changed:\n module.exit_json(changed=True, changes=changes)\n module.exit_json(changed=False)","sub_path":"Data Set/bug-fixing-3/36975c50ef63b2b159686b0c8fbab27f9df98512--fix.py","file_name":"36975c50ef63b2b159686b0c8fbab27f9df98512--fix.py","file_ext":"py","file_size_in_byte":7914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"343495901","text":"'''\nID: arcaand2\nLANG: PYTHON3\nTASK: ride\n'''\n\nwith open('ride.in', 'r') as fin:\n line1 = [x for x in fin.readline().rstrip()]\n line2 = [x for x in fin.readline().rstrip()]\n\nnumber1 = [ord(line1[x])-ord('A')+1 for x in range(len(line1))]\n\nnumber2 = [ord(line2[x])-ord('A')+1 for x in range(len(line2))]\n\n\nresult1 = 1\nresult2 = 1\n \nfor x in number1: \n result1 *= x\nresult1 = result1 % 47\nfor x in number2:\n result2 *= x\nresult2 = result2 % 47\nwith open('ride.out', 'w') as fout:\n if result1 == result2:\n print('GO', file=fout)\n else:\n print('STAY', file=fout)","sub_path":"training/ufo_ride/ride.py","file_name":"ride.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"73009737","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 17 21:34:55 2017\n\nTo do!\n\nstore t array\n\n\n@author: woolseo\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport multiprocessing as proc\nimport time\nimport datetime\n\nN = 10\nt_max =1000\nfilename = 'kim 2014 2a xx'\n\ndef randwalk(a,q):\n \n temp_var_mean = np.array([0,0])\n \n l = 1\n dl = 1\n \n while(l < t_max):\n \n for k in range(0,9): \n \n store_x = np.arange(0,l,1,dtype=np.int)\n \n for j in range(1, N):\n \n \n x = np.array([],dtype=np.int)\n s = np.array([],dtype=np.int)\n \n np.random.seed(); \n \n #t=1\n if( np.random.random() < 0.5 ):\n s_next = +1\n else:\n s_next = -1\n \n x = np.insert(x,0,s_next)\n s = np.insert(s,0,s_next)\n \n \n #t>1\n for i in range(1, l):\n if( np.random.random() < ( 1.0 / ( i**a ) ) ):\n r = np.random.random()\n if( r < 0.5 ):\n s_next = +1\n else:\n s_next = -1\n \n else:\n s_next = s[i-1] #pLMEM\n #s_next = (-1) * s[i-1] #nLMEM\n \n x = np.insert(x,i,x[i-1]+s_next)\n s = np.insert(s,i,s_next)\n \n \n print(l,k)\n \n store_x = np.vstack((store_x,x))\n \n temp_var_mean = np.vstack((temp_var_mean,[l,np.mean(np.var(store_x,1))]))\n \n l = l + dl\n \n dl = dl * 10\n temp = str(a) + 'done'\n print(temp)\n q.put(temp_var_mean)\n \n \n############## start program ###############\n\n\nstartTime = time.time()\nnow = datetime.datetime.now()\nnowDate = now.strftime('%Y%m%d')\n\nfilename = filename + nowDate\nfilename_csv = filename + '.csv'\nfilename_pdf = filename + '.pdf'\n\n\nQ = proc.Queue() # queue\n\np = [] #proceesing array\nresults = np.array([None,2])\nvar_mean = np.array([0,0])\n\n\nfor i in range(4):\n p.append( proc.Process(target = randwalk, args=((i*2+2)*0.1,Q)) )\n p[i].start()\n results = Q.get(True)\n var_mean = np.vstack((var_mean,results))\n np.savetxt(filename_csv, var_mean, delimiter=',')\n plt.plot(var_mean[:,0],var_mean[:,1],'o', ms=2, label=(i*2+2)*0.1)\n\n\nprint(time.time()-startTime)\n \n#plt.axis([10, t_max, 10, t_max*t_max])\nplt.xscale('log') \nplt.yscale('log') \nplt.xlabel('$t$', fontsize=15)\nplt.ylabel('$-^2$', fontsize=15)\nplt.legend(loc=4)\n\n#plt.title(\"2a pLMEM $-^2$\" )\n\nplt.savefig(filename_pdf)\nplt.show()\n\n\n\nprint(\"done\")\n","sub_path":"paper/kim2014/2a_x_xx/2a_numpy_170920_x_xx_pLMEM_multiprocessing.py","file_name":"2a_numpy_170920_x_xx_pLMEM_multiprocessing.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"554650124","text":"# Copyright (c) 2014 Evalf\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n\"\"\"\nThe log module provides print methods ``debug``, ``info``, ``user``,\n``warning``, and ``error``, in increasing order of priority. Output is sent to\nstdout as well as to an html formatted log file if so configured.\n\nThis is a transitional wrapper around the external treelog module.\n\"\"\"\n\nimport builtins, itertools, treelog, contextlib, sys\nfrom treelog import set, add, disable, withcontext, \\\n Log, TeeLog, FilterLog, NullLog, DataLog, RecordLog, StdoutLog, RichOutputLog, LoggingLog\nfrom . import warnings\n\ndef _len(iterable):\n try:\n return len(iterable)\n except:\n return 0\n\nclass iter:\n def __init__(self, title, iterable, length=None):\n self._log = treelog.current\n self._iter = builtins.iter(iterable)\n self._title = title\n self._length = length or _len(iterable)\n self._index = 0\n text = '{} 0'.format(self._title)\n if self._length:\n text += ' (0%)'\n self._log.pushcontext(text)\n self.closed = False\n def __iter__(self):\n return self\n def __next__(self):\n if self.closed:\n raise StopIteration\n try:\n value = next(self._iter)\n except:\n self.close()\n raise\n self._index += 1\n text = '{} {}'.format(self._title, self._index)\n if self._length:\n text += ' ({:.0f}%)'.format(100 * self._index / self._length)\n self._log.popcontext()\n self._log.pushcontext(text)\n return value\n def close(self):\n if not self.closed:\n self._log.popcontext()\n self.closed = True\n def __enter__(self):\n return self\n def __exit__(self, *args):\n self.close()\n def __del__(self):\n if not self.closed:\n warnings.warn('unclosed iterator {!r}'.format(self._title), ResourceWarning)\n self.close()\n\ndef range(title, *args):\n return iter(title, builtins.range(*args))\n\ndef enumerate(title, iterable):\n return iter(title, builtins.enumerate(iterable), length=_len(iterable))\n\ndef zip(title, *iterables):\n return iter(title, builtins.zip(*iterables), length=min(map(_len, iterables)))\n\ndef count(title, start=0, step=1):\n return iter(title, itertools.count(start, step))\n\n@contextlib.contextmanager\ndef open(filename, mode, *, level='user', exists=None):\n if exists is not None:\n warnings.deprecation('the \"exists\" argument is deprecated and will be ignored')\n levels = 'debug', 'info', 'user', 'warning', 'error'\n if level not in levels:\n raise Exception('the \"level\" argument should be on of {}'.format(', '.join(levels)))\n with treelog.open(filename, mode, level=levels.index(level), id=None) as f:\n f.devnull = not f\n yield f\n\ndef __getattr__(name):\n return getattr(treelog.current, name)\n\nif sys.version_info < (3,7):\n def _factory(name):\n def wrapper(*args, **kwargs):\n return __getattr__(name)(*args, **kwargs)\n wrapper.__doc__ = getattr(treelog.Log, name).__doc__\n wrapper.__name__ = name\n wrapper.__qualname__ = name\n return wrapper\n locals().update((name, _factory(name)) for name in dir(treelog.Log) if name not in locals())\n del _factory\n\n# vim:sw=2:sts=2:et\n","sub_path":"nutils/log.py","file_name":"log.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"88014518","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/skip/cli.py\n# Compiled at: 2019-07-12 16:27:22\n# Size of source mod 2**32: 3157 bytes\nfrom typing import Dict, Set, Type\nimport click\nfrom click import Context\nfrom skip.managers.apt import Apt\nfrom skip.managers.apt_get import AptGet\nfrom skip.managers.brew import Brew\nfrom skip.managers.brew_cask import BrewCask\nfrom skip.managers.choco import Choco\nfrom skip.managers.flatpak import Flatpak\nfrom skip.managers.gem import Gem\nfrom skip.managers.linux_brew import LinuxBrew\nfrom skip.managers.macos_brew import MacOSBrew\nfrom skip.managers.manager import PackageManager\nfrom skip.managers.mas import Mas\nfrom skip.managers.npm import Npm\nfrom skip.managers.pip import Pip\nfrom skip.managers.snap import Snap\n\ndef managers() -> Set[Type[PackageManager]]:\n return {Brew, Npm, Apt, AptGet, Gem, Choco, Pip, Snap, LinuxBrew, BrewCask,\n MacOSBrew, Mas, Flatpak}\n\n\n@click.group()\ndef skip():\n pass\n\n\n@skip.command(help='Performs a full upgrade and cleanup for all package managers')\n@click.pass_context\ndef autopilot(context: Context) -> bool:\n context.invoke(update)\n context.invoke(upgrade)\n context.invoke(clean)\n return True\n\n\n@skip.command(help='Setup all package managers')\ndef setup() -> bool:\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.setup()')\n manager.setup()\n print('Finish: ' + manager.canonical_name() + '.setup()')\n\n return True\n\n\n@skip.command(help='Updates all package managers')\ndef update() -> bool:\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.update()')\n manager.update()\n print('Finish: ' + manager.canonical_name() + '.update()')\n\n return True\n\n\n@skip.command(help='Upgrades all package managers')\ndef upgrade() -> bool:\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.upgrade()')\n manager.upgrade()\n print('Finish: ' + manager.canonical_name() + '.upgrade()')\n\n return True\n\n\n@skip.command(help='Cleans all package managers')\ndef clean() -> bool:\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.clean()')\n manager.clean()\n print('Finish: ' + manager.canonical_name() + '.clean()')\n\n return True\n\n\n@skip.command(help='Installs all packages in Skipfile.toml for all package managers')\ndef install() -> bool:\n with open('Skipfile.toml', 'r') as (file):\n from toml import loads\n skipfile = loads(file.read())\n for manager in managers():\n if manager.check():\n print('Start: ' + manager.canonical_name() + '.install()')\n packages = skipfile['package_manager'][manager.canonical_name()]\n for package in packages:\n if packages[package] is str:\n packages[package] = packages[package].strip().split()\n\n manager.install(packages)\n print('Finish: ' + manager.canonical_name() + '.install()')\n\n return True","sub_path":"pycfiles/skip_manager-0.3.2-py3.7/cli.cpython-37.py","file_name":"cli.cpython-37.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"68106107","text":"import os\nimport json\nfrom owh.etl.common.etl import ETL\nimport logging\nfrom owh.etl.common.datafile_parser import DataFileParser\nlogger = logging.getLogger('incident_etl')\n\nclass CancerMortalityETL (ETL):\n \"\"\"\n Loads cancer mortality data into ES db\n \"\"\"\n def __init__(self, configFile):\n ETL.__init__(self, configFile)\n self.create_index(os.path.join(os.path.dirname(__file__), \"es_mapping\"\n ,self.config['elastic_search']['type_mapping']), True)\n self._load_cancer_site_mappings()\n\n def _load_cancer_site_mappings(self):\n with open(os.path.join(os.path.dirname(__file__),\"../cancer-site-mappings.json\")) as jf:\n self.cancer_site_mappings = json.load(jf, encoding=\"utf8\")\n\n def process_cancer_sites(self, record):\n if record['cancer_site'] == '26000':# to separate male/female breast cancer sites\n if record['sex'] == 'Male':\n record['cancer_site'] = '26000-Male'\n else:\n record['cancer_site'] = '26000-Female'\n\n site_hierarchy = []\n if record['cancer_site']:\n site_hierarchy = self.cancer_site_mappings[record['cancer_site']]\n record['cancer_site'] = {'code': record['cancer_site'], 'path': site_hierarchy}\n\n def perform_etl(self):\n \"\"\"Load the cancer mortality data\"\"\"\n record_count = 0\n self.initialCount = self.get_record_count()\n\n for f in os.listdir(self.dataDirectory):\n if not os.path.isfile(os.path.join(self.dataDirectory, f)) or f.endswith(\".zip\") :\n continue\n\n file_path = os.path.join(self.dataDirectory, f)\n logger.info(\"Processing file: %s\", f)\n\n # get the corresponding data mapping file\n config_file = os.path.join(self.dataDirectory, 'data_mapping', 'mortality.json')\n\n if not config_file:\n logger.warn(\"No mapping available for data file %s, skipping\", file_path)\n continue\n\n cancer_mortality_parser = DataFileParser(file_path, config_file)\n cancer_mortality_parser.parseNextLine() # skip the header line\n\n while True:\n record = cancer_mortality_parser.parseNextLine()\n if not record:\n break\n if (record['current_year'] == '1999' or record['state'] == 'PR' ): # skip invalid CBSA records/ 1999 year's records\n continue\n\n self.process_cancer_sites(record)\n #prepare region data\n self.loadRegionData(record)\n record_count += 1\n self.batchRepository.persist({\"index\": {\"_index\": self.config['elastic_search']['index'],\n \"_type\": self.config['elastic_search']['type'],\n \"_id\": record_count}})\n self.batchRepository.persist(record)\n\n self.batchRepository.flush()\n self.refresh_index()\n self.metrics.insertCount = record_count\n self.updateDsMetadata()\n logger.info(\"*** Processed %s records from cancer mortality data file\", self.metrics.insertCount)\n\n def updateDsMetadata(self):\n for y in range(2000, 2017):\n self.loadDataSetMetaData('cancer_mortality', str(y), os.path.join(self.dataDirectory, 'data_mapping', 'mortality.json'))\n\n def validate_etl(self):\n \"\"\" Validate the ETL\"\"\"\n expectedCount = (self.initialCount + self.metrics.insertCount)\n if expectedCount != self.get_record_count():\n self.metrics.message = \"Number of records in the DB (%d) not same as the number of records expected (%d)\" % (self.get_record_count(), expectedCount)\n return False\n if self.get_record_by_id(1) is None:\n self.metrics.message = \"Record 1 is None\"\n return False\n if self.get_record_by_id(self.get_record_count()) is None:\n self.metrics.message = \"Last record is None\"\n return False\n return True\n\n\nif __name__ == \"__main__\":\n # Perform ETL\n etl = CancerMortalityETL(file(os.path.join(os.path.dirname(__file__), \"config.yaml\"), 'r'))\n etl.execute()\n","sub_path":"software/owh/backoffice/owh/etl/cancer/mortality/mortality_etl.py","file_name":"mortality_etl.py","file_ext":"py","file_size_in_byte":4277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"42544211","text":"import logging\nimport os\nimport shutil\nimport subprocess\nfrom abc import ABCMeta, abstractmethod\nfrom datetime import datetime, timedelta\nfrom threading import Thread\n\nfrom md_env import MDTestEnv\n\n\nlog = logging.getLogger(__name__)\n\ndef monitor_proc(env: MDTestEnv, proc):\n proc.wait()\n\n\nclass ACMEServer:\n __metaclass__ = ABCMeta\n\n @abstractmethod\n def start(self):\n raise NotImplementedError\n\n @abstractmethod\n def stop(self):\n raise NotImplementedError\n\n @abstractmethod\n def install_ca_bundle(self, dest):\n raise NotImplementedError\n\n\nclass MDPebbleRunner(ACMEServer):\n\n def __init__(self, env: MDTestEnv):\n self.env = env\n self._pebble = None\n self._challtestsrv = None\n self._log = None\n\n def start(self):\n args = ['pebble', '-config', './test/config/pebble-config.json', '-dnsserver', ':8053']\n env = {}\n env.update(os.environ)\n env['PEBBLE_VA_NOSLEEP'] = '1'\n self._log = open(f'{self.env.gen_dir}/pebble.log', 'w')\n self._pebble = subprocess.Popen(args=args, env=env, cwd=self.env.acme_server_dir,\n stdout=self._log, stderr=self._log)\n t = Thread(target=monitor_proc, args=(self.env, self._pebble))\n t.start()\n\n args = ['pebble-challtestsrv', '-http01', '', '-https01', '', '-tlsalpn01', '']\n self._challtestsrv = subprocess.Popen(args, cwd=self.env.acme_server_dir,\n stdout=self._log, stderr=self._log)\n t = Thread(target=monitor_proc, args=(self.env, self._challtestsrv))\n t.start()\n\n def stop(self):\n if self._pebble:\n self._pebble.terminate()\n self._pebble = None\n if self._challtestsrv:\n self._challtestsrv.terminate()\n self._challtestsrv = None\n if self._log:\n self._log.close()\n self._log = None\n\n def install_ca_bundle(self, dest):\n src = os.path.join(self.env.acme_server_dir, 'test/certs/pebble.minica.pem')\n shutil.copyfile(src, dest)\n end = datetime.now() + timedelta(seconds=20)\n while datetime.now() < end:\n r = self.env.curl_get('https://localhost:15000/roots/0', insecure=True)\n if r.exit_code == 0:\n with open(dest, 'a') as fd:\n fd.write(r.stdout)\n break\n\n\nclass MDBoulderRunner(ACMEServer):\n\n def __init__(self, env: MDTestEnv):\n self.env = env\n\n def start(self):\n pass\n\n def stop(self):\n pass\n\n def install_ca_bundle(self, dest):\n r = self.env.run([\n 'docker', 'exec', 'boulder_boulder_1', 'bash', '-c', \"cat /tmp/root*.pem\"\n ])\n assert r.exit_code == 0\n with open(dest, 'w') as fd:\n fd.write(r.stdout)\n\n","sub_path":"test/md_acme.py","file_name":"md_acme.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"222213352","text":"import numpy\n\nimport os\n\nos.environ['KERAS_BACKEND'] = 'theano'\n\nfrom keras.layers import Dense\nimport csv\n\nfrom ingine import ann\n\n# Устанавливаем seed для повторяемости результатов\nnumpy.random.seed(151681)\n\n\ndef load_data():\n \"\"\"\n Функция получения данных из data.py\n :return: list(2) of lists(2)\n \"\"\"\n input_data = []\n output_data = []\n\n from data import data\n\n data = [_.split(';') for _ in data.split('\\n')]\n\n for row in data:\n in_data = row[0]\n out_data = row[1]\n in_data = in_data.replace('X', '1')\n in_data = in_data.replace('+', '1')\n in_data = in_data.replace('_', '0')\n in_data = in_data.replace('-', '0')\n\n out_data = out_data.replace('X', '0')\n out_data = out_data.replace('+', '0')\n out_data = out_data.replace('O', '1')\n out_data = out_data.replace('_', '0')\n out_data = out_data.replace('-', '0')\n\n in_data = list(map(lambda a: int(a), in_data))\n out_data = list(map(lambda a: int(a), out_data))\n\n input_data.append(in_data)\n output_data.append(out_data)\n\n input_data = numpy.asarray(input_data)\n output_data = numpy.asarray(output_data)\n\n input_data_test = input_data[8000:]\n input_data = input_data[:8000]\n\n output_data_test = output_data[8000:]\n output_data = output_data[:8000]\n\n return (input_data, output_data), (input_data_test, output_data_test)\n\n\n# Загружаем данные\n(X_train, Y_train), (X_test, Y_test) = load_data()\n\n# Определеяем слои\nlayers = [Dense(100, input_dim = 100, activation = \"softsign\", kernel_initializer = \"normal\"),\n Dense(20, activation = \"softsign\", kernel_initializer = \"normal\"),\n Dense(10, activation = \"softsign\", kernel_initializer = \"normal\"),\n Dense(100, activation = \"softsign\", kernel_initializer = \"normal\")]\n\n# Получение модели с\ncustomnn = ann.get_customnn(X_train, Y_train, layers = layers, epochs = 5)\n\nres = customnn(X_test)\n\nxt = numpy.asarray([255 if a == 1 else a for a in X_test[15]]).reshape(10, 10)\nyt = numpy.asarray([255 if a == 1 else a for a in Y_test[15]]).reshape(10, 10)\nrt = numpy.asarray([int(-numpy.sign(a)) * 255 for a in res[15]]).reshape(10, 10)\n\nfrom PIL import Image, ImageDraw\n\nimage = Image.new(\"L\", (500, 500), (255,))\ndraw = ImageDraw.Draw(image)\nfor i in range(10): # For every pixel:\n for j in range(10):\n draw.rectangle((i * 50, j * 50, (i + 1) * 50, (j + 1) * 50), fill = (xt[i][j],))\n\nimage.save(\"images/xt.png\", \"PNG\")\n\nimage = Image.new(\"L\", (500, 500), (255,))\ndraw = ImageDraw.Draw(image)\nfor i in range(10): # For every pixel:\n for j in range(10):\n draw.rectangle((i * 50, j * 50, (i + 1) * 50, (j + 1) * 50), fill = (yt[i][j],))\n\nimage.save(\"images/yt.png\", \"PNG\")\n\nimage = Image.new(\"L\", (500, 500), (255,))\ndraw = ImageDraw.Draw(image)\nfor i in range(10): # For every pixel:\n for j in range(10):\n draw.rectangle((i * 50, j * 50, (i + 1) * 50, (j + 1) * 50), fill = (rt[i][j],))\n\nimage.save(\"images/rt.png\", \"PNG\")\n","sub_path":"ingine/examples/seabattle.py","file_name":"seabattle.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"289550038","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# ### Import necessary libraries\n\n# In[1]:\n\n\n# Data representation and computation\nimport pandas as pd \nimport numpy as np \npd.options.display.float_format = '{:20,.4f}'.format\n\n# plotting\nimport matplotlib.pyplot as plt \nimport seaborn as sns\n\n# Data splitting and pipeline for training models\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.pipeline import Pipeline\nfrom sklearn import metrics\nfrom sklearn.utils import shuffle\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score, f1_score, recall_score, precision_score\n\n\n# Used ML models\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.ensemble import GradientBoostingClassifier\nimport lightgbm as lgb\nfrom xgboost import XGBClassifier\n\n# Miscellaneous\nimport warnings\nfrom prettytable import PrettyTable\n\n# Declaration\nwarnings.filterwarnings('ignore')\nget_ipython().run_line_magic('precision', '2')\nget_ipython().run_line_magic('matplotlib', 'inline')\nsns.set(font_scale=1)\n\n\n# ### Load Data\n\n# In[2]:\n\n\nimport json\nwith open(r\"transactions.txt\",\"r+\") as f:\n llst_transaction_records = f.readlines()\nllst_transaction_records = [json.loads(item) for item in llst_transaction_records]\nldf_training_dataset = pd.DataFrame(llst_transaction_records)\n\nldf_training_dataset['transactionDateTime'] = pd.to_datetime(ldf_training_dataset['transactionDateTime'])\n\n\n# In[3]:\n\n\nldf_training_dataset.head()\n\n\n# ## Question 1: Load\n\n# ##### Statistical summary\n\n# In[4]:\n\n\nprint(\"Number of records: \"+str(len(ldf_training_dataset)))\n\n\n# In[5]:\n\n\nldf_training_dataset.describe()\n\n\n# In[6]:\n\n\nldf_training_dataset.info()\n\n\n# ##### Checking for null or NA values\n\n# In[8]:\n\n\nldf_training_dataset.isnull().sum()\n\n\n# ##### Checking for values stored as blank ('')\n\n# In[9]:\n\n\nldf_training_dataset.eq('').sum()\n\n\n# ## Question 2: Plot\n\n# ##### Plotting bar-chart of \"isFraud`\" \n\n# In[75]:\n\n\nldf_temp = ldf_training_dataset.isFraud.value_counts().to_frame(\"_count\")\nldf_temp.plot(kind=\"bar\")\n\n\n# ##### Plotting histogram of \"transactionAmount\" \n\n# In[76]:\n\n\nldf_training_dataset['transactionAmount'].plot.hist()\n\n\n# ## Question 3: Data Wrangling - Duplicate Transactions\n\n# #### To identify Multi-swipe transactions, please see the explanation in Word documents)\n# In[77]:\n\n\nldf_training_dataset['IsDuplicate'] = (ldf_training_dataset.sort_values(['transactionDateTime'])\n .groupby(['accountNumber', 'transactionAmount', 'merchantName'], sort=False)['transactionDateTime']\n .diff()\n .dt.total_seconds()\n .lt(300))\n\n\n# In[78]:\n\n\nldf_training_dataset.IsDuplicate.value_counts().to_frame(\"Count\")\n\n\n# #### To identify Reversed transactions, using the Transaction Type column\n\n# In[79]:\n\n\nldf_training_dataset.transactionType.value_counts().to_frame(\"Count\")\n\n\n# ## Estimating the total number and dollar amount of Normal & Duplicate Transactions.\n\n# In[80]:\n\n\nModel_Accuracy = PrettyTable()\nModel_Accuracy.field_names = [\"\",\"No. of Transactions\", \"Doller Amount\"]\nModel_Accuracy.align[\"\"] = \"r\"\nldf_training_dataset_normal = ldf_training_dataset[(ldf_training_dataset['transactionType']!=\"REVERSAL\") &\n (ldf_training_dataset['IsDuplicate'] == False)]\n\nModel_Accuracy.add_row([\"Normal (Excluding Duplicates)\",len(ldf_training_dataset_normal), \n round(sum(ldf_training_dataset_normal['transactionAmount']))])\nprint(\"\\nA - Normal (Excluding Duplicates)\")\nprint(Model_Accuracy)\n\n\n# In[81]:\n\n\n\nModel_Accuracy = PrettyTable()\nModel_Accuracy.field_names = [\"\",\"No. of Transactions\", \"Doller Amount\"]\nModel_Accuracy.align[\"\"] = \"r\"\nldf_training_dataset_rev = ldf_training_dataset[ldf_training_dataset[\"transactionType\"] == \"REVERSAL\"]\nldf_training_dataset_multi_swipe = ldf_training_dataset[(ldf_training_dataset['transactionType']!=\"REVERSAL\") &\n (ldf_training_dataset['IsDuplicate'] == True)]\n\nModel_Accuracy.add_row([\"Reversal\",len(ldf_training_dataset_rev), \n round(sum(ldf_training_dataset_rev['transactionAmount']))])\nModel_Accuracy.add_row([\"Multi-Swipe\",len(ldf_training_dataset_multi_swipe), \n round(sum(ldf_training_dataset_multi_swipe['transactionAmount']))])\nModel_Accuracy.add_row([\"\",\"----\",\"----\"])\nModel_Accuracy.add_row([\"Reversal + Multi-Swipe\",int(len(ldf_training_dataset_rev)+\n len(ldf_training_dataset_multi_swipe)),\n round(sum(ldf_training_dataset_rev['transactionAmount']))+\n round(sum(ldf_training_dataset_multi_swipe['transactionAmount']))])\n\nprint(\"\\nB - Duplicates(Reversal + Multi-Swipe)\")\nprint(Model_Accuracy)\n\n\n# In[82]:\n\n\n# =====================================================================================================\n\nModel_Accuracy = PrettyTable()\nModel_Accuracy.field_names = [\"\",\"No. of Transactions\", \"Doller Amount\"]\nModel_Accuracy.align[\"\"] = \"r\"\n\nModel_Accuracy.add_row([\"A + B\",len(ldf_training_dataset_normal)+\n (len(ldf_training_dataset_rev)+len(ldf_training_dataset_multi_swipe)),\n (round(sum(ldf_training_dataset_rev['transactionAmount']))+\n round(sum(ldf_training_dataset_multi_swipe['transactionAmount'])))+\n round(sum(ldf_training_dataset_normal['transactionAmount']))])\nprint(\"\\nC = A + B (Normal & Duplicate both)\")\nprint(Model_Accuracy)\n\n\n# ##Question 4: Model\n\n# ### Sampling to make the dataset balanced\n\n# In[83]:\n\n\nldf_training_dataset.isFraud.value_counts().to_frame(\"Count\")\n\n\n# Since the number of isFraud=True cases is very low as compared to the isFraud=False cases,\n# we will take out a balanced sample by keeping all the records of isFraud=True cases and taking only 18,000 records of isFraud=False cases.\n# In[84]:\n\n\nldf_training_dataset_2 = ldf_training_dataset.groupby('isFraud', group_keys=False).apply(lambda x:x.sample(min(len(x), 18000)))\nldf_training_dataset_2 = ldf_training_dataset_2.reset_index(drop=True)\nprint(\"Number of records after under-sampling: \"+str(len(ldf_training_dataset_2.isFraud)))\n\n\n# In[85]:\n\n\nldf_training_dataset_2.isFraud.value_counts().to_frame(\"Count\")\n\n\n# ##### Removing the duplicate transactions (Reversal and Multi-swipe)\n\n# In[86]:\n\n\nldf_training_dataset_3 = ldf_training_dataset_2[(ldf_training_dataset_2['transactionType']!=\"REVERSAL\") &\n (ldf_training_dataset_2['IsDuplicate'] == False)]\n\n\n# ## Predictive model to determine whether a given transaction will be fraudulent or not\n\n# #### Select input variables\n\n# In[87]:\n\n\ninput_col = ['creditLimit', 'transactionAmount', 'merchantCountryCode',\n 'merchantCategoryCode','cardPresent', 'posEntryMode', 'posConditionCode', \n 'acqCountry', 'currentBalance', 'isFraud']\nldf_training_dataset_clf = ldf_training_dataset_3[input_col]\n\n\n# #### Convert categorical columns to dummy variables \n\n# In[88]:\n\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"creditLimit\"], prefix='FRAUD_CLASSIFIER_creditLimit')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"creditLimit\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"merchantCountryCode\"], prefix='FRAUD_CLASSIFIER_merchantCountryCode')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"merchantCountryCode\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"merchantCategoryCode\"], prefix='FRAUD_CLASSIFIER_merchantCategoryCode')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"merchantCategoryCode\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"cardPresent\"], prefix='FRAUD_CLASSIFIER_cardPresent')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"cardPresent\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"posEntryMode\"], prefix='FRAUD_CLASSIFIER_posEntryMode')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"posEntryMode\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"posConditionCode\"], prefix='FRAUD_CLASSIFIER_posConditionCode')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"posConditionCode\", axis=1, inplace=True)\n\nfeature_dummy = pd.get_dummies(ldf_training_dataset_clf[\"acqCountry\"], prefix='FRAUD_CLASSIFIER_acqCountry')\nldf_training_dataset_clf = pd.concat([ldf_training_dataset_clf, feature_dummy], axis = 1)\nldf_training_dataset_clf.drop(\"acqCountry\", axis=1, inplace=True)\n\n\n# #### Train Test & Validation Split\n\n# In[97]:\n\n\ny = ldf_training_dataset_clf.isFraud\nX = ldf_training_dataset_clf.drop(\"isFraud\", axis=1)\n\nmy_tags = y\n\n\n# In[98]:\n\n\n# splitting X and y into training and testing sets \nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, stratify=y, random_state=123, shuffle=True)\n\n\n# In[99]:\n\n\nprint(X_train.shape)\nprint(y_train.shape)\nprint(X_test.shape)\nprint(y_test.shape)\n\n\n# ### Algorithm 1: Support Vector Machines\n\n# ##### Define a model\n\n# In[89]:\n\n\nclf_svm = SGDClassifier(\n loss='hinge',\n penalty='l2',\n alpha=1e-3,\n random_state=42,\n max_iter=5,\n tol=None)\n\n\n# ##### Fit model on training data\n\n# In[102]:\n\n\nsvm_model = clf_svm.fit(X_train, y_train)\n\n\n# ##### Predicting on test data\n\n# In[103]:\n\n\nsvm_y_pred = svm_model.predict(X_test)\n\n\n# ##### Model evaluation metrics: Accuracy, Precision, Recall, F1 Score\n\n# In[95]:\n\n\nconfusion_matrix(y_test,svm_y_pred)\n\n\n# In[109]:\n\n\nprint('Accuracy %s' % accuracy_score(svm_y_pred, y_test))\nprint('Precision:', precision_score(svm_y_pred, y_test, average='weighted'))\nprint('Recall:', recall_score(svm_y_pred, y_test,average='weighted'))\nprint('F1 score:', f1_score(svm_y_pred, y_test,average='weighted'))\n\n\n# ### Algorithm 2: Light GBM (Light Gradient Boosting Machine Classifier)\n\n# ##### Define a model\n\n# In[112]:\n\n\nclf_lgbm = lgb.LGBMClassifier()\n\n\n# ##### Fit model on training data\n\n# In[ ]:\n\n\nlgbm_model = clf_lgbm.fit(X_train, y_train)\n\n\n# ##### Predicting on test data\n\n# In[ ]:\n\n\nlgbm_y_pred = lgbm_model.predict(X_test)\n\n\n# ##### Model evaluation metrics: Accuracy, Precision, Recall, F1 Score\n\n# In[113]:\n\n\nconfusion_matrix(y_test,lgbm_y_pred)\n\n\n# In[114]:\n\n\nprint('Accuracy %s' % accuracy_score(lgbm_y_pred, y_test))\nprint('Precision:', precision_score(lgbm_y_pred, y_test, average='weighted'))\nprint('Recall:', recall_score(lgbm_y_pred, y_test,average='weighted'))\nprint('F1 score:', f1_score(lgbm_y_pred, y_test,average='weighted'))\n\n\n# ### Algorithm 3: XGB (Extreme Gradient Boost Classifier)\n\n# ##### Define a model\n\n# In[116]:\n\n\nclf_xgb = XGBClassifier()\n\n\n# ##### Fit model on training data\n\n# In[117]:\n\n\nxgb_model = clf_xgb.fit(X_train, y_train)\n\n\n# ##### Predicting on test data\n\n# In[118]:\n\n\nxgb_y_pred = xgb_model.predict(X_test)\n\n\n# ##### Model evaluation metrics: Accuracy, Precision, Recall, F1 Score\n\n# In[119]:\n\n\nconfusion_matrix(y_test,xgb_y_pred)\n\n\n# In[120]:\n\n\nprint('Accuracy %s' % accuracy_score(xgb_y_pred, y_test))\nprint('Precision:', precision_score(xgb_y_pred, y_test, average='weighted'))\nprint('Recall:', recall_score(xgb_y_pred, y_test,average='weighted'))\nprint('F1 score:', f1_score(xgb_y_pred, y_test,average='weighted'))\n\n\n#
\n\n# ## Using an estimate of performance using an appropriate sample\n\n# ### Model Performance Comparison\n\n# In[121]:\n\n\nmodels = {'SVM': [accuracy_score(svm_y_pred, y_test),\n precision_score(svm_y_pred, y_test, average='weighted'),\n recall_score(svm_y_pred, y_test, average='weighted'),\n f1_score(svm_y_pred, y_test,average='weighted')],\n 'LGBM': [accuracy_score(lgbm_y_pred, y_test),\n precision_score(lgbm_y_pred, y_test, average='weighted'),\n recall_score(lgbm_y_pred, y_test,average='weighted'),\n f1_score(lgbm_y_pred, y_test,average='weighted')],\n 'XGB': [accuracy_score(xgb_y_pred, y_test),\n precision_score(xgb_y_pred, y_test, average='weighted'),\n recall_score(xgb_y_pred, y_test,average='weighted'),\n f1_score(xgb_y_pred, y_test,average='weighted')]\n }\n\ndf_models = pd.DataFrame(models, index=['Accuracy', 'Precision', 'Recall', 'F1-Score'])\n\ndf_models\n\n\n# In[125]:\n\n\nplt.rcParams[\"figure.figsize\"] = (15,8)\n\ndf_models.plot.bar(edgecolor = \"white\")\nplt.legend().set_visible(True)\nplt.title(\"Comparing Classification Performance of Multiple Algorithms\")\nplt.xticks(rotation = 0)\nplt.show()\n\n\n\n\n# In[115]:\n\n\nfeat_importances = pd.Series(lgbm_model.feature_importances_, index=X_test.columns)\nfeat_importances.nsmallest(20).plot(kind='barh')\nplt.show()\n\n\n# We can observe that the top 5 features for determining Fraud Transactions are:\n# * posConditionCode=01\n# * merchantCategoryCode=\"furniture\"\n# * creditLimit=250\n# * creditLimit=1000\n# * acqCountry= \" \"\n\n# In[ ]:\n\n\n\n\n","sub_path":"src/SVM_LightGBM_XGB_Fraud_Transaction_Classification.py","file_name":"SVM_LightGBM_XGB_Fraud_Transaction_Classification.py","file_ext":"py","file_size_in_byte":13519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"382045454","text":"\"\"\"\n error_dialog\n\"\"\"\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nimport logging\nimport traceback\nimport sys\nimport platform\n\nfrom PySide import QtGui\nfrom mcedit2.util import qglcontext\n\nfrom mcedit2.util.load_ui import load_ui\n\nlog = logging.getLogger(__name__)\n\ndef showErrorDialog(text, tb, fatal):\n dialog = ErrorDialog(text, tb, fatal)\n dialog.exec_()\n\nclass ErrorDialog(QtGui.QDialog):\n \"\"\"\n A dialog for displaying an error traceback when something goes wrong.\n\n Used to report compile and run errors for plugin modules and classes, and might be\n used to report errors in MCEdit itself during signal or event handlers.\n \"\"\"\n def __init__(self, text, exc_info, fatal):\n super(ErrorDialog, self).__init__()\n load_ui(\"error_dialog.ui\", baseinstance=self)\n\n exc_type, exc_value, exc_tb = exc_info\n\n self.errorDescriptionLabel.setText(text)\n tbText = \"\".join(traceback.format_exception(exc_type, exc_value, exc_tb))\n\n contextInfo = qglcontext.getContextInfo() or \"\"\n\n from mcedit2 import __version__\n tbText = \"MCEdit version: %s\\n\" \\\n \"Python version: %s\\n\" \\\n \"Platform: %s\\n\" \\\n \"System version: %s\\n\" \\\n \"Processor: %s\\n\" \\\n \"\\n\" \\\n \"%s\\n\" \\\n \"------\\n\\n\" \\\n \"%s\\n\\n\" \\\n \"%s\" % (__version__, sys.version, sys.platform,\n platform.platform(), platform.processor(),\n contextInfo, text, tbText)\n self.tracebackView.setText(tbText)\n\n self.restartMCEditLabel.setVisible(fatal)\n\n","sub_path":"src/mcedit2/dialogs/error_dialog.py","file_name":"error_dialog.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"232157661","text":"'''\nCreated on 31/10/2012\n\n@author: jamesd\n'''\n## FIND A WAY IF POSSIBLE TO PUSH THE RIGHT CLICK MENU FROM MAYA BACK INTO THE PYQT WIDGETS??\n############\n### IMPORTS \n############\nfrom PySide.QtGui import *\nfrom PySide.QtCore import *\nimport maya.OpenMayaUI as mui\nimport shiboken\nimport maya.cmds as cmds\n \nclass BD_Widget_ChanBox(QWidget):\n def __init__(self, parent = None):\n QWidget.__init__(self, parent)\n self.Layout = QVBoxLayout(self)\n self.Layout.setObjectName('QChanBox')\n self.wrapChannelBoxQLayout = mui.MQtUtil.fullName(long(shiboken.getCppPointer(self.Layout)[0]))\n try:\n self.pointChanBox = mui.MQtUtil.findLayout('ChannelsLayersPaneLayout')\n self.MayaWrapEditor = shiboken.wrapInstance(long(self.pointChanBox), QWidget)\n self.Layout.addWidget(self.MayaWrapEditor)\n except TypeError:\n cmds.warning('PyQt has lost the channelbox! Restart maya.')\n self.Layout.setContentsMargins(1,1,1,1)\n self.setContentsMargins(1,1,1,1)\n \n def parentMaya(self):\n cmds.paneLayout('ChannelsLayersPaneLayout', edit = True, parent = 'MainChannelsLayersLayout') \n for form in cmds.layout('MainChannelsLayersLayout', query = True, ca = True):\n if 'ChannelButtonForm' in form:\n cmds.formLayout('MainChannelsLayersLayout', edit = True, af = [('ChannelButtonForm', 'top', 0)])\n else:\n cmds.formLayout('MainChannelsLayersLayout', edit = True, af = [(form, 'top', 20), (form, 'left', 0), (form, 'bottom', 0), (form, 'right', 0)])\n \n def parentBD(self):\n self.pointChanBox = mui.MQtUtil.findLayout('ChannelsLayersPaneLayout')\n try:\n self.MayaWrapEditor = shiboken.wrapInstance(long(self.pointChanBox), QWidget)\n except TypeError:\n self.MayaWrapEditor = QWidget() \n self.Layout.addWidget(self.MayaWrapEditor)\n cmds.dockControl('dockControl1', edit = True, visible = False)\n \n def showEvent(self, event):\n QWidget.showEvent(self, event)\n self.parentBD()","sub_path":"BDmaya/main_uiWidgets/BD_Widget_ChanBox.py","file_name":"BD_Widget_ChanBox.py","file_ext":"py","file_size_in_byte":2145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"182671790","text":"import torch\nimport torch.nn as nn\n\n__all__ = ['pmlp', 'palexnet', 'presnet']\n\n\nclass PLinear(nn.Linear):\n\n def __init__(self, in_features, out_features, bias=True):\n super(PLinear, self).__init__(in_features, out_features, bias)\n self.scale = nn.Parameter(torch.ones(out_features))\n self.weight.requires_grad = False\n if bias:\n self.bias.requires_grad = False\n\n def forward(self, input):\n output = input.matmul(self.weight.t()) * self.scale\n if self.bias is not None:\n output += torch.jit._unwrap_optional(self.bias)\n return output\n\n\n### MLP ###\n\nclass PMLP(nn.Module):\n\n def __init__(self, glorot_init, num_classes=10):\n super(PMLP, self).__init__()\n self.FC1 = nn.Sequential(\n nn.PLinear(3 * 32 * 32, 512),\n nn.ReLU(inplace=True)\n )\n self.FC2 = nn.Sequential(\n nn.PLinear(512, 512),\n nn.ReLU(inplace=True)\n )\n self.FC3 = nn.Sequential(\n nn.PLinear(512, 512),\n nn.ReLU(inplace=True)\n )\n self.classifier = nn.PLinear(512, num_classes)\n if glorot_init:\n lins = [self.FC1[0], self.FC2[0], self.FC3[0], self.classifier]\n for l in lins:\n nn.init.xavier_uniform_(l.weight)\n nn.init.zeros_(l.bias)\n\n def forward(self, x):\n x = x.view(-1, 3 * 32 * 32)\n x = self.FC3(self.FC2(self.FC1(x)))\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n\ndef pmlp(**kwargs):\n model = PMLP(**kwargs)\n return model\n\n\n### AlexNet ###\n\nclass PAlexNet(nn.Module):\n\n def __init__(self, num_classes=10):\n super(PAlexNet, self).__init__()\n self.features = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=5),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(64, 192, kernel_size=5, padding=2),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n nn.Conv2d(192, 384, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(384, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.Conv2d(256, 256, kernel_size=3, padding=1),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n self.classifier = nn.PLinear(256, num_classes)\n\n def forward(self, x):\n x = self.features(x)\n x = x.view(x.size(0), -1)\n x = self.classifier(x)\n return x\n\n\ndef palexnet(**kwargs):\n r\"\"\"AlexNet model architecture from the\n `\"One weird trick...\" `_ paper.\n \"\"\"\n model = PAlexNet(**kwargs)\n return model\n\n\n### ResNet ###\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 Bottleneck(nn.Module):\n expansion = 4\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(Bottleneck, self).__init__()\n self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU(inplace=True)\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 out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(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 PResNet(nn.Module):\n\n def __init__(self, depth, num_classes=1000):\n super(PResNet, self).__init__()\n # Model type specifies number of layers for CIFAR-10 model\n assert (depth - 2) % 6 == 0, 'depth should be 6n+2'\n n = (depth - 2) // 6\n\n block = Bottleneck if depth >=44 else BasicBlock\n\n self.inplanes = 16\n self.conv1 = nn.Conv2d(3, 16, kernel_size=3, padding=1,\n bias=False)\n self.bn1 = nn.BatchNorm2d(16)\n self.relu = nn.ReLU(inplace=True)\n self.layer1 = self._make_layer(block, 16, n)\n self.layer2 = self._make_layer(block, 32, n, stride=2)\n self.layer3 = self._make_layer(block, 64, n, stride=2)\n self.avgpool = nn.AvgPool2d(8)\n self.fc = nn.PLinear(64 * 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, math.sqrt(2. / n))\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) # 32x32\n\n x = self.layer1(x) # 32x32\n x = self.layer2(x) # 16x16\n x = self.layer3(x) # 8x8\n\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n\n return x\n\n\ndef presnet(**kwargs):\n \"\"\"\n Constructs a Porcupine ResNet model.\n \"\"\"\n return PResNet(**kwargs)\n\n","sub_path":"models/cifar/pnn.py","file_name":"pnn.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"456599600","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 20 09:34:37 2018\n\n@author: SilverDoe\n\"\"\"\n\n'''\n========================== DataFrame ==========================================\n\npandas.DataFrame( data, index, columns, dtype, copy)\n\nParameters : \n============\n1. data : data takes various forms like ndarray, series, map, lists, dict, constants\n and also another DataFrame.\n \n2. index : For the row labels, the Index to be used for the resulting frame is \n Optional Default np.arrange(n) if no index is passed.\n \n3. columns : For column labels, the optional default syntax is - np.arrange(n). \n This is only true if no index is passed.\n \n4. dtype : Data type of each column.\n\n5. copy : This command (or whatever it is) is used for copying of data, if the \n default is False.\n \n\n'''\n\n#=============== Empty DataFrame =================================================\n\nimport pandas as pd\ndf = pd.DataFrame()\nprint(df)\n\n#============= DataFrame from Lists ============================================\n\n# no index passed, no column names given\nimport pandas as pd\ndata = [1,2,3,4,5]\ndf = pd.DataFrame(data)\nprint(df)\n\n# no index passed, column names given\nimport pandas as pd\ndata = [['Natsu',13],['Lisanna',9],['Happy',1]]\ndf = pd.DataFrame(data,columns=['Name','Age'])\nprint(df)\n\n# no index passed, column names given, datatype passed\nimport pandas as pd\ndata = [['Natsu',13],['Lisanna',8],['Happy',1]]\ndf = pd.DataFrame(data,columns=['Name','Age'],dtype=float)\nprint(df)\n\n\n#========== Dataframe from Dictionary of ndarrays/lists ============================================\n\n''' \n>>All the ndarrays must be of same length. If index is passed, then the length\n of the index should equal to the length of the arrays.\n \n>> To preserve the order of the columns:\n 1. use ordered doctionary, since dictionaries will not preserve the order when created. \n 2. use columns index while creating the dataframe.\n 3. use reorder the columns the way you want by using df = df[list of column names in the order you want]\n \n'''\n \n# using arrays, No index given.\nimport pandas as pd\ndata = {'Name':['Lisanna', 'Natsu', 'Erza', 'Gray'],'Age':[15,20,23,20]}\ndf = pd.DataFrame(data)\nprint(df)\n\n# using arrays, Index given. \nimport pandas as pd\ndata = {'Name':['Lisanna', 'Natsu', 'Erza', 'Gray'],'Age':[15,20,23,20]}\ndf = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])\nprint(df)\n\n'''\n>>List of Dictionaries can be passed as input data to create a DataFrame. The \ndictionary keys are by default taken as column names.\n\n>>NaN (Not a Number) is appended in missing areas when using lists instead of arrays.\n\n'''\n\n# using lists, no index given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\ndf = pd.DataFrame(data)\nprint(df)\n\n# using lists,index given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\ndf = pd.DataFrame(data, index=['first', 'second'])\nprint(df)\n\n# using lists,index given, columns given\nimport pandas as pd\ndata = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]\n\n#With two column indices, values same as dictionary keys\ndf1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])\nprint(df1)\n\n#With two column indices with one index with other name\ndf2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])\nprint(df2)\n\n\n#using dictionary of Series\nimport pandas as pd\n\nd = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),\n 'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}\n\ndf = pd.DataFrame(d)\nprint(df)\n\n\n# using ordered dictionary to preserve the order of the columns\nimport numpy as np\nimport pandas as pd\nfrom collections import OrderedDict\n\na = np.array( [ 1, 2, 3 ] )\nb = np.array( [ 4, 5, 6 ] )\nc = np.array( [ 7, 8, 9 ] )\n\nnd = { 'p': pd.Series(a), 'z': pd.Series(b), 'n': pd.Series(c) } # normal dictionary\nod = OrderedDict( { 'p': pd.Series(a), 'z': pd.Series(b), 'n': pd.Series(c) } ) # ordered doctionary\n\ndf = pd.DataFrame(od)\nprint(df)\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2_Python Advanced/8_Pandas/2_DataFrames.py","file_name":"2_DataFrames.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"647491234","text":"# -*- coding: utf-8 -*-\n\"\"\"\n pyvisa.util\n ~~~~~~~~~~~\n\n General utility functions.\n\n This file is part of PyVISA.\n\n :copyright: 2014 by PyVISA Authors, see AUTHORS for more details.\n :license: MIT, see LICENSE for more details.\n\"\"\"\nimport functools\nimport inspect\nimport io\nimport os\nimport platform\nimport struct\nimport subprocess\nimport sys\nimport warnings\nfrom collections import OrderedDict\nfrom subprocess import check_output\n\nfrom . import __version__, logger\n\ntry:\n import numpy as np\nexcept ImportError:\n np = None\n\n\n#: Length of the header found before a binary block (ieee or hp) that will\n#: trigger a warning to alert the user of a possibly incorrect answer from the\n#: instrument. In general binary block are not prefixed by a header and finding\n#: a long one may mean that we picked up a # in the bulk of the message.\nDEFAULT_LENGTH_BEFORE_BLOCK = 25\n\n\ndef _use_numpy_routines(container):\n \"\"\"Should optimized numpy routines be used to extract the data.\n\n \"\"\"\n if np is None or container in (tuple, list):\n return False\n\n if (container is np.array or (inspect.isclass(container) and\n issubclass(container, np.ndarray))):\n return True\n\n return False\n\n\ndef read_user_library_path():\n \"\"\"Return the library path stored in one of the following configuration files:\n\n /share/pyvisa/.pyvisarc\n ~/.pyvisarc\n\n is the site-specific directory prefix where the platform\n independent Python files are installed.\n\n Example configuration file:\n\n [Paths]\n visa library=/my/path/visa.so\n\n Return `None` if configuration files or keys are not present.\n\n \"\"\"\n from configparser import ConfigParser, NoSectionError, NoOptionError\n\n config_parser = ConfigParser()\n files = config_parser.read([os.path.join(sys.prefix, \"share\", \"pyvisa\",\n \".pyvisarc\"),\n os.path.join(os.path.expanduser(\"~\"),\n \".pyvisarc\")])\n\n if not files:\n logger.debug('No user defined library files')\n return None\n\n logger.debug('User defined library files: %s' % files)\n try:\n return config_parser.get(\"Paths\", \"visa library\")\n except (NoOptionError, NoSectionError):\n logger.debug('NoOptionError or NoSectionError while reading config file')\n return None\n\n\nclass LibraryPath(str):\n\n #: Architectural information (32, ) or (64, ) or (32, 64)\n _arch = None\n\n def __new__(cls, path, found_by='auto'):\n obj = super(LibraryPath, cls).__new__(cls, path)\n obj.path = path\n obj.found_by = found_by\n\n return obj\n\n @property\n def arch(self):\n if self._arch is None:\n try:\n self._arch = get_arch(self.path)\n except Exception:\n self._arch = tuple()\n\n return self._arch\n\n @property\n def is_32bit(self):\n if not self.arch:\n return 'n/a'\n return 32 in self.arch\n\n @property\n def is_64bit(self):\n if not self.arch:\n return 'n/a'\n return 64 in self.arch\n\n @property\n def bitness(self):\n if not self.arch:\n return 'n/a'\n return ', '.join(str(a) for a in self.arch)\n\n\ndef warn_for_invalid_kwargs(keyw, allowed_keys): # pragma: no cover\n warnings.warn('warn_for_invalid_kwargs will be removed in 1.12',\n FutureWarning)\n for key in keyw.keys():\n if key not in allowed_keys:\n warnings.warn('Keyword argument \"%s\" unknown' % key, stacklevel=3)\n\n\ndef filter_kwargs(keyw, selected_keys): # pragma: no cover\n warnings.warn('warn_for_invalid_kwargs will be removed in 1.12',\n FutureWarning)\n result = {}\n for key, value in keyw.items():\n if key in selected_keys:\n result[key] = value\n return result\n\n\ndef split_kwargs(keyw, self_keys, parent_keys, warn=True): # pragma: no cover\n warnings.warn('warn_for_invalid_kwargs will be removed in 1.12',\n FutureWarning)\n self_kwargs = dict()\n parent_kwargs = dict()\n self_keys = set(self_keys)\n parent_keys = set(parent_keys)\n all_keys = self_keys | parent_keys\n for key, value in keyw.items():\n if warn and key not in all_keys:\n warnings.warn('Keyword argument \"%s\" unknown' % key, stacklevel=3)\n if key in self_keys:\n self_kwargs[key] = value\n if key in parent_keys:\n parent_kwargs[key] = value\n\n return self_kwargs, parent_kwargs\n\n\n_converters = {\n 's': str,\n 'b': functools.partial(int, base=2),\n 'c': chr,\n 'd': int,\n 'o': functools.partial(int, base=8),\n 'x': functools.partial(int, base=16),\n 'X': functools.partial(int, base=16),\n 'e': float,\n 'E': float,\n 'f': float,\n 'F': float,\n 'g': float,\n 'G': float,\n}\n\n_np_converters = {\n 'd': 'i',\n 'e': 'd',\n 'E': 'd',\n 'f': 'd',\n 'F': 'd',\n 'g': 'd',\n 'G': 'd',\n}\n\n\ndef from_ascii_block(ascii_data, converter='f', separator=',', container=list):\n \"\"\"Parse ascii data and return an iterable of numbers.\n\n :param ascii_data: data to be parsed.\n :type ascii_data: str\n :param converter: function used to convert each value.\n Defaults to float\n :type converter: callable\n :param separator: a callable that split the str into individual elements.\n If a str is given, data.split(separator) is used.\n :type: separator: (str) -> collections.Iterable[T] | str\n :param container: container type to use for the output data.\n \"\"\"\n if (_use_numpy_routines(container) and\n isinstance(converter, str) and\n isinstance(separator, str) and\n converter in _np_converters):\n return np.fromstring(ascii_data, _np_converters[converter],\n sep=separator)\n\n if isinstance(converter, str):\n try:\n converter = _converters[converter]\n except KeyError:\n raise ValueError('Invalid code for converter: %s not in %s' %\n (converter, str(tuple(_converters.keys()))))\n\n if isinstance(separator, str):\n data = ascii_data.split(separator)\n else:\n data = separator(ascii_data)\n\n return container([converter(raw_value) for raw_value in data])\n\n\ndef to_ascii_block(iterable, converter='f', separator=','):\n \"\"\"Turn an iterable of numbers in an ascii block of data.\n\n :param iterable: data to be parsed.\n :type iterable: collections.Iterable[T]\n :param converter: function used to convert each value.\n String formatting codes are also accepted.\n Defaults to str.\n :type converter: callable | str\n :param separator: a callable that split the str into individual elements.\n If a str is given, data.split(separator) is used.\n :type: separator: (collections.Iterable[T]) -> str | str\n\n :rtype: str\n \"\"\"\n\n if isinstance(separator, str):\n separator = separator.join\n\n if isinstance(converter, str):\n converter = '%' + converter\n block = separator(converter % val for val in iterable)\n else:\n block = separator(converter(val) for val in iterable)\n return block\n\n\ndef parse_ieee_block_header(block, length_before_block=None,\n raise_on_late_block=False) -> (int, int):\n \"\"\"Parse the header of a IEEE block.\n\n Definite Length Arbitrary Block:\n #\n\n The header_length specifies the size of the data_length field.\n And the data_length field specifies the size of the data.\n\n Indefinite Length Arbitrary Block:\n #0\n\n In this case the data length returned will be 0. The actual length can be\n deduced from the block and the offset.\n\n :param block: IEEE block.\n :type block: bytes | bytearray\n :return: (offset, data_length)\n :rtype: (int, int)\n\n \"\"\"\n begin = block.find(b'#')\n if begin < 0:\n raise ValueError(\"Could not find hash sign (#) indicating the start of\"\n \" the block.\")\n\n length_before_block = length_before_block or DEFAULT_LENGTH_BEFORE_BLOCK\n if begin > length_before_block:\n msg = (\"The beginning of the block has been found at %d which \"\n \"is an unexpectedly large value. The actual block may \"\n \"have been missing a beginning marker but the block \"\n \"contained one:\\n%s\") % (begin, repr(block))\n if raise_on_late_block:\n raise RuntimeError(msg)\n else:\n warnings.warn(msg, UserWarning)\n\n try:\n # int(block[begin+1]) != int(block[begin+1:begin+2]) in Python 3\n header_length = int(block[begin+1:begin+2])\n except ValueError:\n header_length = 0\n offset = begin + 2 + header_length\n\n if header_length > 0:\n # #3100DATA\n # 012345\n data_length = int(block[begin+2:offset])\n else:\n # #0DATA\n # 012\n data_length = 0\n\n return offset, data_length\n\n\ndef parse_hp_block_header(block, is_big_endian, length_before_block=None,\n raise_on_late_block=False):\n \"\"\"Parse the header of a HP block.\n\n Definite Length Arbitrary Block:\n #A\n\n The header ia always 4 bytes long.\n The data_length field specifies the size of the data.\n\n :param block: HP block.\n :type block: bytes | bytearray\n :param is_big_endian: boolean indicating endianess.\n :return: (offset, data_length)\n :rtype: (int, int)\n\n \"\"\"\n begin = block.find(b'#A')\n if begin < 0:\n raise ValueError(\"Could not find the standard block header (#A) \"\n \"indicating the start of the block.\")\n\n length_before_block = length_before_block or DEFAULT_LENGTH_BEFORE_BLOCK\n if begin > length_before_block:\n msg = (\"The beginning of the block has been found at %d which \"\n \"is an unexpectedly large value. The actual block may \"\n \"have been missing a beginning marker but the block \"\n \"contained one:\\n%s\") % (begin, repr(block))\n if raise_on_late_block:\n raise RuntimeError(msg)\n else:\n warnings.warn(msg, UserWarning)\n\n offset = begin + 4\n\n data_length = int.from_bytes(block[begin+2:offset],\n byteorder='big' if is_big_endian else 'little'\n )\n\n return offset, data_length\n\n\ndef from_ieee_block(block, datatype='f', is_big_endian=False, container=list):\n \"\"\"Convert a block in the IEEE format into an iterable of numbers.\n\n Definite Length Arbitrary Block:\n #\n\n The header_length specifies the size of the data_length field.\n And the data_length field specifies the size of the data.\n\n Indefinite Length Arbitrary Block:\n #0\n\n :param block: IEEE block.\n :type block: bytes | bytearray\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :param container: container type to use for the output data.\n :return: items\n :rtype: type(container)\n\n \"\"\"\n offset, data_length = parse_ieee_block_header(block)\n\n # If the data length is not reported takes all the data and do not make\n # any assumption about the termination character\n if data_length == 0:\n data_length = len(block) - offset\n\n if len(block) < offset + data_length:\n raise ValueError(\"Binary data is incomplete. The header states %d data\"\n \" bytes, but %d where received.\" %\n (data_length, len(block) - offset))\n\n return from_binary_block(block, offset, data_length, datatype,\n is_big_endian, container)\n\n\ndef from_hp_block(block, datatype='f', is_big_endian=False, container=list):\n \"\"\"Convert a block in the HP format into an iterable of numbers.\n\n Definite Length Arbitrary Block:\n #A\n\n The header ia always 4 bytes long.\n The data_length field specifies the size of the data.\n\n :param block: HP block.\n :type block: bytes | bytearray\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :param container: container type to use for the output data.\n :return: items\n :rtype: type(container)\n \"\"\"\n offset, data_length = parse_hp_block_header(block, is_big_endian)\n\n # If the data length is not reported takes all the data and do not make\n # any assumption about the termination character\n if data_length == 0:\n data_length = len(block) - offset\n\n if len(block) < offset + data_length:\n raise ValueError(\"Binary data is incomplete. The header states %d data\"\n \" bytes, but %d where received.\" %\n (data_length, len(block) - offset))\n\n return from_binary_block(block, offset, data_length, datatype,\n is_big_endian, container)\n\n\ndef from_binary_block(block, offset=0, data_length=None, datatype='f',\n is_big_endian=False, container=list):\n \"\"\"Convert a binary block into an iterable of numbers.\n\n :param block: binary block.\n :type block: bytes | bytearray\n :param offset: offset at which the data block starts (default=0)\n :param data_length: size in bytes of the data block\n (default=len(block) - offset)\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :param container: container type to use for the output data.\n :return: items\n :rtype: type(container)\n \"\"\"\n if data_length is None:\n data_length = len(block) - offset\n\n element_length = struct.calcsize(datatype)\n array_length = int(data_length / element_length)\n\n endianess = '>' if is_big_endian else '<'\n\n if _use_numpy_routines(container):\n return np.frombuffer(block, endianess+datatype, array_length, offset)\n\n fullfmt = '%s%d%s' % (endianess, array_length, datatype)\n\n try:\n return container(struct.unpack_from(fullfmt, block, offset))\n except struct.error:\n raise ValueError(\"Binary data was malformed\")\n\n\ndef to_binary_block(iterable, header, datatype, is_big_endian):\n \"\"\"Convert an iterable of numbers into a block of data with a given header.\n\n :param iterable: an iterable of numbers.\n :param header: the header which should prefix the binary block\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :return: IEEE block.\n :rtype: bytes\n \"\"\"\n array_length = len(iterable)\n\n endianess = '>' if is_big_endian else '<'\n fullfmt = '%s%d%s' % (endianess, array_length, datatype)\n\n if isinstance(header, str):\n header = bytes(header, 'ascii')\n\n return header + struct.pack(fullfmt, *iterable)\n\n\ndef to_ieee_block(iterable, datatype='f', is_big_endian=False):\n \"\"\"Convert an iterable of numbers into a block of data in the IEEE format.\n\n :param iterable: an iterable of numbers.\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :return: IEEE block.\n :rtype: bytes\n \"\"\"\n array_length = len(iterable)\n element_length = struct.calcsize(datatype)\n data_length = array_length * element_length\n\n header = '%d' % data_length\n header = '#%d%s' % (len(header), header)\n\n return to_binary_block(iterable, header, datatype, is_big_endian)\n\n\ndef to_hp_block(iterable, datatype='f', is_big_endian=False):\n \"\"\"Convert an iterable of numbers into a block of data in the HP format.\n\n :param iterable: an iterable of numbers.\n :param datatype: the format string for a single element. See struct module.\n :param is_big_endian: boolean indicating endianess.\n :return: IEEE block.\n :rtype: bytes\n \"\"\"\n\n array_length = len(iterable)\n element_length = struct.calcsize(datatype)\n data_length = array_length * element_length\n\n header = b'#A' + (int.to_bytes(data_length, 2,\n 'big' if is_big_endian else 'little'))\n\n return to_binary_block(iterable, header, datatype, is_big_endian)\n\n\ndef get_system_details(backends=True):\n \"\"\"Return a dictionary with information about the system\n \"\"\"\n buildno, builddate = platform.python_build()\n if sys.maxunicode == 65535:\n # UCS2 build (standard)\n unitype = 'UCS2'\n else:\n # UCS4 build (most recent Linux distros)\n unitype = 'UCS4'\n bits, linkage = platform.architecture()\n\n d = {\n 'platform': platform.platform(),\n 'processor': platform.processor(),\n 'executable': sys.executable,\n 'implementation': getattr(platform, 'python_implementation',\n lambda: 'n/a')(),\n 'python': platform.python_version(),\n 'compiler': platform.python_compiler(),\n 'buildno': buildno,\n 'builddate': builddate,\n 'unicode': unitype,\n 'bits': bits,\n 'pyvisa': __version__,\n 'backends': OrderedDict()\n }\n\n if backends:\n from . import highlevel\n for backend in highlevel.list_backends():\n if backend.startswith('pyvisa-'):\n backend = backend[7:]\n\n try:\n cls = highlevel.get_wrapper_class(backend)\n except Exception as e:\n d['backends'][backend] = ['Could not instantiate backend',\n '-> %s' % str(e)]\n continue\n\n try:\n d['backends'][backend] = cls.get_debug_info()\n except Exception as e:\n d['backends'][backend] = ['Could not obtain debug info',\n '-> %s' % str(e)]\n\n return d\n\n\ndef system_details_to_str(d, indent=''):\n \"\"\"Return a str with the system details.\n\n \"\"\"\n\n l = ['Machine Details:',\n ' Platform ID: %s' % d.get('platform', 'n/a'),\n ' Processor: %s' % d.get('processor', 'n/a'),\n '',\n 'Python:',\n ' Implementation: %s' % d.get('implementation', 'n/a'),\n ' Executable: %s' % d.get('executable', 'n/a'),\n ' Version: %s' % d.get('python', 'n/a'),\n ' Compiler: %s' % d.get('compiler', 'n/a'),\n ' Bits: %s' % d.get('bits', 'n/a'),\n ' Build: %s (#%s)' % (d.get('builddate', 'n/a'),\n d.get('buildno', 'n/a')),\n ' Unicode: %s' % d.get('unicode', 'n/a'),\n '',\n 'PyVISA Version: %s' % d.get('pyvisa', 'n/a'),\n '',\n ]\n\n def _to_list(key, value, indent_level=0):\n sp = ' ' * indent_level * 3\n\n if isinstance(value, str):\n if key:\n return ['%s%s: %s' % (sp, key, value)]\n else:\n return ['%s%s' % (sp, value)]\n\n elif isinstance(value, dict):\n if key:\n al = ['%s%s:' % (sp, key)]\n else:\n al = []\n\n for k, v in value.items():\n al.extend(_to_list(k, v, indent_level+1))\n return al\n\n elif isinstance(value, (tuple, list)):\n if key:\n al = ['%s%s:' % (sp, key)]\n else:\n al = []\n\n for v in value:\n al.extend(_to_list(None, v, indent_level+1))\n\n return al\n\n else:\n return [\"%s\" % value]\n\n l.extend(_to_list('Backends', d['backends']))\n\n joiner = '\\n' + indent\n return indent + joiner.join(l) + '\\n'\n\n\ndef get_debug_info(to_screen=True):\n out = system_details_to_str(get_system_details())\n if not to_screen:\n return out\n print(out)\n\n\ndef pip_install(package): # pragma: no cover\n warnings.warn('warn_for_invalid_kwargs will be removed in 1.12',\n FutureWarning)\n try:\n # noinspection PyPackageRequirements,PyUnresolvedReferences\n import pip\n return pip.main(['install', package])\n except ImportError:\n print(system_details_to_str(get_system_details()))\n raise RuntimeError('Please install pip to continue.')\n\n\nmachine_types = {\n 0: 'UNKNOWN',\n 0x014c: 'I386',\n 0x0162: 'R3000',\n 0x0166: 'R4000',\n 0x0168: 'R10000',\n 0x0169: 'WCEMIPSV2',\n 0x0184: 'ALPHA',\n 0x01a2: 'SH3',\n 0x01a3: 'SH3DSP',\n 0x01a4: 'SH3E',\n 0x01a6: 'SH4',\n 0x01a8: 'SH5',\n 0x01c0: 'ARM',\n 0x01c2: 'THUMB',\n 0x01c4: 'ARMNT',\n 0x01d3: 'AM33',\n 0x01f0: 'POWERPC',\n 0x01f1: 'POWERPCFP',\n 0x0200: 'IA64',\n 0x0266: 'MIPS16',\n 0x0284: 'ALPHA64',\n # 0x0284: 'AXP64', # same\n 0x0366: 'MIPSFPU',\n 0x0466: 'MIPSFPU16',\n 0x0520: 'TRICORE',\n 0x0cef: 'CEF',\n 0x0ebc: 'EBC',\n 0x8664: 'AMD64',\n 0x9041: 'M32R',\n 0xc0ee: 'CEE',\n}\n\n\ndef get_shared_library_arch(filename):\n with io.open(filename, 'rb') as fp:\n dos_headers = fp.read(64)\n _ = fp.read(4)\n\n magic, skip, offset = struct.unpack(\"=2s58sl\", dos_headers)\n\n if magic != b'MZ':\n raise Exception('Not an executable')\n\n fp.seek(offset, io.SEEK_SET)\n pe_header = fp.read(6)\n\n sig, skip, machine = struct.unpack(str('=2s2sH'), pe_header)\n\n if sig != b'PE':\n raise Exception('Not a PE executable')\n\n return machine_types.get(machine, 'UNKNOWN')\n\n\ndef get_arch(filename):\n this_platform = sys.platform\n if this_platform.startswith('win'):\n machine_type = get_shared_library_arch(filename)\n if machine_type == 'I386':\n return 32,\n elif machine_type in ('IA64', 'AMD64'):\n return 64,\n else:\n return ()\n elif this_platform not in ('linux2', 'linux3', 'linux', 'darwin'):\n raise OSError('Unsupported platform: %s' % this_platform)\n\n out = subprocess.run([\"file\", filename], capture_output=True)\n out = out.stdout.decode(\"ascii\")\n print(out)\n ret = []\n if this_platform.startswith('linux'):\n if '32-bit' in out:\n ret.append(32)\n if '64-bit' in out:\n ret.append(64)\n else: # darwin\n if '(for architecture i386)' in out:\n ret.append(32)\n if '(for architecture x86_64)' in out:\n ret.append(64)\n\n return tuple(ret)\n","sub_path":"pyvisa/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":22766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"559896167","text":"from Corpus.Sentence import Sentence\n\n\nclass UniversalDependencyTreeBankSentence(Sentence):\n\n comments: list\n\n def __init__(self):\n super().__init__()\n self.comments = []\n\n def addComment(self, comment: str):\n self.comments.append(comment)\n\n def __str__(self) -> str:\n result = \"\"\n for comment in self.comments:\n result += comment + \"\\n\"\n for word in self.words:\n result += word.__str__() + \"\\n\"\n return result\n","sub_path":"DependencyParser/Universal/UniversalDependencyTreeBankSentence.py","file_name":"UniversalDependencyTreeBankSentence.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"500903604","text":"from django.db import models\nfrom django.db.models import options\nfrom django.db.models.aggregates import Sum\nfrom django.utils.translation import ugettext as _\n\nfrom django_extensions.db.fields import (ModificationDateTimeField,\n CreationDateTimeField)\n\nfrom bluebottle.utils.fields import ImageField\nfrom bluebottle.utils.utils import GetTweetMixin, StatusDefinition\n\n\nclass BaseFundraiser(models.Model, GetTweetMixin):\n owner = models.ForeignKey('members.Member',\n verbose_name=_(\"initiator\"),\n help_text=_(\"Project owner\"))\n project = models.ForeignKey('projects.Project',\n verbose_name=_(\"project\"))\n\n title = models.CharField(_(\"title\"), max_length=255)\n description = models.TextField(_(\"description\"), blank=True)\n image = ImageField(_(\"picture\"), max_length=255, blank=True, null=True,\n upload_to='fundraiser_images/',\n help_text=_(\"Minimal of 800px wide\"))\n video_url = models.URLField(max_length=100, blank=True, default='')\n\n amount = models.DecimalField(_(\"amount\"), decimal_places=2, max_digits=10)\n currency = models.CharField(max_length=10, default='EUR')\n deadline = models.DateTimeField(null=True)\n\n created = CreationDateTimeField(_(\"created\"), help_text=_(\n \"When this fundraiser was created.\"))\n updated = ModificationDateTimeField(_('updated'))\n deleted = models.DateTimeField(_('deleted'), blank=True, null=True)\n\n location = models.ForeignKey('geo.Location', null=True, blank=True)\n\n def __unicode__(self):\n return self.title\n\n @property\n def amount_donated(self):\n donations = self.donation_set.filter(\n order__status__in=[StatusDefinition.SUCCESS,\n StatusDefinition.PENDING])\n if donations:\n total = donations.aggregate(sum=Sum('amount'))\n return total['sum']\n return 0.0\n\n class Meta():\n abstract = True\n","sub_path":"bluebottle/bb_fundraisers/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"481322377","text":"import os\ndef get_ex_file(wrong_file_name, path):\n files = os.listdir(path)\n words = wrong_file_name.split()\n samples = []\n more = []\n cnt = 0\n file_split = [i.split() for i in files]\n values = [compare(words, i) for i in file_split] \n return os.path.join(path, files[values.index(max(values))]).replace(\"\\\\\\\\\", \"/\").replace(\"\\\\\", \"/\")\n\ndef compare(list1, list2):\n cnt = 0\n for i, j in zip(list1, list2):\n if i.lower() == j.lower():\n cnt+=1\n return cnt\ndef get_sub_folder_path(path):\n return path[:path.rindex('/')]\ndef replace_string(list, word, w=\"\"):\n for i in list:\n word = word.replace(i, \"\")\n return word\n\ndef rm(wrong_file_name, path):\n list = ['.', \",\"]\n files = os.listdir(path)\n file_split = [i.split() for i in files]\n file = replace_string(list, wrong_file_name, w=\"\")\n for i in files:\n if file in i:\n return os.path.join(path, i).replace(\"\\\\\", \"/\")\n else:\n pass\n return None\nif __name__==\"__main__\":\n print(rm(\"Eredaze - Save Me (feat. Luke & Jolle) (Audio)\", 'D:\\Programs\\Advanced Youtube Downloader\\TestMp3'))\n","sub_path":"utils/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"323462215","text":"import logging\nimport string\nimport subprocess\nimport os\nimport selectors\nimport sys\nfrom collections import namedtuple\n\nfrom .board import KERNEL_RELEASE, L4T_VERSION, AVT_RELEASE\n\nTools = namedtuple('Tools', ['extract', 'execute', 'apply_template','get_template_args'])\n\ndef tools(args):\n def get_template_args(board):\n avt_release = os.getenv('AVT_RELEASE')\n\n if avt_release is None:\n process = subprocess.run(['git','rev-parse','--short','HEAD'],stdout=subprocess.PIPE)\n git_hash = process.stdout.decode(\"utf-8\").strip()\n avt_release = f'{AVT_RELEASE}~g{git_hash}'\n\n template_args = {\n \"L4T_TOOLS_VERSION\": board.l4t_tools_version,\n \"KERNEL_RELEASE\": KERNEL_RELEASE,\n \"L4T_VERSION\": L4T_VERSION,\n \"AVT_RELEASE\": avt_release,\n \"BOARD_NAME\": board.bundle_name\n }\n return template_args\n\n def apply_template(src, dest, board):\n template_args = get_template_args(board)\n\n fin = open(src, 'rt')\n template = string.Template(fin.read())\n fin.close()\n fout = open(dest, 'wt')\n fout.write(template.substitute(template_args))\n fout.close()\n\n def execute(args, **kwargs):\n src = args[0]\n try:\n sudo = kwargs.get('sudo', False)\n stdin = None\n if sudo:\n args = ['sudo', '-S', '-n'] + args\n stdin = subprocess.PIPE\n src = 'sudo ' + src\n\n outfile = kwargs.get('outfile', subprocess.PIPE)\n\n sub = subprocess.Popen(args, bufsize=1, stdout=outfile, stderr=subprocess.PIPE, cwd=kwargs.get('cwd', None), env=kwargs.get('env', None))\n\n logging.verbose(f\"Executing `{' '.join(str(x) for x in args)}`\")\n\n sel = selectors.DefaultSelector()\n if outfile == subprocess.PIPE:\n sel.register(sub.stdout, selectors.EVENT_READ)\n sel.register(sub.stderr, selectors.EVENT_READ)\n stderr_log = \"\"\n stdout_log = \"\"\n while sub.poll() == None:\n events = sel.select()\n for k, _ in events:\n fd = k.fileobj\n data = fd.readline().decode('UTF-8')\n\n if len(data) > 0:\n data = data.rstrip()\n if fd == sub.stdout:\n stdout_log += data + \"\\n\"\n logging.debug(f'({src},stdout) {data}')\n elif fd == sub.stderr:\n stderr_log += data + \"\\n\"\n logging.debug(f'({src},stderr) {data}')\n\n if sub.returncode != 0:\n logging.error(f'Error {sub.returncode} executing `{\" \".join(str(x) for x in args)}`')\n logging.error(f'stdout:\\n{stdout_log}\\nstderr:\\n{stderr_log}')\n raise RuntimeError(f'Subprocess returned error {sub.returncode}')\n\n except Exception as err:\n raise RuntimeError(f'Error {str(err)} executing `{\" \".join(str(x) for x in args)}`') from err\n \n\n def extract(archive_file, destination, **kwargs):\n logging.verbose(f'Extracting {archive_file.local_file} to {destination}')\n os.makedirs(destination, exist_ok=True)\n suffixes = archive_file.local_file.suffixes\n args = []\n if '.tbz2' in suffixes or '.tgz' in suffixes or '.tar' in suffixes:\n strip = kwargs.get('strip', None)\n cmd = 'xfv'\n if '.xz' in suffixes:\n cmd = cmd + 'J'\n elif '.bz2' in suffixes or '.tbz2' in suffixes:\n cmd = cmd + 'j'\n elif '.gz' in suffixes or '.tgz' in suffixes:\n cmd = cmd + 'z'\n\n args.extend(['tar', cmd, archive_file.local_file])\n if strip:\n args.append(f'--strip-components={strip}')\n args.extend(['-C', destination])\n\n if kwargs.get('sudo', False):\n args.insert(0, 'sudo')\n\n try:\n execute(args)\n except Exception as err:\n logging.error(f'Failed to extract {archive_file.local_file}')\n raise RuntimeError(f'Error extracting archive') from err\n\n return Tools(extract=extract, execute=execute, apply_template=apply_template, get_template_args=get_template_args)\n","sub_path":"avt_build/jetson_build/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":3845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"3779123","text":"import subprocess\nfrom Tkinter import *\nimport threading\nimport subprocess\n\n\n\n\nlabelList = list()\n\ndef scan():\n output = subprocess.check_output((\"arp\", \"-a\"))\n for line in output.splitlines():\n print(line)\n list = str(line).split(' ')\n label = Label(root, text=\"Device Name: \" + list[0] + \"; Hardware Address: \" + list[3] + \" is active at IP: \" + list[1], fg=\"green4\", borderwidth = 2, relief = \"groove\")\n labelList.append(label)\n label.pack()\n\n\n\ndef button1():\n threading.Thread(target=scan).start()\n\ndef button2():\n for label in labelList:\n label.destroy()\n\n\nroot = Tk()\nroot.title(\"Network Scanner\")\nroot.geometry(\"650x650\")\nframe = Frame(root,width=1000,height=1000,bd=2,relief=GROOVE)\nframe.pack()\n\nbutton1 = Button(frame, text = \"Scan Your Network\", command = button1)\nbutton2 = Button(frame, text = \"Clear Screen\", command = button2)\nbutton1.pack()\nbutton2.pack()\n\nroot.mainloop()","sub_path":"GUILanScan.py","file_name":"GUILanScan.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"306946353","text":"\nimport binascii\nimport json\n\nimport requests\nimport sys\nfrom base58 import b58decode\nfrom neocore.IO.BinaryWriter import BinaryWriter\nfrom neocore.BigInteger import BigInteger\nfrom neo.Core.TX.InvocationTransaction import InvocationTransaction\nfrom neo.Core.TX.Transaction import TransactionOutput,TransactionInput\nfrom neo.Core.Blockchain import Blockchain\nfrom neocore.Cryptography.Crypto import Crypto\nfrom neocore.Fixed8 import Fixed8\nfrom neocore.UInt160 import UInt160\nfrom neocore.UInt256 import UInt256\nfrom neo.IO.MemoryStream import MemoryStream\nfrom neo.SmartContract.ContractParameterContext import ContractParametersContext\nfrom neo.VM.ScriptBuilder import ScriptBuilder, PACK\nfrom neo.Wallets.NEP5Token import NEP5Token\n\n\n\n\n\n# address_to = \"AbZNDqwCSZj4XJSGHmbQTSoHofE2PRMurT\"\n# address_from = \"AGgZna4kbTXPm16yYZyG6RyrQz2Sqotno6\"\n# tnc_amount = 7\n# gas_change = None\n# input_txid = None\n# preIndex = None\n# contract_hash =\"849d095d07950b9e56d0c895ec48ec5100cfdff1\"\n# private_key = \"0d94b060fe4a5f382174f75f3dca384ebc59c729cef92d553084c7c660a4c08f\"\n# public_key = \"023886d5529481223f94d422bb6a1e05b0f831e2628c3200373a986b8208ff1c26\"\n\ndef get_gas_balance(address):\n url = \"http://192.168.203.64:8000/api/getBalance\"\n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = {\n \"address\": address\n }\n res = requests.post(url, headers=headers, json=data).json()\n if res:\n return res[\"gasBalance\"]\n return None\n\n\ndef get_gas_vouts(address):\n\n url = \"http://192.168.203.64:8000/api/getGasVout\"\n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = {\n \"address\": address\n }\n res = requests.post(url, headers=headers, json=data).json()\n\n return res\n\n\n\ndef send_rawtransaction(hexstr):\n url = \"http://192.168.203.64:20332\"\n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = {\n \"jsonrpc\": \"2.0\",\n \"method\": \"sendrawtransaction\",\n \"params\": [hexstr],\n \"id\": 1\n }\n res = requests.post(url, headers=headers, json=data).json()\n if res[\"result\"]:\n return \"sucess\"\n return \"fail\"\n\n\ndef amount_from_string(token, amount_str):\n precision_mult = pow(10, token.decimals)\n amount = float(amount_str) * precision_mult\n\n return int(amount)\n\n\ndef get_nep5token_id(contract_hash):\n hash_ar = bytearray(binascii.unhexlify(contract_hash))\n hash_ar.reverse()\n hash = UInt160(data=hash_ar)\n token = NEP5Token()\n token.SetScriptHash(hash)\n # token.symbol = \"TNC\"\n token.decimals = 8\n\n return token\n\n\ndef ToScriptHash(address):\n data = b58decode(address)\n if len(data) != 25:\n raise ValueError('Not correct Address, wrong length.')\n if data[0] != 23:\n raise ValueError('Not correct Coin Version')\n\n checksum = Crypto.Default().Hash256(data[:21])[:4]\n if checksum != data[21:]:\n raise Exception('Address format error')\n return UInt160(data=data[1:21])\n\n\ndef get_asset_id(asset_type):\n assetId = None\n\n if asset_type.lower() == 'neo':\n assetId = Blockchain.Default().SystemShare().Hash\n elif asset_type.lower() == 'gas':\n assetId = Blockchain.Default().SystemCoin().Hash\n elif Blockchain.Default().GetAssetState(asset_type):\n assetId = Blockchain.Default().GetAssetState(asset_type).AssetId\n\n return assetId\n\n\ndef hex_reverse(input):\n tmp_list = []\n for i in range(0, len(input), 2):\n tmp_list.append(input[i:i + 2])\n hex_str = \"\".join(list(reversed(tmp_list)))\n return hex_str\n\n\ndef get_tx_data(tx):\n ms = MemoryStream()\n w = BinaryWriter(ms)\n tx.Serialize(w)\n ms.flush()\n tx_data = ms.ToArray().decode()\n return tx_data\n\n\ndef toArray(obj):\n ms = MemoryStream()\n w = BinaryWriter(ms)\n obj.Serialize(w)\n ms.flush()\n return ms.ToArray().decode()\n\n\ndef create_tx(contract_hash,address_from,address_to,tnc_amount,gas_change,input_txid,preIndex):\n\n nep5TokenId=get_nep5token_id(contract_hash)\n scripthash_from=ToScriptHash(address_from)\n scripthash_to=ToScriptHash(address_to)\n f8amount=amount_from_string(nep5TokenId,tnc_amount)\n f8amount_change = Fixed8.TryParse(gas_change, require_positive=True)\n assetId=get_asset_id(\"gas\")\n preHash=UInt256(data=binascii.unhexlify(hex_reverse(input_txid)))\n\n input = TransactionInput(prevHash=preHash, prevIndex=preIndex)\n output = TransactionOutput(AssetId=assetId, Value=f8amount_change, script_hash=scripthash_from)\n\n tx = InvocationTransaction(outputs=[output], inputs=[input])\n tx.Version = 1\n context = ContractParametersContext(tx)\n tx.scripts = context.GetScripts()\n\n\n\n\n invoke_args=[nep5TokenId.ScriptHash, 'transfer',[bytearray.fromhex(hex_reverse(scripthash_from.ToString())),\n bytearray.fromhex(hex_reverse(scripthash_to.ToString())),\n BigInteger(f8amount)]]\n sb = ScriptBuilder()\n invoke_args.reverse()\n for item in invoke_args[:2]:\n if type(item) is list:\n item.reverse()\n listlength = len(item)\n for listitem in item:\n sb.push(listitem)\n sb.push(listlength)\n sb.Emit(PACK)\n else:\n sb.push(binascii.hexlify(item.encode()))\n\n sb.EmitAppCall(nep5TokenId.ScriptHash.ToArray())\n\n\n op_data = sb.ToArray().decode()\n tx.Script = binascii.unhexlify(op_data)\n tx_data=get_tx_data(tx)[:-2]\n print (\"tx_data:\",tx_data)\n signstr =binascii.hexlify(Crypto.Sign(message=tx_data, private_key=private_key)).decode()\n rawtx_data = tx_data + \"014140\" + signstr + \"2321\" + public_key + \"ac\"\n return rawtx_data\n\n\n\n","sub_path":"src/neo_python_tool/rpcServer/transfer_tnc.py","file_name":"transfer_tnc.py","file_ext":"py","file_size_in_byte":5769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"305242325","text":"# see also https://github.com/sourcefabric-innovation/citizendesk-core/blob/master/src/citizendesk/feeds/any/coverage/storage.py#L18\nentity = {\n 'schema': {\n 'title': {\n 'type': 'string',\n 'required': True\n },\n 'description': {'type': 'string'},\n 'active': {'type': 'boolean'},\n },\n 'resource_methods': ['GET', 'POST'],\n 'item_methods': ['GET', 'PUT', 'DELETE', 'PATCH'],\n 'pagination': False,\n}\n","sub_path":"citizendesk_interface/entities/coverages.py","file_name":"coverages.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"359515098","text":"import h5py\nimport numpy as np\nimport sys\nfrom pysingfel.util import symmpdb\nfrom pysingfel.ff_waaskirf_database import *\nimport pysingfel.particle\nfrom scipy.spatial import distance\n\ndef max_radius(particles):\n radius_current = 0\n for particle in particles:\n radius_arr = particle.atom_pos - np.mean(particle.atom_pos, axis=0)\n for row in radius_arr:\n radius = np.sqrt(row[0]**2+row[1]**2+row[2]**2)\n if radius > radius_current:\n radius_current = radius\n radius_max = radius_current\n return radius_max\n\n\ndef distribute_particles(particles, beam_focus_radius, jet_radius): #beam_focus_radius = 10e-6 #jet_radius = 1e-4\n state = []\n for particle in particles:\n for count in range(particles[particle]):\n state.append(particle)\n radius_max = max_radius(particles)\n N = sum(particles.values()) # total number of particles\n coords = np.zeros((N,3)) # initialize N*3 array\n # generate N*3 random positions\n for i in range(N):\n coords[i,0] = beam_focus_radius*np.random.uniform(-1, 1)\n coords[i,1] = beam_focus_radius*np.random.uniform(-1, 1)\n coords[i,2] = jet_radius*np.random.uniform(-1, 1)\n # calculate N*N distance matrix\n dist_matrix = distance.cdist(coords, coords, 'euclidean')\n # collision detection check (<2 maxRadius)\n collision = dist_matrix < 2*radius_max\n checkList = [collision[i][j] for i in range(N) for j in range(N) if j > i]\n if any(item == True for item in checkList):\n distribute_particles(particles, beam_focus_radius, jet_radius)\n return state, coords\n\n\ndef position_in_3d(particles, beam_focus_radius, jet_radius):\n state, coords = distribute_particles(particles, beam_focus_radius, jet_radius)\n x = np.array([])\n y = np.array([])\n z = np.array([])\n for i in range(len(state)):\n x = np.concatenate([x,state[i].atom_pos[:,0]+coords[i][0]])\n y = np.concatenate([y,state[i].atom_pos[:,1]+coords[i][1]])\n z = np.concatenate([z,state[i].atom_pos[:,2]+coords[i][2]])\n return x, y, z\n","sub_path":"pysingfel/particlePlacement.py","file_name":"particlePlacement.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"478945157","text":"from directory_components.decorators import skip_ga360\nfrom django.conf.urls import url\nfrom perfect_fit_prospectus.views import PerfectFitProspectusMainView, \\\n PerfectFitProspectusReportProxyView, PerfectFitProspectusSuccessView\n\n\nurlpatterns = [\n url(\n '^$',\n skip_ga360(PerfectFitProspectusMainView.as_view()),\n name='main'\n ),\n url(\n '^success/$',\n skip_ga360(PerfectFitProspectusSuccessView.as_view()),\n name='success'\n ),\n url(\n '^reports/(?P.*)$',\n skip_ga360(PerfectFitProspectusReportProxyView.as_view()),\n name='report'\n ),\n]\n","sub_path":"perfect_fit_prospectus/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"517862850","text":"from tastypie.authentication import ApiKeyAuthentication\nfrom tastypie.authorization import DjangoAuthorization\nfrom tastypie.resources import ModelResource, ALL\n\nfrom ui.models import Record\n\n\nclass RecordResource(ModelResource):\n class Meta:\n queryset = Record.objects.all()\n resource_name = 'record'\n authentication = ApiKeyAuthentication()\n authorization = DjangoAuthorization()\n filtering = {\n 'hostname': ALL,\n 'event': ALL,\n 'timestamp': ALL,\n }\n","sub_path":"loggins/ui/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"84735082","text":"# Default location for this file is ~/.homeassistant/apps/switch_reset.py\r\nimport appdaemon.appapi as appapi\r\nimport shelve\r\nimport time\r\nimport pdb\r\n\r\n#\r\n# App to reset input_boolean, input_select, input_slider, device_tracker to previous values after HA restart\r\n#\r\n# Args:\r\n#\r\n#delay - amount of time after restart to set the switches\r\n# \r\n#\r\n# Release Notes\r\n#\r\n# Version 1.0:\r\n# Initial Version\r\n\r\nclass SwitchReset(appapi.AppDaemon):\r\n\r\n def initialize(self):\r\n \r\n self.listen_event(self.ha_event, \"ha_started\")\r\n self.listen_event(self.appd_event, \"appd_started\")\r\n self.listen_state(self.state_change, \"input_boolean\")\r\n self.listen_state(self.state_change, \"input_select\")\r\n self.listen_state(self.state_change, \"input_slider\")\r\n if \"additional_entities\" in self.args:\r\n self.additional_entities = [x.strip() for x in self.args[\"additional_entities\"].split(\",\")]\r\n\r\n for entity in self.additional_entities:\r\n self.listen_state(self.state_change, entity)\r\n\r\n def ha_event(self, event_name, data, kwargs):\r\n self.log_notify(\"Home Assistant restart detected\")\r\n self.run_in(self.set_switches, self.args[\"delay\"])\r\n \r\n def appd_event(self, event_name, data, kwargs):\r\n self.log_notify(\"AppDaemon restart detected\")\r\n self.run_in(self.set_switches, self.args[\"delay\"])\r\n\r\n def state_change(self, entity, attribute, old, new, kwargs):\r\n dev_db = shelve.open(self.args[\"file\"])\r\n type, id = entity.split(\".\")\r\n\r\n if type == \"climate\":\r\n climate_dict = { 'temperature': self.get_state(entity, 'temperature'), 'operation_mode': self.get_state(entity, 'operation_mode') }\r\n if dev_db[entity] != climate_dict:\r\n dev_db[entity] = climate_dict\r\n self.log_notify(\"State change: {} to {}\".format(entity, climate_dict))\r\n else:\r\n dev_db[entity] = new\r\n self.log_notify(\"State change: {} to {}\".format(entity, new))\r\n\r\n dev_db.close()\r\n\r\n def set_switches(self, kwargs):\r\n dev_db = shelve.open(self.args[\"file\"])\r\n self.log_notify(\"Setting switches\")\r\n # Find out what devices are avaiable.\r\n # If we don't know about it initialize, if we do set the switch appropriately\r\n state = self.get_state()\r\n for entity in state:\r\n type, id = entity.split(\".\")\r\n if type == \"input_boolean\" or type == \"input_select\" or type == \"input_slider\" or (entity in self.additional_entities):\r\n if entity in dev_db:\r\n if type != \"climate\":\r\n if dev_db[entity] != state[entity][\"state\"]:\r\n self.log_notify(\"Setting {} to {} (was {})\".format(entity, dev_db[entity], state[entity][\"state\"]))\r\n new_state = self.set_state(entity, state = dev_db[entity])\r\n else:\r\n temp = self.get_state(entity, \"temperature\")\r\n mode = self.get_state(entity, \"operation_mode\")\r\n\r\n if dev_db[entity][\"temperature\"] != temp:\r\n self.log_notify(\"Setting {} to {} (was {})\".format(entity, dev_db[entity], temp))\r\n new_state = self.call_service(\"climate/set_temperature\", temperature = dev_db[entity][\"temperature\"], entity_id = entity)\r\n if dev_db[entity][\"operation_mode\"] != mode:\r\n self.log_notify(\"Setting {} to {} (was {})\".format(entity, dev_db[entity], temp))\r\n new_state = self.call_service(\"climate/set_operation_mode\", operation_mode = dev_db[entity][\"operation_mode\"], entity_id = entity)\r\n else:\r\n self.log_notify(\"Adding {}, setting value to current state ({})\".format(entity, state[entity][\"state\"]))\r\n if type != \"climate\":\r\n dev_db[entity] = state[entity][\"state\"]\r\n else:\r\n dev_db[entity] = self.get_state(entity, \"temperature\")\r\n\r\n dev_db.close()\r\n \r\n def log_notify(self, message, level = \"INFO\"):\r\n if \"log\" in self.args:\r\n self.log(message)\r\n if \"notify\" in self.args:\r\n self.notify(message, \"ios\", name=\"ios\")","sub_path":"appdaemon/apps/switch_reset.py","file_name":"switch_reset.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"227976291","text":"# -*- coding: utf-8 -*-\n\"\"\"\nauthor: 周行健\ncreate time: 2020/7/13\nupdate time: 2020/7/19\n\"\"\"\n\n\nimport numpy as np\nimport tensorflow.compat.v1 as tf\ntf.disable_v2_behavior()\n#pip install pillow\nfrom PIL import Image\nimport os\n\n\n\n\n\n# 定义卷积函数\ndef conv_layer(inputs, W, b, conv_strides, kernel_size, pool_strides, padding):\n L1_conv = tf.nn.conv2d(inputs, W, strides=conv_strides, padding=padding)\n L1_relu = tf.nn.relu(L1_conv + b)\n return tf.nn.max_pool(L1_relu, ksize=kernel_size, strides=pool_strides, padding='SAME')\n\n# 定义全连接层函数\ndef full_connect(inputs, W, b):\n return tf.nn.relu(tf.matmul(inputs, W) + b)\n\ndef predict():\n#if __name__ =='__main__' and sys.argv[1]=='predict':\n SIZE = 1280\n WIDTH = 32\n HEIGHT = 40\n NUM_CLASSES = 34\n\n SAVER_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'License_plate/train-saver/digits/')\n\n LETTERS_DIGITS = (\"0\",\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"J\",\"K\",\"L\",\"M\",\"N\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\")\n\n result_digits = []\n\n # 定义输入节点,对应于图片像素值矩阵集合和图片标签(即所代表的数字)\n #tf.placeholder为tf1的API\n x = tf.placeholder(tf.float32, shape=[None, SIZE])\n y_ = tf.placeholder(tf.float32, shape=[None, NUM_CLASSES])\n\n x_image = tf.reshape(x, [-1, WIDTH, HEIGHT, 1])\n license_num = \"\"\n\n saver = tf.train.import_meta_graph(\"%smodel.ckpt.meta\"%(SAVER_DIR))\n with tf.Session() as sess:\n model_file=tf.train.latest_checkpoint(SAVER_DIR)\n sess.run(tf.global_variables_initializer())\n sess.run(tf.local_variables_initializer())\n saver.restore(sess, model_file)\n\n # 第一个卷积层\n W_conv1 = sess.graph.get_tensor_by_name(\"W_conv1:0\")\n b_conv1 = sess.graph.get_tensor_by_name(\"b_conv1:0\")\n conv_strides = [1, 1, 1, 1]\n kernel_size = [1, 2, 2, 1]\n pool_strides = [1, 2, 2, 1]\n L1_pool = conv_layer(x_image, W_conv1, b_conv1, conv_strides, kernel_size, pool_strides, padding='SAME')\n\n # 第二个卷积层\n W_conv2 = sess.graph.get_tensor_by_name(\"W_conv2:0\")\n b_conv2 = sess.graph.get_tensor_by_name(\"b_conv2:0\")\n conv_strides = [1, 1, 1, 1]\n kernel_size = [1, 1, 1, 1]\n pool_strides = [1, 1, 1, 1]\n L2_pool = conv_layer(L1_pool, W_conv2, b_conv2, conv_strides, kernel_size, pool_strides, padding='SAME')\n\n\n # 全连接层\n W_fc1 = sess.graph.get_tensor_by_name(\"W_fc1:0\")\n b_fc1 = sess.graph.get_tensor_by_name(\"b_fc1:0\")\n h_pool2_flat = tf.reshape(L2_pool, [-1, 16 * 20*32])\n h_fc1 = full_connect(h_pool2_flat, W_fc1, b_fc1)\n\n\n # dropout\n keep_prob = tf.placeholder(tf.float32)\n\n h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)\n\n\n # readout层\n W_fc2 = sess.graph.get_tensor_by_name(\"W_fc2:0\")\n b_fc2 = sess.graph.get_tensor_by_name(\"b_fc2:0\")\n\n # 定义优化器和训练op\n conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n\n for n in range(3,8):\n cache_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),\n 'License_plate/cache/')\n\n path = cache_path +str(n) + '.bmp'\n img = Image.open(path)\n img = img.convert(\"1\")\n width = img.size[0]\n height = img.size[1]\n\n img_data = [[0]*SIZE for i in range(1)]\n for h in range(0, height):\n for w in range(0, width):\n if img.getpixel((w, h)) < 190:\n img_data[0][w+h*width] = 1\n else:\n img_data[0][w+h*width] = 0\n\n result = sess.run(conv, feed_dict = {x: np.array(img_data), keep_prob: 1.0})\n\n max1 = 0\n max2 = 0\n max3 = 0\n max1_index = 0\n max2_index = 0\n max3_index = 0\n for j in range(NUM_CLASSES):\n if result[0][j] > max1:\n max1 = result[0][j]\n max1_index = j\n continue\n if (result[0][j]>max2) and (result[0][j]<=max1):\n max2 = result[0][j]\n max2_index = j\n continue\n if (result[0][j]>max3) and (result[0][j]<=max2):\n max3 = result[0][j]\n max3_index = j\n continue\n\n license_num = license_num + LETTERS_DIGITS[max1_index]\n #print (\"概率: [%s %0.2f%%] [%s %0.2f%%] [%s %0.2f%%]\" % (LETTERS_DIGITS[max1_index],max1*100, LETTERS_DIGITS[max2_index],max2*100, LETTERS_DIGITS[max3_index],max3*100))\n results = LETTERS_DIGITS[max1_index] + '\\t' + str(max1*100) + '%'\n #print(results)\n result_digits.append(results)\n #print(result_digits)\n #print(result_digits[0])\n #print (\"车牌编号是: 【%s】\" % license_num)\n return result_digits\n\n\n#predict()","sub_path":"rear/VehicleIdentificationSystem/VehicleIdentificationSystem/license/License_plate/predict_digits.py","file_name":"predict_digits.py","file_ext":"py","file_size_in_byte":5113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"466899612","text":"import tkinter as tk\n\nclass ShowImage(tk.Toplevel):\n def __init__(self, parent=None, x0=0, y0=0):\n tk.Toplevel.__init__(self, parent)\n self.title('미리보기')\n self.wm_attributes('-topmost', True)\n\n self.label = tk.Label(self)\n self.label.pack(fill='both', expand=True)\n\n self.geometry('{}x{}+{}+{}'.format(310, 310, x0, y0))\n\n self.imgNum =0\n self.maxImgNum=0\n self.parent =parent\n\n def setImage(self, image):\n self.label.configure(image= image)\n self.label.image= image\n\n def choice(self, imageControl):\n width = imageControl.fullWidth\n height = int(imageControl.fullHeight / imageControl.imgNum)\n\n self.maxImgNum = imageControl.imgNum -1\n\n self.geometry('{}x{}+{}+{}'.format(width, height, 0, 0))\n self.frame1= tk.Frame(self)\n self.btn_next = tk.Button(self.frame1, text='다음', command=lambda:self.command_next())\n self.btn_prev = tk.Button(self.frame1, text='이전', command=lambda:self.command_prev())\n self.btn_del = tk.Button(self.frame1, text='삭제', command=lambda:self.command_del())\n self.btn_end = tk.Button(self.frame1, text='완료', command=lambda:self.command_end())\n\n self.btn_next.grid(row=0, column=0, padx=5)\n self.btn_prev.grid(row=0, column=1, padx=5)\n self.btn_del.grid(row=0, column=2, padx=5)\n self.btn_end.grid(row=0, column=3, padx=5)\n\n self.label.pack_forget()\n\n self.frame1.pack()\n self.label.pack()\n\n self.imgCtrl = imageControl\n\n self.setImage(self.imgCtrl.getImage(0))\n\n def command_next(self):\n self.imgNum +=1\n if self.imgNum > self.maxImgNum:\n self.imgNum = self.maxImgNum\n self.setImage(self.imgCtrl.getImage(self.imgNum))\n \n def command_prev(self):\n self.imgNum -= 1\n if self.imgNum<0:\n self.imgNum = 0\n self.setImage(self.imgCtrl.getImage(self.imgNum))\n\n def command_del(self):\n del self.imgCtrl.result[self.imgNum]\n self.maxImgNum -= 1\n self.imgNum = min(self.maxImgNum, self.imgNum)\n self.setImage(self.imgCtrl.getImage(self.imgNum))\n \n def command_end(self):\n self.parent.command_end()\n self.parent.threadStopped = False","sub_path":"UI/showImage.py","file_name":"showImage.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"321136258","text":"\"\"\"\n ShuffleNet V2 for ImageNet-1K, implemented in TensorFlow.\n Original paper: 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\"\"\"\n\n__all__ = ['ShuffleNetV2', 'shufflenetv2_wd2', 'shufflenetv2_w1', 'shufflenetv2_w3d2', 'shufflenetv2_w2']\n\nimport os\nimport tensorflow as tf\nimport tensorflow.keras.layers as nn\nfrom .common import conv1x1, depthwise_conv3x3, conv1x1_block, conv3x3_block, ChannelShuffle, SEBlock,\\\n BatchNorm, MaxPool2d, SimpleSequential, get_channel_axis, flatten\n\n\nclass ShuffleUnit(nn.Layer):\n \"\"\"\n ShuffleNetV2 unit.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n downsample : bool\n Whether do downsample.\n use_se : bool\n Whether to use SE block.\n use_residual : bool\n Whether to use residual connection.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n downsample,\n use_se,\n use_residual,\n data_format=\"channels_last\",\n **kwargs):\n super(ShuffleUnit, self).__init__(**kwargs)\n self.data_format = data_format\n self.downsample = downsample\n self.use_se = use_se\n self.use_residual = use_residual\n mid_channels = out_channels // 2\n\n self.compress_conv1 = conv1x1(\n in_channels=(in_channels if self.downsample else mid_channels),\n out_channels=mid_channels,\n data_format=data_format,\n name=\"compress_conv1\")\n self.compress_bn1 = BatchNorm(\n # in_channels=mid_channels,\n data_format=data_format,\n name=\"compress_bn1\")\n self.dw_conv2 = depthwise_conv3x3(\n channels=mid_channels,\n strides=(2 if self.downsample else 1),\n data_format=data_format,\n name=\"dw_conv2\")\n self.dw_bn2 = BatchNorm(\n # in_channels=mid_channels,\n data_format=data_format,\n name=\"dw_bn2\")\n self.expand_conv3 = conv1x1(\n in_channels=mid_channels,\n out_channels=mid_channels,\n data_format=data_format,\n name=\"expand_conv3\")\n self.expand_bn3 = BatchNorm(\n # in_channels=mid_channels,\n data_format=data_format,\n name=\"expand_bn3\")\n if self.use_se:\n self.se = SEBlock(\n channels=mid_channels,\n data_format=data_format,\n name=\"se\")\n if downsample:\n self.dw_conv4 = depthwise_conv3x3(\n channels=in_channels,\n strides=2,\n data_format=data_format,\n name=\"dw_conv4\")\n self.dw_bn4 = BatchNorm(\n # in_channels=in_channels,\n data_format=data_format,\n name=\"dw_bn4\")\n self.expand_conv5 = conv1x1(\n in_channels=in_channels,\n out_channels=mid_channels,\n data_format=data_format,\n name=\"expand_conv5\")\n self.expand_bn5 = BatchNorm(\n # in_channels=mid_channels,\n data_format=data_format,\n name=\"expand_bn5\")\n\n self.activ = nn.ReLU()\n self.c_shuffle = ChannelShuffle(\n channels=out_channels,\n groups=2,\n data_format=data_format,\n name=\"c_shuffle\")\n\n def call(self, x, training=None):\n if self.downsample:\n y1 = self.dw_conv4(x)\n y1 = self.dw_bn4(y1, training=training)\n y1 = self.expand_conv5(y1)\n y1 = self.expand_bn5(y1, training=training)\n y1 = self.activ(y1)\n x2 = x\n else:\n y1, x2 = tf.split(x, num_or_size_splits=2, axis=get_channel_axis(self.data_format))\n y2 = self.compress_conv1(x2)\n y2 = self.compress_bn1(y2, training=training)\n y2 = self.activ(y2)\n y2 = self.dw_conv2(y2)\n y2 = self.dw_bn2(y2, training=training)\n y2 = self.expand_conv3(y2)\n y2 = self.expand_bn3(y2, training=training)\n y2 = self.activ(y2)\n if self.use_se:\n y2 = self.se(y2)\n if self.use_residual and not self.downsample:\n y2 = y2 + x2\n x = tf.concat([y1, y2], axis=get_channel_axis(self.data_format))\n x = self.c_shuffle(x)\n return x\n\n\nclass ShuffleInitBlock(nn.Layer):\n \"\"\"\n ShuffleNetV2 specific initial block.\n\n Parameters:\n ----------\n in_channels : int\n Number of input channels.\n out_channels : int\n Number of output channels.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n in_channels,\n out_channels,\n data_format=\"channels_last\",\n **kwargs):\n super(ShuffleInitBlock, self).__init__(**kwargs)\n self.conv = conv3x3_block(\n in_channels=in_channels,\n out_channels=out_channels,\n strides=2,\n data_format=data_format,\n name=\"conv\")\n self.pool = MaxPool2d(\n pool_size=3,\n strides=2,\n padding=0,\n ceil_mode=True,\n data_format=data_format,\n name=\"pool\")\n\n def call(self, x, training=None):\n x = self.conv(x, training=training)\n x = self.pool(x)\n return x\n\n\nclass ShuffleNetV2(tf.keras.Model):\n \"\"\"\n ShuffleNetV2 model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n channels : list of list of int\n Number of output channels for each unit.\n init_block_channels : int\n Number of output channels for the initial unit.\n final_block_channels : int\n Number of output channels for the final block of the feature extractor.\n use_se : bool, default False\n Whether to use SE block.\n use_residual : bool, default False\n Whether to use residual connections.\n in_channels : int, default 3\n Number of input channels.\n in_size : tuple of two ints, default (224, 224)\n Spatial size of the expected input image.\n classes : int, default 1000\n Number of classification classes.\n data_format : str, default 'channels_last'\n The ordering of the dimensions in tensors.\n \"\"\"\n def __init__(self,\n channels,\n init_block_channels,\n final_block_channels,\n use_se=False,\n use_residual=False,\n in_channels=3,\n in_size=(224, 224),\n classes=1000,\n data_format=\"channels_last\",\n **kwargs):\n super(ShuffleNetV2, self).__init__(**kwargs)\n self.in_size = in_size\n self.classes = classes\n self.data_format = data_format\n\n self.features = SimpleSequential(name=\"features\")\n self.features.add(ShuffleInitBlock(\n in_channels=in_channels,\n out_channels=init_block_channels,\n data_format=data_format,\n name=\"init_block\"))\n in_channels = init_block_channels\n for i, channels_per_stage in enumerate(channels):\n stage = SimpleSequential(name=\"stage{}\".format(i + 1))\n for j, out_channels in enumerate(channels_per_stage):\n downsample = (j == 0)\n stage.add(ShuffleUnit(\n in_channels=in_channels,\n out_channels=out_channels,\n downsample=downsample,\n use_se=use_se,\n use_residual=use_residual,\n data_format=data_format,\n name=\"unit{}\".format(j + 1)))\n in_channels = out_channels\n self.features.add(stage)\n self.features.add(conv1x1_block(\n in_channels=in_channels,\n out_channels=final_block_channels,\n data_format=data_format,\n name=\"final_block\"))\n in_channels = final_block_channels\n self.features.add(nn.AveragePooling2D(\n pool_size=7,\n strides=1,\n data_format=data_format,\n name=\"final_pool\"))\n\n self.output1 = nn.Dense(\n units=classes,\n input_dim=in_channels,\n name=\"output1\")\n\n def call(self, x, training=None):\n x = self.features(x, training=training)\n x = flatten(x, self.data_format)\n x = self.output1(x)\n return x\n\n\ndef get_shufflenetv2(width_scale,\n model_name=None,\n pretrained=False,\n root=os.path.join(\"~\", \".tensorflow\", \"models\"),\n **kwargs):\n \"\"\"\n Create ShuffleNetV2 model with specific parameters.\n\n Parameters:\n ----------\n width_scale : float\n Scale factor for width of layers.\n model_name : str or None, default None\n Model name for loading pretrained model.\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n\n init_block_channels = 24\n final_block_channels = 1024\n layers = [4, 8, 4]\n channels_per_layers = [116, 232, 464]\n\n channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]\n\n if width_scale != 1.0:\n channels = [[int(cij * width_scale) for cij in ci] for ci in channels]\n if width_scale > 1.5:\n final_block_channels = int(final_block_channels * width_scale)\n\n net = ShuffleNetV2(\n channels=channels,\n init_block_channels=init_block_channels,\n final_block_channels=final_block_channels,\n **kwargs)\n\n if pretrained:\n if (model_name is None) or (not model_name):\n raise ValueError(\"Parameter `model_name` should be properly initialized for loading pretrained model.\")\n from .model_store import get_model_file\n in_channels = kwargs[\"in_channels\"] if (\"in_channels\" in kwargs) else 3\n input_shape = (1,) + (in_channels,) + net.in_size if net.data_format == \"channels_first\" else\\\n (1,) + net.in_size + (in_channels,)\n net.build(input_shape=input_shape)\n net.load_weights(\n filepath=get_model_file(\n model_name=model_name,\n local_model_store_dir_path=root))\n\n return net\n\n\ndef shufflenetv2_wd2(**kwargs):\n \"\"\"\n ShuffleNetV2 0.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(12.0 / 29.0), model_name=\"shufflenetv2_wd2\", **kwargs)\n\n\ndef shufflenetv2_w1(**kwargs):\n \"\"\"\n ShuffleNetV2 1x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=1.0, model_name=\"shufflenetv2_w1\", **kwargs)\n\n\ndef shufflenetv2_w3d2(**kwargs):\n \"\"\"\n ShuffleNetV2 1.5x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(44.0 / 29.0), model_name=\"shufflenetv2_w3d2\", **kwargs)\n\n\ndef shufflenetv2_w2(**kwargs):\n \"\"\"\n ShuffleNetV2 2x model from 'ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design,'\n https://arxiv.org/abs/1807.11164.\n\n Parameters:\n ----------\n pretrained : bool, default False\n Whether to load the pretrained weights for model.\n root : str, default '~/.tensorflow/models'\n Location for keeping the model parameters.\n \"\"\"\n return get_shufflenetv2(width_scale=(61.0 / 29.0), model_name=\"shufflenetv2_w2\", **kwargs)\n\n\ndef _test():\n import numpy as np\n import tensorflow.keras.backend as K\n\n pretrained = False\n\n models = [\n shufflenetv2_wd2,\n shufflenetv2_w1,\n shufflenetv2_w3d2,\n shufflenetv2_w2,\n ]\n\n for model in models:\n\n net = model(pretrained=pretrained)\n\n batch = 14\n x = tf.random.normal((batch, 224, 224, 3))\n y = net(x)\n assert (tuple(y.shape.as_list()) == (batch, 1000))\n\n weight_count = sum([np.prod(K.get_value(w).shape) for w in net.trainable_weights])\n print(\"m={}, {}\".format(model.__name__, weight_count))\n assert (model != shufflenetv2_wd2 or weight_count == 1366792)\n assert (model != shufflenetv2_w1 or weight_count == 2278604)\n assert (model != shufflenetv2_w3d2 or weight_count == 4406098)\n assert (model != shufflenetv2_w2 or weight_count == 7601686)\n\n\nif __name__ == \"__main__\":\n _test()\n","sub_path":"tensorflow2/tf2cv/models/shufflenetv2.py","file_name":"shufflenetv2.py","file_ext":"py","file_size_in_byte":13783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"447105832","text":"import re\n\n\nclass Sequencer(object):\n \n def __init__(self):\n self.next_id = 1\n self.data = dict()\n \n def id(self, x):\n existing_id = self.data.get(x, None)\n\n if existing_id:\n return existing_id\n \n self.data[x] = self.next_id\n self.next_id += 1\n \n return self.next_id - 1\n\n\n\nclass NGramSpace(object):\n \n def __init__(self, n):\n self.n = n\n self.ngrams = Sequencer()\n \n def parse(self, text):\n normalized_text = re.sub('\\W', ' ', text.lower())\n split_text = normalized_text.split()\n \n ids = set()\n \n for i in range(0, len(split_text) + 1 - self.n):\n ngram = \" \".join(split_text[i:i+self.n])\n ids.add(self.ngrams.id(ngram))\n \n sorted_ids = list(ids)\n sorted_ids.sort()\n \n return sorted_ids\n \n\ndef overlap(x, y):\n i = 0\n j = 0\n \n c = 0\n \n len_x = len(x)\n len_y = len(y)\n \n while i < len_x and j < len_y:\n if x[i] > y[j]:\n j += 1\n elif x[i] < y[j]:\n i += 1\n else: # x[i] == y[j]\n c += 1\n i += 1\n j += 1 \n \n return c\n \n\ndef jaccard(x, y):\n intersection_size = overlap(x, y)\n union_size = len(x) + len(y) - intersection_size\n \n return float(intersection_size) / union_size if union_size != 0 else 0\n\n","sub_path":"duplicates/ngrams.py","file_name":"ngrams.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"318127022","text":"\n# Возвращает список аптек\ndef get_apt_list(form,manager_id):\n manager=form.db.get(table='manager',where='id=%s',values=[manager_id],onerow=1)\n if manager['type']==3:\n r=form.db.query(\n query='''\n SELECT\n wt.*, 0 more, concat(m.name_f,' ',m.name_i,' ',m.name_o) ma_fio, m.email ma_email,\n m.phone ma_phone\n FROM\n ur_lico_manager ulm\n join apteka wt ON wt.ur_lico_id=ulm.ur_lico_id\n left join manager m ON wt.anna_manager_id=m.id\n WHERE\n wt.manager_id=%s\n ''',\n values=[manager_id],\n onerow=1,\n errors=form.errors\n )\n if(r): return [r]\n return []\n \n else:\n return form.db.query(\n query=\"\"\"\n SELECT\n wt.*, 0 more, concat(m.name_f,' ',m.name_i,' ',m.name_o) ma_fio, m.email ma_email,\n m.phone ma_phone\n FROM\n ur_lico_manager ulm\n join apteka wt ON wt.ur_lico_id=ulm.ur_lico_id\n left join manager m ON wt.anna_manager_id=m.id\n WHERE\n ulm.manager_id=%s\n\n \"\"\",\n errors=form.errors,\n values=[manager_id]\n )\n\ndef get_apt_list_ids(form,manager_id=0):\n if not manager_id:\n manager_id=form.manager['id']\n res_lst=[]\n lst=[]\n \n\n lst=get_apt_list(form,manager_id)\n for a in lst:\n \n res_lst.append(str(a['id']))\n \n\n \n\n return res_lst\n\ndef get_apt_managers_ids(form,manager_id):\n ids=get_apt_list_ids(form,manager_id)\n rez=form.db.query(\n query=f'''\n select\n manager_id \n from\n apteka\n where id in ({\",\".join(ids)}) and manager_id is not null group by manager_id \n ''',\n #debug=1,\n massive=1\n )\n if len(rez)==0:\n rez.append('0')\n return rez\n\ndef apt_list_id_for_apt(form,manager_id):\n rez=[]\n apteka_id=form.db.query(\n query='select id from apteka where manager_id=%s',\n values=[manager_id],\n onevalue=1\n )\n if apteka_id:\n rez.append(str(apteka_id))\n return rez\n\n\ndef get_all_ids_for_aptcomp(form,apteka_id):\n # получит все id-шники аптек в рамках этого же юрлица\n res=form.db.query(\n query='''\n SELECT\n a2.id\n from\n apteka a1\n join apteka a2 ON a2.ur_lico_id=a1.ur_lico_id\n WHERE a1.id=%s\n ''',\n massive=1,\n values=[apteka_id]\n )\n\n res2=[]\n for r in res:\n res2.append(str(r))\n #form.pre(res2)\n return res2\n","sub_path":"backend/lib/anna/get_apt_list.py","file_name":"get_apt_list.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"425580071","text":"import omni.ext\nfrom omni.services.transport.client.https_async import consumer\nimport omni.ui as ui\nfrom pathlib import Path\nimport carb.settings\nimport os \nimport asyncio\nimport webbrowser\nfrom enum import IntEnum\nimport omni.services.client as _client\nimport omni.services.transport.client.http_async\n\nfrom pxr import Usd, Sdf, Gf, UsdGeom\nfrom synctwin.item.connector.item_engineering_connector import ItemEngineeringConnector\nICON_PATH = Path(__file__).parent.parent.parent.parent.joinpath(\"data\")\n\n# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be\n# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled\n# on_shutdown() is called.\nclass LevelOfDetail(IntEnum):\n LOW = 0,\n MEDIUM = 1,\n HIGH = 2 \n\nclass ItemConnectorExtension(omni.ext.IExt):\n # ext_id is current extension id. It can be used with extension manager to query additional information, like where\n # this extension is located on filesystem.\n\n def project_url(self, project_id): \n return f\"{self._itemtool_url}/{project_id}\"\n \n def on_startup(self, ext_id):\n \n self._usd_context = omni.usd.get_context()\n self._selection = self._usd_context.get_selection()\n self._events = self._usd_context.get_stage_event_stream()\n self._stage_event_sub = self._events.create_subscription_to_pop(\n self._on_stage_event, name=\"on stage event synctwin item connector\"\n ) \n self._item = ItemEngineeringConnector() \n self._settings = carb.settings.get_settings()\n self._projects_path = self._settings.get(\"projects_path\") \n self._parts_path = self._settings.get(\"parts_path\")\n self._itemtool_url= self._settings.get(\"itemtool_url\")\n self._project_id = \"1d05717eb87cec4287ed241312306c5f4\" \n\n print(\"[synctwin.item.connector] synctwin item startup\")\n\n self._window = ui.Window(\"synctwin item connector\", width=300, height=200)\n\n with self._window.frame:\n with ui.VStack():\n \n with ui.HStack(): \n \n omni.ui.Image(f'{ICON_PATH}/item_logo.png', width=80)\n with ui.VStack():\n ui.Spacer() \n ui.Button(\"...\", width=25, height=25, tooltip=\"open engineering tool in browser\", clicked_fn=lambda: on_browser_click())\n ui.Spacer()\n ui.Spacer()\n ui.Label(\"Project-ID\")\n project_field = ui.StringField(height=30)\n project_field.model.set_value(self._project_id)\n project_field.model.add_end_edit_fn(lambda new_value: on_project_edit(new_value))\n ui.Button(\"update\", height=40, clicked_fn=lambda: on_update_click())\n def on_project_edit(new_value):\n print(\"new value:\", new_value.as_string)\n self._project_id = new_value.as_string\n def on_update_click():\n self._item.import_project(self._project_id)\n def on_browser_click():\n self.open_browser(self.project_url(self._project_id)) \n ui.Spacer()\n \n \n def on_shutdown(self):\n print(\"[synctwin.item.connector] synctwin item shutdown\")\n\n def _on_stage_event(self, event):\n \"\"\"Called with subscription to pop\"\"\"\n\n if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):\n self._on_selection_changed()\n\n def _on_selection_changed(self):\n \"\"\"Called when the user changes the selection\"\"\" \n selection = self._selection.get_selected_prim_paths()\n stage = self._usd_context.get_stage()\n print(\"selection\", selection )\n print(\"stage\", stage)\n if selection and stage:\n prim = stage.GetPrimAtPath(selection[0])\n properties = prim.GetPropertyNames()\n #print(properties)\n print(prim.GetCustomData()) \n\n def open_browser(self, url): \n webbrowser.open(url)\n","sub_path":"exts/synctwin.item.connector/synctwin/item/connector/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":4254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"631756574","text":"# Regression Example With Boston Dataset: Baseline\n\nimport numpy as np\nimport pandas\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.wrappers.scikit_learn import KerasRegressor\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom scipy.io import loadmat\n\n\n# load training set\ntrainSet = loadmat('data_load_forecast/trainSet.mat')\n# # split into input (X) and output (Y) variables\ntrainX = trainSet['trainX']\ntrainY = trainSet['trainY']\n\n\n# load testing set\n## OPT 1: still using training set\n# testSet = loadmat('data_load_forecast/trainSet.mat')\n# testX = trainSet['trainX']\n# testY = trainSet['trainY']\n## OPT 2: using testing set\ntestSet = loadmat('data_load_forecast/testSet.mat')\ntestX = testSet['testX']\ntestY = testSet['testY']\n\n\n# # find row indices that have nan\nindices_nan_train = np.isnan(trainX).any(axis=1)\nindices_nan_test = np.isnan(testX).any(axis=1)\n# # delete the corresponding rows in both X and Y\ntrainX = trainX[~indices_nan_train]\ntrainY = trainY[~indices_nan_train]\ntestX = testX[~indices_nan_test]\ntestY = testY[~indices_nan_test]\n\n# scale the power data to per unit\nPowerBase = 1\ntrainX[:, 5:8] = trainX[:, 5:8]/PowerBase\ntrainY = trainY/PowerBase\ntestX[:, 5:8] = testX[:, 5:8]/PowerBase\ntestY = testY/PowerBase\n\n# create model\nmodel = Sequential()\nmodel.add(Dense(5, input_dim=8, activation='relu')) # activation= 'sigmoid'\nmodel.add(Dense(5, activation='relu'))\nmodel.add(Dense(5, activation='relu'))\nmodel.add(Dense(1, activation='relu'))\n\n# Compile model\nmodel.compile(loss='mean_squared_error', optimizer='adam', metrics=['mape'])\n\n# Fit the model\nmodel.fit(trainX, trainY, nb_epoch=20, batch_size=100) #\n\n# evaluate the model\nscores = model.evaluate(testX, testY)\nprint(\"%s: %.2f\" % (model.metrics_names[1], scores[1]))\n\n# perform prediction\nhatY = model.predict(testX)\nerror = testY - hatY\n\n# plot\nplt.figure()\nplt.plot(testY)\nplt.plot(hatY)\nplt.title('Load Forecasting')\nplt.show()\n\n# plot\nplt.figure()\nplt.plot(error)\nplt.title('Load Forecasting Error')\nplt.show()\n\n","sub_path":"practice/multilayer_perceptrons/keras_sequential_load_forecast.py","file_name":"keras_sequential_load_forecast.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"366800427","text":"# import the pyplot and wavfile modules\r\n\r\nimport matplotlib.pyplot as plot\r\n\r\nfrom scipy.io import wavfile\r\nfrom dtw import dtw\r\n\r\n# Read the wav file (mono)\r\n\r\nsamplingFrequency1, signalData1 = wavfile.read('chunk2.wav')\r\nsamplingFrequency2, signalData2 = wavfile.read('J&T-M.wav')\r\n\r\n# Plot the signal read from wav file\r\nx= str('chunk2.wav')\r\ny=str('J&T-M.wav')\r\n\r\nplot.subplot(211)\r\nplot.title('Spectrogram of',x)\r\nplot.plot(signalData1)\r\nplot.xlabel('Time')\r\nplot.ylabel('Amplitude')\r\n\r\nplot.subplot(212)\r\nplot.title('Spectrogram of ',y)\r\nplot.plot(signalData2)\r\nplot.xlabel('Time')\r\nplot.ylabel('Amplitude')\r\n\r\nplot.show()\r\n# plot.subplot(212)\r\n#\r\n# plot.specgram(signalData, Fs=samplingFrequency)\r\n#\r\n# plot.xlabel('Time')\r\n#\r\n# plot.ylabel('Frequency')\r\n\r\n\r\n","sub_path":"DTW/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"628336515","text":"import numpy as np\nimport theano\nimport theano.tensor as T\nfrom common.time_executor import get_execution_time\n\n# by specifying [10] as the hidden_layer_neuron implies using 1 hidden layer with 10 neurons\n# respectively by specifying [100, 100] -> 2 hidden layers each layer 100 neurons\n\n\nclass SoftmaxNeuralNetwork:\n\n def __init__(self, train_x, train_y, num_features=6, list_of_neuron_on_hidden_layer=list([10]), decay=1e-6,\n verbose=True):\n\n self.train_x = train_x\n self.train_y = train_y\n self.verbose = verbose\n\n self.num_train_data = len(train_x)\n\n self.train_cost = []\n self.train_prediction = []\n self.train_exec_time = []\n\n self.test_prediction = []\n\n weights = []\n biases = []\n\n # first layer which connect to the input layer\n weights.append(\n self.init_weight(len(train_x[0]), list_of_neuron_on_hidden_layer[0]) )\n biases.append(\n self.init_bias(list_of_neuron_on_hidden_layer[0]))\n\n previous_layer = list_of_neuron_on_hidden_layer[0]\n\n for layer in range(1, len(list_of_neuron_on_hidden_layer)):\n weights.append(\n self.init_weight(previous_layer, list_of_neuron_on_hidden_layer[layer]))\n\n biases.append(\n self.init_bias(list_of_neuron_on_hidden_layer[layer]))\n\n # for output layer\n weights.append(\n self.init_weight(previous_layer, num_features)\n )\n\n biases.append(\n self.init_bias(num_features)\n )\n\n # construct neural network\n\n layers = []\n\n x_input = T.matrix('X')\n y_output = T.matrix('Y')\n\n prev_input = x_input\n\n for i in range(len(weights)-1):\n calculation = T.nnet.sigmoid(T.dot(prev_input, weights[i]) + biases[i])\n layers.append(calculation)\n prev_input = calculation\n\n # last output layer, use softmax function\n calculation = T.nnet.softmax(T.dot(prev_input, weights[len(weights)-1]) +\n biases[len(biases) - 1])\n layers.append(calculation)\n\n y_prediction = T.argmax(calculation, axis=1)\n\n sum_sqr_weights = T.sqr(weights[0])\n\n for i in range(1, len(weights)):\n sum_sqr_weights += T.sum(T.sqr(weights[i]))\n\n cost = T.mean(T.nnet.categorical_crossentropy(calculation, y_output)) + decay*T.sum(sum_sqr_weights)\n params = list(weights+biases)\n updates = self.sgd(cost=cost, params=params)\n\n self.computation = theano.function(\n inputs=[x_input, y_output],\n updates=updates,\n outputs=cost\n )\n\n self.prediction = theano.function(\n inputs=[x_input],\n outputs=y_prediction\n )\n\n return\n\n def init_bias(self, n):\n return theano.shared(np.zeros(n), theano.config.floatX)\n\n def init_weight(self, n_in, n_out, is_logistic_function=False):\n\n weight = np.random.uniform(\n size=(n_in, n_out),\n low=-np.sqrt(6. / (n_in + n_out)),\n high=np.sqrt(6. / (n_in + n_out)),\n )\n\n if is_logistic_function:\n weight = weight*4\n\n return theano.shared(weight, theano.config.floatX)\n\n def sgd(self, cost, params, lr=0.01):\n\n # return list of gradients\n grads = T.grad(cost=cost, wrt=params)\n\n updates = []\n for p, g in zip(params, grads):\n updates.append([p, p - g * lr])\n return updates\n\n def reshuffle_train_data(self):\n\n id_to_random = np.arange(self.num_train_data)\n np.random.shuffle(id_to_random)\n return self.train_x[id_to_random], self.train_y[id_to_random]\n\n def start_train(self, test_x, test_y, epochs=1000, batch_size=100):\n\n for i in range(epochs):\n\n self.reshuffle_train_data()\n\n prediction_batch = []\n\n cost, exec_time = get_execution_time(self.start_one_iter_func, batch_size, prediction_batch)\n\n # predictions of train data\n prediction = np.mean(prediction_batch)\n\n self.train_cost.append(cost)\n self.train_prediction.append(prediction)\n self.train_exec_time.append(exec_time)\n\n print_verbose = (i % 5*batch_size == 0 or i == epochs-1) and self.verbose\n\n self.start_test(test_x=test_x, test_y=test_y, print_verbose=print_verbose)\n\n if print_verbose:\n\n print ('execution_time: %s epoch: %d, train cost: %s, train predictions: %s \\n' %\n (np.sum(self.train_exec_time), i, cost, prediction))\n print('------------------------------------\\n')\n\n def start_one_iter_func(self, batch_size, prediction_batch):\n\n cost = 0\n\n for cnt in range(0, len(self.train_x), batch_size):\n\n end = cnt + batch_size\n\n if end > len(self.train_x):\n end = len(self.train_x)\n\n train_x_batch = self.train_x[cnt:end]\n train_y_batch = self.train_y[cnt:end]\n\n cost += self.computation(train_x_batch, train_y_batch)\n prediction = self.prediction(self.train_x)\n predict_in_percentage = np.mean(np.argmax(self.train_y, axis=1) == prediction)\n prediction_batch.append(predict_in_percentage)\n\n return cost\n\n def start_test(self, test_x, test_y, print_verbose):\n\n prediction = self.prediction(test_x)\n\n predict_in_percentage = np.mean(np.argmax(test_y, axis=1) == prediction)\n self.test_prediction.append(predict_in_percentage)\n\n if print_verbose:\n print ('test predictions: %s \\n' % predict_in_percentage)\n\n def get_train_result(self):\n\n return self.train_cost, self.train_prediction, np.sum(self.train_exec_time)\n\n def get_test_result(self):\n\n return self.test_prediction\n","sub_path":"training/softmax_nn.py","file_name":"softmax_nn.py","file_ext":"py","file_size_in_byte":5902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"222643088","text":"from __future__ import print_function\nfrom django.core.management import BaseCommand, CommandError\n\nfrom corehq.apps.app_manager.models import Application\n\n\nclass Command(BaseCommand):\n \"\"\"\n Creates a master and linked app pair for two existing apps\n \"\"\"\n args = \"master_app linked_app\"\n\n def handle(self, *args, **options):\n if len(args) != 2:\n raise CommandError(\"Usage is ./manage.py link_apps %s\" % self.args)\n print(\"Linking apps\")\n master_id = args[0]\n linked_id = args[1]\n master_app = Application.get(master_id)\n linked_app = Application.get(linked_id)\n master_app.linked_whitelist.append(linked_app.domain)\n linked_app.doc_type = 'LinkedApplication'\n linked_app.master = master_id\n if master_app.version < linked_app.version:\n master_app.version = linked_app.version\n master_app.save()\n linked_app.save()\n","sub_path":"corehq/apps/app_manager/management/commands/link_apps.py","file_name":"link_apps.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"620321019","text":"import os\n\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mezzanineSecurity.settings')\nimport django\ndjango.setup()\n\nimport datetime\nimport time\n\nfrom django.http.response import HttpResponseForbidden\nfrom fireWall.models import FireWallSetting, BlockList, WebLogs\n\ndef get_ip(req):\n return req.META['REMOTE_ADDR']\n\ndef add_session(request, setting_threshold): \n dt = datetime.datetime.now()\n timestamp = time.mktime(dt.timetuple())\n session_request = request.session.get('requestList', None)\n \n if session_request == None or session_request == '':\n requestList = []\n else:\n requestList = request.session['requestList'] \n requestList.append(timestamp) \n\n if len(requestList) > setting_threshold:\n num = len(requestList) - setting_threshold \n del requestList[0:num]\n request.session['requestList'] = requestList\n \ndef saveWebLogs(request):\n x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n \n if x_forwarded_for:\n IP = x_forwarded_for.split(',')[0]\n else:\n IP = request.META.get('REMOTE_ADDR')\n \n WebLogs.objects.create(IP=IP, datetime = datetime.datetime.now(), visited = request.build_absolute_uri()) \n \n \ndef calculator_IPRepuation(IP, repuation, threshold): \n today_min = datetime.datetime.combine(datetime.date.today(), datetime.time.min)\n today_max = datetime.datetime.combine(datetime.date.today(), datetime.time.max)\n logs = WebLogs.objects.filter(datetime__range=(today_min, today_max))\n IPRepuation = repuation - (threshold * len(logs) / 60)\n return IPRepuation\n\n\ndef saveBlackList(IP, threshold):\n \n blockIP = BlockList.objects.filter(IP=IP).first()\n \n if not blockIP:\n repuation = calculator_IPRepuation(IP, 100, threshold)\n BlockList.objects.create(IP=IP,repuation=repuation) \n else:\n repuation = calculator_IPRepuation(IP, blockIP.repuation, threshold)\n BlockList.objects.filter(IP=IP).update(repuation = repuation)\n \n\n \nclass FireWallMiddleware(object):\n def process_request(self, request):\n \n fireWallSetting = FireWallSetting.objects.filter(id = 1).first()\n \n IP = get_ip(request) \n \n if fireWallSetting != None:\n if BlockList.objects.filter(IP = IP).first():\n setting_threshold = fireWallSetting.blackThreshold\n \n else:\n setting_threshold = fireWallSetting.threshold\n setting_timeRange = fireWallSetting.timeRange *60 \n else:\n setting_threshold = 20\n setting_timeRange = 60 \n \n add_session(request, setting_threshold)\n \n firstRequest = request.session['requestList'][0]\n lastRequest = request.session['requestList'][-1] \n if len(request.session['requestList'])>=setting_threshold and lastRequest - firstRequest < setting_timeRange:\n saveWebLogs(request)\n saveBlackList(IP, setting_threshold) \n return HttpResponseForbidden(\"Your browser didn't send a complete request in time.\")","sub_path":"mezzanineSecurity/fireWall/fireWall.py","file_name":"fireWall.py","file_ext":"py","file_size_in_byte":3168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"560442193","text":"#!/usr/bin/env python\n\n#\n# daemon for Switcher\n#\n# author = Jose Caballero \n#\n\nimport logging\nimport os\nimport pwd\nimport sys\nimport socket\nimport time\nimport traceback\n\nfrom ConfigParser import SafeConfigParser\nfrom optparse import OptionParser\n\nfrom switcher.services.serverapi import AGIS, AGISMock\nfrom switcher.services.notify import Email, EmailMock\nfrom switcher.switcherexceptions import SwitcherConfigurationFailure, SwitcherEmailSendFailure\nfrom switcher.topology.topology import Topology\nfrom switcher.utils import AllowedEntities, load_json, send_notifications\n\n\n# =============================================================================\n\ndef send_failure_notification(subject, body, to):\n #FIXME: From is hardcoded \n # when fixed, we can call send_notifications directly\n send_notifications(subject, \n body,\n 'adcssb02@mail.cern.ch',\n to)\n\n# =============================================================================\n\n\nclass SwitcherCLI(object):\n\n def __init__(self):\n self.__parseopts()\n self.__createconfig()\n self.__readconfig()\n self.__setuplogging()\n self.__checkroot()\n\n\n def __parseopts(self):\n\n parser = OptionParser()\n parser.add_option('--conf', \n dest='conffile',\n default='/etc/switcher/switcher.conf',\n action='store',\n metavar='FILE1[,FILE2,FILE3]',\n help='Load configuration from FILEs (comma separated list)')\n (self.options, self.args) = parser.parse_args()\n\n\n def __readconfig(self):\n \"\"\"\n reads the basic configuration parameters for the daemon\n \"\"\"\n self.logfile = self.switcherconf.get('SWITCHER', 'logfile')\n\n loglevel = self.switcherconf.get('SWITCHER', 'loglevel')\n if loglevel == 'debug':\n self.loglevel = logging.DEBUG\n elif loglevel == 'info':\n self.loglevel = logging.INFO\n elif loglevel == 'warning':\n self.loglevel = logging.WARNING\n\n self.runAs = self.switcherconf.get('SWITCHER', 'runAs')\n\n self.dryrun = self.switcherconf.getboolean('SWITCHER', 'dryrun')\n self.allow_notifications = self.switcherconf.getboolean('SWITCHER', 'allow_notifications')\n self.failure_notifications = self.switcherconf.get('SWITCHER', 'failure_notifications')\n\n\n def __setuplogging(self):\n \"\"\"\n Setup logging \n \n General principles we have tried to used for logging: \n \n -- Logging syntax and semantics should be uniform throughout the program, \n based on whatever organization scheme is appropriate. \n \n -- Have sufficient DEBUG messages to show domain problem calculations input and output.\n DEBUG messages should never span more than one line. \n \n -- A moderate number of INFO messages should be logged to mark major \n functional steps in the operation of the program, \n e.g. when a persistent object is instantiated and initialized, \n when a functional cycle/loop is complete. \n It would be good if these messages note summary statistics, \n e.g. \"the last submit cycle submitted 90 jobs and 10 jobs finished\". \n A program being run with INFO log level should provide enough output \n that the user can watch the program function and quickly observe interesting events. \n \n -- Initially, all logging should be directed to a single file. \n But provision should be made for eventually directing logging output from different subsystems \n (submit, info, proxy management) to different files, \n and at different levels of verbosity (DEBUG, INFO, WARN), and with different formatters. \n Control of this distribution should use the standard Python \"logging.conf\" format file: \n \n -- All messages are always printed out in the logs files, \n but also to the stderr when DEBUG or INFO levels are selected. \n \n -- We keep the original python levels meaning, \n including WARNING as being the default level. \n \n DEBUG Detailed domain problem information related to scheduling, calculations,\n program state. \n INFO High level confirmation that things are working as expected. \n WARNING An indication that something unexpected happened, \n or indicative of some problem in the near future (e.g. 'disk space low'). \n The software is still working as expected. \n ERROR Due to a more serious problem, the software has not been able to perform some function. \n CRITICAL A serious error, indicating that the program itself may be unable to continue running. \n \n \"\"\"\n self.log = logging.getLogger()\n\n logfile = os.path.expanduser(self.logfile)\n if logfile == 'syslog':\n logStream = logging.handlers.SysLogHandler('/dev/log')\n elif logfile == 'stdout':\n logStream = logging.StreamHandler()\n else:\n lf = os.path.expanduser(logfile)\n logdir = os.path.dirname(lf)\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n runuid = pwd.getpwnam(self.runAs).pw_uid\n rungid = pwd.getpwnam(self.runAs).pw_gid\n os.chown(logdir, runuid, rungid)\n logStream = logging.FileHandler(filename=lf)\n\n FORMAT='%(asctime)s (UTC) [ %(levelname)s ] %(name)s %(filename)s:%(lineno)d %(funcName)s(): %(message)s'\n formatter = logging.Formatter(FORMAT)\n formatter.converter = time.gmtime # to convert timestamps to UTC\n logStream.setFormatter(formatter)\n self.log.addHandler(logStream)\n self.log.setLevel(self.loglevel)\n self.log.info('Logging initialized.')\n\n\n def __checkroot(self):\n \"\"\"\n If running as root, drop privileges to --runas' account.\n \"\"\"\n starting_uid = os.getuid()\n starting_gid = os.getgid()\n starting_uid_name = pwd.getpwuid(starting_uid)[0]\n\n hostname = socket.gethostname()\n\n if os.getuid() != 0:\n self.log.info(\"Already running as unprivileged user %s at %s\" % (starting_uid_name, hostname))\n\n if os.getuid() == 0:\n try:\n runuid = pwd.getpwnam(self.runAs).pw_uid\n rungid = pwd.getpwnam(self.runAs).pw_gid\n os.chown(self.logfile, runuid, rungid)\n\n os.setgid(rungid)\n os.setuid(runuid)\n os.seteuid(runuid)\n os.setegid(rungid)\n\n self.log.info(\"Now running as user %d:%d at %s...\" % (runuid, rungid, hostname))\n\n except KeyError as e:\n self.log.critical('No such user %s, unable run properly. Error: %s' % (self.options.runAs, e))\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down, unable to change user', \n self.failure_notifications)\n sys.exit(1)\n\n except OSError as e:\n self.log.critical('Could not set user or group id to %s:%s. Error: %s' % (runuid, rungid, e))\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down, unable to change user',\n self.failure_notifications)\n sys.exit(1)\n\n\n def __createconfig(self):\n \"\"\"\n get the basic configuration for the daemon\n \"\"\"\n self.switcherconf = SafeConfigParser()\n self.switcherconf.readfp(open(self.options.conffile))\n \n\n def run(self):\n \"\"\"\n Create Switcher object and enter main loop\n \"\"\"\n try:\n self.log.info('Creating Switcher object and entering main loop...')\n\n switcherloop = SwitcherLoop(self.switcherconf)\n switcherloop.run(self.dryrun, self.allow_notifications)\n\n except KeyboardInterrupt:\n self.log.info('Caught keyboard interrupt - exitting')\n switcher.stop()\n sys.exit(0)\n except SwitcherConfigurationFailure as e:\n self.log.critical('Switcher configuration failure: %s', e)\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down due Configuration Failure',\n self.failure_notifications)\n sys.exit(1)\n except ImportError as e:\n self.log.critical('Failed to import necessary python module: %s' % e)\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down due Import Error',\n self.failure_notifications)\n sys.exit(1)\n except Exception as ex:\n self.log.critical(\"\"\"Please report to Jose \"\"\")\n self.log.critical(traceback.format_exc(None))\n print(traceback.format_exc(None))\n send_failure_notification('[Switcher3 FATAL Failure]', \n 'Switcher3 service shut down due Unkown Error: %s' %ex, \n self.failure_notifications)\n sys.exit(1)\n\n\n\nclass SwitcherLoop(object):\n \"\"\"\n class to implement the main loop\n \"\"\"\n\n def __init__(self, switcherconf):\n self.log = logging.getLogger('switcher')\n self.switcherconf = switcherconf\n self.shutdown = False\n self.sleep = self.switcherconf.getint('SWITCHER', 'sleep')\n\n\n def run(self, dryrun, allow_notifications):\n \"\"\"\n main loop\n \"\"\"\n try:\n while not self.shutdown:\n try:\n switcher = Switcher(self.switcherconf)\n switcher._run(dryrun, allow_notifications)\n except SwitcherConfigurationFailure as ex:\n self.log.critical('Exception raised during Switcher main loop run: %s.' % ex)\n except SwitcherEmailSendFailure as ex:\n self.log.critical('Exception raised during Switcher main loop run: %s.' % ex)\n except Exception as ex:\n self.log.critical('Exception raised during Switcher main loop run: %s.' % ex)\n time.sleep(self.sleep)\n self.log.debug('Checking for interrupt.')\n except Exception as ex:\n # FIXME: unless we used specific Exceptions inside while loop, this code will never run \n self.log.fatal('Unrecognized Exception raised during Switcher main loop run: %s. Aborting.' % ex)\n self.shutdown = True\n raise ex\n self.log.debug('Leaving.')\n\n\n\nclass Switcher(object):\n \"\"\"\n class implementing actions to be performed on \n each cycle of the loop\n \"\"\"\n\n def __init__(self, switcherconf):\n \"\"\"\n :param SafeConfigParser switcherconf: primary config object\n \"\"\"\n self.log = logging.getLogger('switcher')\n self.shutdown = False\n self.switcherconf = switcherconf\n\n self.__readconfig()\n\n\n def __readconfig(self): \n \"\"\"\n get the configuration parameters for this class\n and create the rest of Config objects\n \"\"\"\n self.sleep = self.switcherconf.getint('SWITCHER', 'sleep')\n\n downtimesconf = self.switcherconf.get('SWITCHER', 'downtimesconf')\n self.downtimesconf = SafeConfigParser()\n self.downtimesconf.readfp(open(downtimesconf))\n\n notificationsconf = self.switcherconf.get('SWITCHER', 'notificationsconf')\n self.notificationsconf = SafeConfigParser()\n self.notificationsconf.readfp(open(notificationsconf))\n\n self.schedconfig = self.switcherconf.get('SOURCE', 'schedconfig')\n self.ddmtopology = self.switcherconf.get('SOURCE', 'ddmtopology')\n self.switcherstatus = self.switcherconf.get('SOURCE', 'switcherstatus')\n self.sites = self.switcherconf.get('SOURCE', 'sites')\n self.downtimescalendar = self.switcherconf.get('SOURCE', 'downtimescalendar')\n\n self.probe_state_source = self.switcherconf.get('SOURCE', 'probestate')\n\n self.allowed_clouds = self.__get_allowed_entities('clouds')\n self.allowed_sites = self.__get_allowed_entities('sites')\n self.allowed_queues = self.__get_allowed_entities('queues')\n\n\n def __get_allowed_entities(self, name):\n \"\"\"\n gets from the schedconfig if certain entitties\n are allowed or excluded.\n :param string name: can be \"clouds\", \"sites\" or \"queues\"\n :return AllowedEntities:\n \"\"\"\n\n config_allowed_key = 'allowed_%s' %name\n config_excluded_key = 'excluded_%s' %name\n\n def _get_value(key):\n if self.switcherconf.has_option('SOURCE', key):\n value = self.switcherconf.get('SOURCE', key)\n if value == 'None':\n value = None\n if value is not None:\n value = [x.strip() for x in value.split(',')]\n else:\n value = None\n return value\n \n allowed = _get_value(config_allowed_key)\n excluded = _get_value(config_excluded_key)\n return AllowedEntities(allowed, excluded) \n\n\n# def run(self, dryrun=False, allow_notifications=True):\n# \"\"\"\n# main loop\n# \"\"\"\n# try: \n# while not self.shutdown:\n# try:\n# self._run(dryrun, allow_notifications)\n# except Exception as ex:\n# self.log.error('Exception raised during Switcher main loop run: %s.' % ex)\n# time.sleep(self.sleep) \n# self.log.debug('Checking for interrupt.')\n# except Exception as ex:\n# # FIXME: unless we used specific Exceptions inside while loop, this code will never run \n# self.log.error('Unrecognized Exception raised during Switcher main loop run: %s. Aborting.' % ex)\n# self.shutdown = True\n# raise ex\n# self.log.debug('Leaving.')\n\n\n def _run(self, dryrun=False, allow_notifications=True):\n \"\"\"\n actual actions performed in the main loop\n \"\"\"\n self.log.info('Starting new loop.')\n\n # FIXME\n # passing allow_only and excluded_queues should be done in a better way\n # this is a temporary solution\n topology = Topology(self.schedconfig, self.allowed_clouds, self.allowed_sites, self.allowed_queues, self.ddmtopology, self.notificationsconf, self.downtimesconf)\n topology.add_switcher_status(self.switcherstatus)\n topology.add_downtimes(self.downtimescalendar)\n topology.add_nucleus(self.sites)\n self.log.info('Topology tree generated %s.' %topology)\n\n if dryrun:\n agis = AGISMock(self.switcherconf)\n else:\n agis = AGIS(self.switcherconf)\n\n try:\n probe_state = load_json(self.probe_state_source)['switcher']['state'].lower()\n except Exception as ex:\n self.log.critical('Unable to read probe state configuration from src. Exception: %s' %ex)\n raise SwitcherConfigurationFailure(self.probe_state_source, ex)\n active = (probe_state == 'active')\n if allow_notifications:\n email = Email(active)\n else:\n email = EmailMock(active)\n\n topology.evaluate()\n topology.act(agis)\n topology.reevaluate(self.schedconfig)\n topology.notify(email)\n\n # =====================================================================\n # FIXME \n # temporary solution\n # =====================================================================\n from switcher.services.ssb import ssb, ssbmock\n if dryrun:\n ssb_fun = ssbmock\n else:\n ssb_fun = ssb\n ssb_fun(topology)\n\n self.log.info('Actions finished.')\n\n\nif __name__ == '__main__':\n \n cli = SwitcherCLI()\n cli.run()\n\n\n","sub_path":"switcher/switcherd.py","file_name":"switcherd.py","file_ext":"py","file_size_in_byte":16486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"406173181","text":"\n# coding: utf-8\n\n# In[2]:\n\n\nimport numpy as np\nimport cv2\nimport os\ncap = cv2.VideoCapture(0)\n\ntry:\n if not os.path.exists('cameraFrames'):\n os.makedirs('cameraFrames')\nexcept OSError:\n print ('Error: Creating directory of data')\n\ncurrentFrame = 0 \nwhile(True):\n\n ret, frame = cap.read()\n\n cv2.imshow('cameraCapture',frame)\n \n if cv2.waitKey(20) & 0xFF == ord('q'):\n break;\n else:\n name = './cameraFrames/frame' + str(currentFrame) + '.jpg'\n cv2.imwrite(name, frame)\n currentFrame += 1\nprint(str(currentFrame) +' image frames created.'); \ncap.release()\ncv2.destroyAllWindows()\n\n","sub_path":"Video Frame Generation/Camera-capture-Frames.py","file_name":"Camera-capture-Frames.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"46014948","text":"#!/usr/bin/env python\n\n'''\nGV(global variance)\n'''\nimport os\nimport sys\nimport numpy as np\nimport argparse\nimport logging\nimport h5py\n\nlogging.basicConfig(format='%(asctime)s %(threadName)s [%(levelname)s] [line:%(lineno)d] %(message)s', datefmt='%Y-%m-%d %H:%M:%S',\n level = logging.DEBUG\n #level = logging.WARN\n )\n\n\nparser = argparse.ArgumentParser(description='Read TFRecords')\n\nparser.add_argument('--metapath', type=str, default='/gfs/atlastts/StandFemale_22K/tfrecords/mcep_cut_normal/meta/mcep_cut/mean-std-meta.hdf5', help='file path to the hdf5.')\nparser.add_argument('--mceppath', type=str, default=None, help='file path to the SYN mcep.')\n\nFLAGS = parser.parse_args()\n\n# h5py\nf = h5py.File(FLAGS.metapath, 'r')\nlogging.info('Keys: {}'.format(f.keys()))\n\nfor k in f.keys():\n logging.info('{} keys values: {}'.format(k, f[k][:]))\n\nsyn_mean=f['gen_mean'][:]\nsyn_std=f['gen_std'][:]\nmean = f['nature_mean'][:]\nstd = f['nature_std'][:]\n\n\ndata = np.fromfile(FLAGS.mceppath, np.float32)\n\ndata = np.reshape(data, (-1, 41))\nlogging.info('mcep shape({}):\\n{}'.format(data.shape, data))\n\ndata = (data - syn_mean) / syn_std\ndata = data * std + mean\n\nlogging.info('mcep GV shape({}):\\n{}'.format(data.shape, data))\n\ndata.astype(np.float32).tofile(FLAGS.mceppath)\n\nsys.exit(0)\n\n","sub_path":"tools/mcep_gv.py","file_name":"mcep_gv.py","file_ext":"py","file_size_in_byte":1335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"428228861","text":"#!/usr/bin/python3\r\nfrom prng import LFSR\r\nfrom prng import PRNG\r\nimport prng_analysis\r\n\r\n\r\nq = 2\r\nalph = 0.01\r\npolynomial_coefficients = [[1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],\r\n [1, 1, 0, 1, 1, 0, 0, 0, 0],\r\n [1, 0, 0, 1, 0, 0, 0, 0, 0, 0]]\r\n\r\n\r\n\r\nout_sequence = open(\"seq.txt\", 'r').read().replace('\\n', '')\r\nprint(\"in seq: \")\r\nprint(out_sequence)\r\nstates = prng_analysis.prng_analysis(polynomial_coefficients, out_sequence, alph)\r\n\r\nprint(\"pract start states: \")\r\nfor state in states:\r\n print(state)\r\n\r\nl1_start_state = [0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0]\r\nl2_start_state = [1, 1, 1, 1, 1, 0, 0, 0, 1]\r\nl3_start_state = [1, 0, 0, 1, 0, 1, 1, 0, 0, 0]\r\n\r\nl1 = LFSR(q, polynomial_coefficients[0], l1_start_state)\r\nl2 = LFSR(q, polynomial_coefficients[1], l2_start_state)\r\nl3 = LFSR(q, polynomial_coefficients[2], l3_start_state)\r\n\r\nprng = PRNG([l1, l2, l3])\r\nout_sequence = \"\"\r\n\r\nfor i in range(1000):\r\n out_sequence += str(prng.next_value())\r\nprint(\"real seq: \")\r\nprint(out_sequence)\r\n\r\nprint(\"real start states: \")\r\nprint(l1_start_state)\r\nprint(l2_start_state)\r\nprint(l3_start_state)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"597246926","text":"\"\"\"\r\nSample estimates\r\n----------------\r\n * :func:`estimate` returns an uncertain number defined from\r\n the statistics of a sample of data.\r\n * :func:`multi_estimate_real` returns a sequence of related \r\n uncertain real numbers defined from the multivariate statistics \r\n calculated from a sample of data. \r\n * :func:`multi_estimate_complex` returns a sequence of related uncertain\r\n complex numbers defined from the multivariate statistics of a sample of data. \r\n * :func:`estimate_digitized` returns an uncertain number for \r\n the mean of a sample of digitized data.\r\n * :func:`mean` returns the mean of a sample of data.\r\n * :func:`standard_uncertainty` evaluates the standard \r\n uncertainty associated with the sample mean.\r\n * :func:`standard_deviation` evaluates the standard \r\n deviation of a sample of data.\r\n * :func:`variance_covariance_complex` evaluates the variance\r\n and covariance associated with the mean real component \r\n and mean imaginary component of the data.\r\n \r\n.. note::\r\n\r\n Many functions in :mod:`type_a` treat data as pure numbers. \r\n Sequences of uncertain numbers can be passed to these \r\n functions, but only the uncertain-number values will be used.\r\n \r\nModule contents\r\n---------------\r\n\r\n\"\"\"\r\nfrom __future__ import division\r\n\r\nimport sys\r\nimport math\r\nimport numbers\r\nfrom functools import reduce\r\n\r\ntry:\r\n from itertools import izip # Python 2\r\nexcept ImportError:\r\n izip = zip\r\n xrange = range\r\n\r\nfrom GTC.context import _context \r\n\r\nfrom GTC.lib import (\r\n UncertainReal, \r\n UncertainComplex,\r\n set_correlation_real,\r\n real_ensemble,\r\n complex_ensemble\r\n)\r\n\r\nfrom GTC.named_tuples import (\r\n VarianceCovariance,\r\n StandardUncertainty,\r\n StandardDeviation\r\n)\r\n\r\n__all__ = (\r\n 'estimate',\r\n 'estimate_digitized',\r\n 'multi_estimate_real',\r\n 'multi_estimate_complex',\r\n 'mean',\r\n 'standard_deviation',\r\n 'standard_uncertainty',\r\n 'variance_covariance_complex',\r\n)\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef _as_value(x):\r\n try:\r\n return x.x \r\n except AttributeError:\r\n return x \r\n \r\n#-----------------------------------------------------------------------------------------\r\ndef estimate_digitized(seq,delta,label=None,truncate=False,context=_context):\r\n \"\"\"\r\n Return an uncertain number for the mean of digitized data\r\n\r\n :arg seq: data\r\n :type seq: float, :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex`\r\n :arg float delta: digitization step size \r\n :arg str label: label for uncertain number returned\r\n :arg bool truncate: if ``True``, truncation, rather than rounding, is assumed\r\n :rtype: :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex`\r\n\r\n A sequence of data that has been formatted with fixed precision \r\n can completely conceal a small amount of variability in the original\r\n values, or merely obscure that variability. \r\n \r\n This function recognises the possible interaction between truncation, or rounding,\r\n errors and random errors in the underlying data. The function \r\n obtains the mean of the data sequence and evaluates the uncertainty \r\n in this mean as an estimate of the mean of the process generating \r\n the data. \r\n \r\n Set the argument ``truncate`` to ``True`` \r\n if data have been truncated, instead of rounded.\r\n \r\n See reference: R Willink, *Metrologia*, **44** (2007) 73-81\r\n\r\n **Examples**::\r\n \r\n # LSD = 0.0001, data varies between -0.0055 and -0.0057\r\n >>> seq = (-0.0056,-0.0055,-0.0056,-0.0056,-0.0056, \r\n ... -0.0057,-0.0057,-0.0056,-0.0056,-0.0057,-0.0057)\r\n >>> type_a.estimate_digitized(seq,0.0001)\r\n ureal(-0.005627272727272727,1.9497827808661157e-05,10)\r\n\r\n # LSD = 0.0001, data varies between -0.0056 and -0.0057\r\n >>> seq = (-0.0056,-0.0056,-0.0056,-0.0056,-0.0056,\r\n ... -0.0057,-0.0057,-0.0056,-0.0056,-0.0057,-0.0057)\r\n >>> type_a.estimate_digitized(seq,0.0001)\r\n ureal(-0.005636363636363636,1.5212000482437775e-05,10)\r\n\r\n # LSD = 0.0001, no spread in data values\r\n >>> seq = (-0.0056,-0.0056,-0.0056,-0.0056,-0.0056,\r\n ... -0.0056,-0.0056,-0.0056,-0.0056,-0.0056,-0.0056)\r\n >>> type_a.estimate_digitized(seq,0.0001)\r\n ureal(-0.0056,2.886751345948129e-05,10)\r\n \r\n # LSD = 0.0001, no spread in data values, fewer points\r\n >>> seq = (-0.0056,-0.0056,-0.0056)\r\n >>> type_a.estimate_digitized(seq,0.0001)\r\n ureal(-0.0056,3.291402943021917e-05,2)\r\n \r\n \"\"\"\r\n N = len(seq)\r\n if N < 2:\r\n raise RuntimeError(\r\n \"digitized data sequence must have more than one element\"\r\n )\r\n\r\n try:\r\n seq = [ float(x_i) for x_i in seq ]\r\n except TypeError:\r\n # If not a float then an uncertain number?\r\n seq = [ x_i.x for x_i in seq ]\r\n \r\n x_max = max(seq)\r\n x_min = min(seq)\r\n \r\n mean = math.fsum(seq)/N\r\n \r\n if x_max == x_min:\r\n # No scatter in the data\r\n if N == 2:\r\n root_c_12 = math.sqrt(6.4/12.0)\r\n elif N == 3:\r\n root_c_12 = math.sqrt(1.3/12.0)\r\n elif N >= 4:\r\n root_c_12 = math.sqrt(1.0/12.0)\r\n else:\r\n assert False,\"should not occur\"\r\n \r\n u = root_c_12*delta\r\n else:\r\n accum = lambda psum,x: psum + (x-mean)**2\r\n var = reduce(accum, seq, 0.0) / (N - 1)\r\n\r\n if abs(x_max - x_min - delta) < 10*sys.float_info.epsilon:\r\n # Scatter is LSD only\r\n x_mid = (x_max + x_min)/2.0\r\n u = math.sqrt(\r\n max(var/N,(x_mid - mean)**2/3.0)\r\n )\r\n else:\r\n u = math.sqrt(var/N)\r\n\r\n if truncate:\r\n mean += delta/2.0\r\n \r\n return UncertainReal._elementary(mean,u,N-1,label,independent=True)\r\n \r\n#-----------------------------------------------------------------------------------------\r\ndef estimate(seq,label=None,context=_context):\r\n \"\"\"Return an uncertain number for the mean of the data \r\n\r\n :arg seq: a sequence of data\r\n :arg str label: a label for the returned uncertain number\r\n \r\n :rtype: :class:`~lib.UncertainReal` or :class:`~lib.UncertainComplex`\r\n \r\n The elements of ``seq`` may be real numbers, complex numbers, or\r\n uncertain real or complex numbers. Note that only the value of uncertain \r\n numbers will be used.\r\n\r\n In a type-A evaluation, the sample mean provides an estimate of the \r\n quantity of interest. The uncertainty in this estimate \r\n is the standard deviation of the sample mean (or the \r\n sample covariance of the mean, in the complex case). \r\n \r\n The function returns an :class:`~lib.UncertainReal` when \r\n the mean of the data is real, and an :class:`~lib.UncertainComplex` \r\n when the mean of the data is complex.\r\n\r\n **Examples**::\r\n\r\n >>> data = range(15)\r\n >>> type_a.estimate(data)\r\n ureal(7.0,1.1547005383792515,14)\r\n \r\n >>> data = [(0.91518731126816899+1.5213442955575518j),\r\n ... (0.96572684493613492-0.18547192979059401j),\r\n ... (0.23216598132006649+1.6951311687588568j),\r\n ... (2.1642786101267397+2.2024333895672563j),\r\n ... (1.1812532664590505+0.59062101107787357j),\r\n ... (1.2259264339405165+1.1499373179910186j),\r\n ... (-0.99422341300318684+1.7359338393131392j),\r\n ... (1.2122867690240853+0.32535154897909946j),\r\n ... (2.0122536479379196-0.23283009302603963j),\r\n ... (1.6770229536619197+0.77195994890476838j)]\r\n\r\n >>> type_a.estimate(data)\r\n ucomplex((1.059187840567141+0.9574410497332932j), u=[0.28881665310241805,0.2655555630050262], r=-4.090655272692547, df=9)\r\n\r\n \"\"\"\r\n df = len(seq)-1\r\n mu = mean(seq)\r\n \r\n if isinstance(mu,complex):\r\n u,r = standard_uncertainty(seq,mu)\r\n return UncertainComplex._elementary(\r\n mu,u[0],u[1],r,df,\r\n label,\r\n independent = (r == 0.0)\r\n )\r\n \r\n else:\r\n u = standard_uncertainty(seq,mu)\r\n return UncertainReal._elementary(\r\n mu,u,df,label,independent=True\r\n )\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef mean(seq):\r\n \"\"\"Return the arithmetic mean of data in ``seq``\r\n\r\n If ``seq`` contains real or uncertain real numbers,\r\n a real number is returned.\r\n\r\n If ``seq`` contains complex or uncertain complex\r\n numbers, a complex number is returned.\r\n \r\n **Example**::\r\n\r\n >>> data = range(15)\r\n >>> type_a.mean(data)\r\n 7.0\r\n \r\n \"\"\"\r\n mu = sum(seq) / len(seq)\r\n if isinstance(mu,(numbers.Real,UncertainReal) ):\r\n return _as_value(mu)\r\n elif isinstance(mu,(numbers.Complex,UncertainComplex)):\r\n return _as_value(mu)\r\n else:\r\n raise TypeError(\r\n \"Unexpected type: '%s'\" % repr(mu)\r\n )\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef standard_deviation(seq,mu=None):\r\n \"\"\"Return the sample standard deviation\r\n \r\n :arg seq: sequence of data\r\n :arg mu: the arithmetic mean of ``seq``\r\n \r\n If ``seq`` contains real or uncertain real numbers, \r\n the sample standard deviation is returned.\r\n \r\n If ``seq`` contains complex or uncertain complex\r\n numbers, the standard deviation in the real and\r\n imaginary components is evaluated, as well as\r\n the correlation coefficient between the components.\r\n The results are returned in a pair of objects: a\r\n :obj:`~named_tuples.StandardDeviation` namedtuple \r\n and a correlation coefficient. \r\n\r\n Only the values of uncertain numbers are used in calculations. \r\n \r\n **Examples**::\r\n\r\n >>> data = range(15)\r\n >>> type_a.standard_deviation(data)\r\n 4.47213595499958\r\n\r\n >>> data = [(0.91518731126816899+1.5213442955575518j),\r\n ... (0.96572684493613492-0.18547192979059401j),\r\n ... (0.23216598132006649+1.6951311687588568j),\r\n ... (2.1642786101267397+2.2024333895672563j),\r\n ... (1.1812532664590505+0.59062101107787357j),\r\n ... (1.2259264339405165+1.1499373179910186j),\r\n ... (-0.99422341300318684+1.7359338393131392j),\r\n ... (1.2122867690240853+0.32535154897909946j),\r\n ... (2.0122536479379196-0.23283009302603963j),\r\n ... (1.6770229536619197+0.77195994890476838j)]\r\n >>> sd,r = type_a.standard_deviation(data)\r\n >>> sd\r\n StandardDeviation(real=0.913318449990377, imag=0.8397604244242309)\r\n >>> r\r\n -0.31374045124595246\r\n \r\n \"\"\"\r\n N = len(seq)\r\n \r\n if mu is None:\r\n mu = mean(seq)\r\n\r\n # `mean` returns either a real or complex\r\n if isinstance(mu,numbers.Real):\r\n accum = lambda psum,x: psum + (_as_value(x)-mu)**2\r\n variance = reduce(accum, seq, 0.0) / (N - 1)\r\n \r\n return math.sqrt( variance )\r\n \r\n elif isinstance(mu,numbers.Complex):\r\n cv_11,cv_12,cv_12,cv_22 = variance_covariance_complex(seq,mu)\r\n\r\n sd_re = math.sqrt(cv_11)\r\n sd_im = math.sqrt(cv_22)\r\n\r\n den = sd_re * sd_im\r\n \r\n if den == 0.0: \r\n if cv_12 != 0.0 :\r\n raise RuntimeError(\r\n \"numerical instability in covariance calculation\"\r\n )\r\n else:\r\n r = 0.0\r\n else:\r\n r = cv_12 / den\r\n \r\n return StandardDeviation(sd_re,sd_im), r\r\n \r\n else:\r\n assert False,\"unexpected\"\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef standard_uncertainty(seq,mu=None):\r\n \"\"\"Return the standard uncertainty of the sample mean\r\n\r\n :arg seq: sequence of data\r\n :arg mu: the arithmetic mean of ``seq``\r\n \r\n :rtype: float or :obj:`~named_tuples.StandardUncertainty`\r\n \r\n If ``seq`` contains real or uncertain real numbers,\r\n the standard uncertainty of the sample mean \r\n is returned.\r\n\r\n If ``seq`` contains complex or uncertain complex\r\n numbers, the standard uncertainties of the real and\r\n imaginary components are evaluated, as well as the\r\n sample correlation coefficient are returned in a\r\n :obj:`~named_tuples.StandardUncertainty` namedtuple\r\n\r\n Only the values of uncertain numbers are used in calculations. \r\n\r\n **Example**::\r\n\r\n >>> data = range(15)\r\n >>> type_a.standard_uncertainty(data)\r\n 1.1547005383792515\r\n\r\n >>> data = [(0.91518731126816899+1.5213442955575518j),\r\n ... (0.96572684493613492-0.18547192979059401j),\r\n ... (0.23216598132006649+1.6951311687588568j),\r\n ... (2.1642786101267397+2.2024333895672563j),\r\n ... (1.1812532664590505+0.59062101107787357j),\r\n ... (1.2259264339405165+1.1499373179910186j),\r\n ... (-0.99422341300318684+1.7359338393131392j),\r\n ... (1.2122867690240853+0.32535154897909946j),\r\n ... (2.0122536479379196-0.23283009302603963j),\r\n ... (1.6770229536619197+0.77195994890476838j)]\r\n >>> u,r = type_a.standard_uncertainty(data)\r\n >>> u\r\n StandardUncertainty(real=0.28881665310241805, imag=0.2655555630050262)\r\n >>> u.real\r\n 0.28881665310241805\r\n >>> r\r\n -0.31374045124595246\r\n\r\n \"\"\"\r\n ROOT_N = math.sqrt(len(seq))\r\n \r\n if mu is None:\r\n mu = mean(seq)\r\n\r\n if isinstance(mu,numbers.Real):\r\n sd = standard_deviation(seq,mu)\r\n return sd / ROOT_N \r\n \r\n elif isinstance(mu,numbers.Complex):\r\n sd,r = standard_deviation(seq,mu)\r\n return StandardUncertainty(sd.real/ROOT_N,sd.imag/ROOT_N),r\r\n \r\n else:\r\n assert False,\"unexpected, mu={!r}\".format(mu)\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef variance_covariance_complex(seq,mu=None):\r\n \"\"\"Return the sample variance-covariance matrix\r\n\r\n :arg seq: sequence of data \r\n :arg mu: the arithmetic mean of ``seq``\r\n\r\n :returns: a 4-element sequence\r\n\r\n If ``mu`` is ``None`` the mean will be evaluated \r\n by :func:`~type_a.mean`.\r\n\r\n ``seq`` may contain numbers or uncertain numbers.\r\n Only the values of uncertain numbers are used in calculations. \r\n \r\n Variance-covariance matrix elements are returned \r\n in a :obj:`~named_tuples.VarianceCovariance` namedtuple; \r\n they can be accessed using the \r\n attributes ``.rr``, ``.ri``, ``,ir`` and ``.ii``.\r\n \r\n **Example**::\r\n \r\n >>> data = [(0.91518731126816899+1.5213442955575518j),\r\n ... (0.96572684493613492-0.18547192979059401j),\r\n ... (0.23216598132006649+1.6951311687588568j),\r\n ... (2.1642786101267397+2.2024333895672563j),\r\n ... (1.1812532664590505+0.59062101107787357j),\r\n ... (1.2259264339405165+1.1499373179910186j),\r\n ... (-0.99422341300318684+1.7359338393131392j),\r\n ... (1.2122867690240853+0.32535154897909946j),\r\n ... (2.0122536479379196-0.23283009302603963j),\r\n ... (1.6770229536619197+0.77195994890476838j)]\r\n >>> type_a.variance_covariance_complex(data)\r\n VarianceCovariance(rr=0.8341505910928249, ri=-0.24062910264062262, ir=-0.24062910264062262, ii=0.7051975704291644)\r\n\r\n >>> v = type_a.variance_covariance_complex(data)\r\n >>> v[0]\r\n 0.8341505910928249\r\n >>> v.rr\r\n 0.8341505910928249\r\n >>> v.ii\r\n 0.7051975704291644\r\n\r\n \"\"\"\r\n N = len(seq)\r\n \r\n zseq = [ _as_value(x) for x in seq ]\r\n \r\n if mu is None:\r\n mu = mean(zseq) \r\n else:\r\n mu = complex( mu )\r\n\r\n \r\n accum_vr = lambda psum,z: psum + (z.real - mu.real)**2\r\n accum_vi = lambda psum,z: psum + (z.imag - mu.imag)**2\r\n accum_cv = lambda psum,z: psum + (z.imag - mu.imag)*(z.real - mu.real)\r\n \r\n cv_11 = reduce(accum_vr,zseq,0.0) / (N-1) \r\n cv_22 = reduce(accum_vi,zseq,0.0) / (N-1)\r\n cv_12 = reduce(accum_cv,zseq,0.0) / (N-1)\r\n\r\n return VarianceCovariance(cv_11,cv_12,cv_12,cv_22)\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef multi_estimate_real(seq_of_seq,labels=None):\r\n \"\"\"Return a sequence of uncertain real numbers \r\n\r\n :arg seq_of_seq: a sequence of sequences of data\r\n :arg labels: a sequence of `str` labels \r\n \r\n :rtype: seq of :class:`~lib.UncertainReal`\r\n\r\n The sequences in ``seq_of_seq`` must all be the same length.\r\n Each sequence is associated with a particular quantity and contains \r\n a sample of data. An uncertain number for the quantity will be created \r\n using the sample of data, using sample statistics. The covariance \r\n between different quantities will also be evaluated from the data.\r\n \r\n A sequence of elementary uncertain numbers are returned. The uncertain numbers \r\n are considered related, allowing a degrees-of-freedom calculations \r\n to be performed on derived quantities. \r\n\r\n **Example**::\r\n \r\n # From Appendix H2 in the GUM\r\n \r\n >>> V = [5.007,4.994,5.005,4.990,4.999]\r\n >>> I = [19.663E-3,19.639E-3,19.640E-3,19.685E-3,19.678E-3]\r\n >>> phi = [1.0456,1.0438,1.0468,1.0428,1.0433]\r\n >>> v,i,p = type_a.multi_estimate_real((V,I,phi),labels=('V','I','phi'))\r\n >>> v\r\n ureal(4.999,0.0032093613071761794,4, label='V')\r\n >>> i\r\n ureal(0.019661,9.471008394041335e-06,4, label='I')\r\n >>> p\r\n ureal(1.04446,0.0007520638270785368,4, label='phi')\r\n \r\n >>> r = v/i*cos(p)\r\n >>> r\r\n ureal(127.73216992810208,0.0710714073969954,4.0)\r\n \r\n \"\"\"\r\n M = len(seq_of_seq)\r\n N = len(seq_of_seq[0])\r\n \r\n if labels is not None and len(labels) != M:\r\n raise RuntimeError(\r\n \"Incorrect number of labels: '{!r}'\".format(labels) \r\n ) \r\n \r\n # Calculate the deviations from the mean for each sequence\r\n means = [ ]\r\n dev = []\r\n for i,seq_i in enumerate(seq_of_seq):\r\n if len(seq_i) != N:\r\n raise RuntimeError( \"{:d}th sequence length inconsistent\".format(i) )\r\n\r\n mu_i = math.fsum(seq_i) / N\r\n means.append( mu_i )\r\n dev.append([ float(x_j)-mu_i for x_j in seq_i])\r\n\r\n # calculate the covariance matrix\r\n N_N_1 = N*(N-1)\r\n u = []\r\n cv = [] # M elements of len M-1, M-2, ...\r\n for i,seq_i in enumerate(dev):\r\n u_i = math.sqrt(\r\n math.fsum(d_i**2 for d_i in seq_i)/N_N_1\r\n )\r\n u.append(u_i)\r\n cv.append([])\r\n for seq_j in dev[i+1:]:\r\n cv[i].append(\r\n math.fsum(\r\n d_i*d_j\r\n for d_i,d_j in izip(seq_i,seq_j)\r\n )/N_N_1\r\n )\r\n\r\n ureal = UncertainReal._elementary\r\n\r\n # Create a list of elementary uncertain numbers\r\n # to return a list of standard uncertainties\r\n # to normalise the CV matrix.\r\n df = N-1\r\n rtn = []\r\n for i in xrange(M):\r\n mu_i = means[i]\r\n u_i = u[i]\r\n l_i = labels[i] if labels is not None else \"\"\r\n rtn.append( ureal(mu_i,u_i,df,l_i,independent=False) )\r\n\r\n # Create the list of ensemble id's,\r\n # assign it to the register in the context,\r\n # set the correlation between nodes\r\n real_ensemble( rtn, df )\r\n \r\n for i in xrange(M):\r\n u_i = u[i]\r\n un_i = rtn[i]\r\n \r\n for j in xrange(M-1-i):\r\n cv_ij = cv[i][j]\r\n if cv_ij != 0.0:\r\n r = cv_ij / (u_i*u[i+j+1])\r\n un_j = rtn[i+j+1]\r\n set_correlation_real(un_i,un_j,r)\r\n\r\n return rtn\r\n\r\n#-----------------------------------------------------------------------------------------\r\ndef multi_estimate_complex(seq_of_seq,labels=None,context=_context):\r\n \"\"\"\r\n Return a sequence of uncertain complex numbers\r\n\r\n :arg seq_of_seq: a sequence of sequences of data\r\n :arg labels: a sequence of `str` labels\r\n \r\n :rtype: a sequence of :class:`~lib.UncertainComplex`\r\n \r\n The sequences in ``seq_of_seq`` must all be the same length.\r\n Each sequence contains a sample of data that is associated with \r\n a particular quantity. An uncertain number for the quantity will \r\n be created using this data from sample statistics. The covariance \r\n between different quantities will also be evaluated from the data.\r\n \r\n A sequence of elementary uncertain complex numbers are returned. These \r\n uncertain numbers are considered related, allowing a degrees-of-freedom \r\n calculations to be performed on derived quantities. \r\n \r\n Defines uncertain numbers using the sample statistics, including\r\n the sample covariance. \r\n\r\n **Example**::\r\n \r\n # From Appendix H2 in the GUM\r\n \r\n >>> I = [ complex(x) for x in (19.663E-3,19.639E-3,19.640E-3,19.685E-3,19.678E-3) ]\r\n >>> V = [ complex(x) for x in (5.007,4.994,5.005,4.990,4.999)]\r\n >>> P = [ complex(0,p) for p in (1.0456,1.0438,1.0468,1.0428,1.0433) ]\r\n\r\n >>> v,i,p = type_a.multi_estimate_complex( (V,I,P) )\r\n\r\n >>> get_correlation(v.real,i.real)\r\n -0.355311219817512\r\n\r\n >>> z = v/i*exp(p)\r\n >>> z.real\r\n ureal(127.73216992810208,0.0710714073969954,4.0)\r\n >>> get_correlation(z.real,z.imag)\r\n -0.5884297844235157\r\n \r\n \"\"\"\r\n M = len(seq_of_seq)\r\n N = len(seq_of_seq[0])\r\n \r\n if labels is not None and len(labels) != M:\r\n raise RuntimeError( \r\n \"Incorrect number of labels: '{!r}'\".format(labels) \r\n ) \r\n\r\n # 1. Create a 2M sequence of sequences of real values\r\n x = []\r\n for i in xrange(M):\r\n x.append( [ float(z_i.real) for z_i in seq_of_seq[i] ] )\r\n x.append( [ float(z_i.imag) for z_i in seq_of_seq[i] ] )\r\n if len(x[-1]) != N:\r\n raise RuntimeError(\r\n \"{:d}th sequence length is incorrect\".format(i)\r\n )\r\n\r\n TWOM = 2*M\r\n N_1 = N-1\r\n N_N_1 = N*N_1\r\n\r\n # 2. Evaluate the means and uncertainties (keep the deviation sequences)\r\n x_mean = [ math.fsum(seq_i) / N for seq_i in x ]\r\n x_u = []\r\n for i in xrange(TWOM):\r\n mu_i = x_mean[i]\r\n x[i] = [ mu_i - x_ij for x_ij in x[i] ]\r\n x_u.append(\r\n math.sqrt(\r\n math.fsum( x_ij**2 for x_ij in x[i] )/N_N_1\r\n )\r\n )\r\n # 3. Define uncertain M complex numbers\r\n ucomplex = UncertainComplex._elementary\r\n\r\n x_influences = []\r\n rtn = []\r\n for i in xrange(M):\r\n j = 2*i\r\n uc = ucomplex(\r\n complex(x_mean[j],x_mean[j+1]),\r\n x_u[j],x_u[j+1],0.0,\r\n N_1,\r\n labels[i] if labels is not None else None,\r\n independent=False\r\n )\r\n rtn.append( uc )\r\n x_influences.extend( (uc.real,uc.imag) )\r\n \r\n\r\n # 4. Calculate covariances and set correlation coefficients\r\n for i in xrange(TWOM-1):\r\n x_i = x[i]\r\n un_i = x_influences[i]\r\n for j in xrange(i+1,TWOM):\r\n x_j = x[j]\r\n cv = math.fsum( \r\n d_i*d_j for d_i,d_j in izip(x_i,x_j)\r\n )/N_N_1\r\n if cv != 0.0:\r\n r = cv/(x_u[i]*x_u[j]) \r\n set_correlation_real(un_i,x_influences[j],r)\r\n\r\n complex_ensemble( rtn, N_1 )\r\n \r\n return rtn\r\n\r\n#============================================================================ \r\nif __name__ == \"__main__\":\r\n import doctest\r\n from GTC import * \r\n doctest.testmod( optionflags=doctest.NORMALIZE_WHITESPACE )\r\n\r\n \r\n","sub_path":"GTC/type_a.py","file_name":"type_a.py","file_ext":"py","file_size_in_byte":23950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"285641582","text":"# http://hr.tencent.com/position.php?&start=10#a\n\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef main():\n url = \"http://hr.tencent.com/position.php?&start=10#a\"\n headers = {\n \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"accept-language\": \"zH-Cn,zh;q=0.9\",\n \"cache-control\": \"max-age=0\",\n \"connection\": \"keep-alive\",\n \"cookie\": \"PHPSESSId=f838p1k61v5q1o1u4a01310rg7; pgv_pvi=7488512000; pgv_si=s7002374144\",\n \"host\": \"hr.tencent.com\",\n \"upgrade-insecure-requests\": \"1\",\n \"user-agent\": \"mozilla/5.0 (windowS NT 10.0; win64; x64) appLewEbkit/537.36 (KHTML, likE gecko) chrome/67.0.3396.99 safari/537.36\",\n }\n\n res = requests.get(url,headers=headers)\n\n soup = BeautifulSoup(res.text,'lxml')\n odd_lst = soup.select('tr[class=\"odd\"]')\n even_lst = soup.select('tr[class=\"even\"]')\n odd_lst.extend(even_lst)\n\n zhaopin_info = []\n\n for i in odd_lst:\n item = {}\n name = i.td.a.string\n category = i.find_all('td')[1].string\n num = i.select('td')[2].string\n addr = i.select(\"td\")[3].get_text()\n time = i.select(\"td\")[4].get_text()\n\n item['name'] = name\n item['category'] = category\n item['num'] = num\n item['addr'] = addr\n item['time'] = time\n\n zhaopin_info.append(item)\n\n with open(\"zhaopin_info.txt\",\"w\") as f:\n f.write(str(zhaopin_info))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"0706/test01_tencent社招抓取首页招聘信息.py","file_name":"test01_tencent社招抓取首页招聘信息.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"505735716","text":"#import MySQLdb\nfrom sqlalchemy import create_engine\nimport csv\nimport string\nimport re,os,random,string,codecs\nimport requests\nfrom clint.textui import progress\nfrom itertools import (takewhile,repeat)\n\ndef chunks(l,n):\n '''Yield successive n-sized chunks from l. Useful for multi-processing'''\n chunk_list =[]\n for i in range(0, len(l), n):\n chunk_list.append(l[i:i + n])\n return chunk_list\n\ndef connect_to_db(host, username, password, database,server_side_cursors=False):\n engine = create_engine('mysql+mysqldb://{}:{}@{}/{}?charset=utf8mb4'.format(username, password, host, database ), encoding='utf-8', pool_size=30, max_overflow=0, server_side_cursors=server_side_cursors )\n return engine\n\ndef send_slack_notification(message, slack_client, slack_channel, section=\"DB Update\", level=\"info\"):\n color_map = {\"info\": \"#6699cc\", \"success\": \"#aad922\", \"warning\": \"#FFFF00\", \"error\": \"#d62828\"}\n print(color_map[level])\n return slack_client.api_call(\n \"chat.postMessage\",\n channel=slack_channel,\n text=section,\n attachments=[\n {\n \"color\": color_map[level],\n \"text\": message\n }\n ]\n )\n\ndef id_generator(size=25, chars=string.ascii_lowercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\ndef write_csv(rows, outputdir, filename):\n \"\"\" Write a list of lists to a csv file \"\"\"\n print(outputdir)\n print(os.path.join(outputdir, filename))\n writer = csv.writer(open(os.path.join(outputdir, filename), 'w',encoding='utf-8'))\n writer.writerows(rows)\n\ndef download(url, filepath):\n \"\"\" Download data from a URL with a handy progress bar \"\"\"\n\n print(\"Downloading: {}\".format(url))\n r = requests.get(url, stream=True)\n\n with open(filepath, 'wb') as f:\n content_length = int(r.headers.get('content-length'))\n for chunk in progress.bar(r.iter_content(chunk_size=1024),\n expected_size=(content_length/1024) + 1):\n if chunk:\n f.write(chunk)\n f.flush()\n\n\ndef get_patent_ids(db_con, new_db):\n\n patent_data = db_con.execute('select id, number from {}.patent'.format(new_db))\n patnums = {}\n for patent in patent_data:\n patnums[patent['number']] = patent['id']\n return set(patnums.keys()), patnums\n\n\ndef better_title(text):\n title = \" \".join([item if item not in [\"Of\", \"The\", \"For\", \"And\", \"On\"] else item.lower() for item in str(text).title().split( )])\n return re.sub('['+string.punctuation+']', '', title)\n\n\n# REQUIRES: a table's column info from information schema and table prefix for join statement\n# MODIFIES: nothing\n# EFFECTS: returns string statements for create, insert, and select components \n# in order to build query for a table \ndef get_column_info(table_col_info, table_prefix):\n \n column_data =[item for item in table_col_info]\n \n # create cols string for create, insert, and select statements for 1) rawinventor \n table_cols_create_stmt = [item[0] + ' ' + item[1] for item in column_data]\n table_cols_create_str = ', '.join(table_cols_create_stmt)\n \n table_cols_insert_stmt = [item[0] for item in column_data]\n table_cols_insert_str = ', '.join(table_cols_insert_stmt)\n \n table_cols_select_stmt = [table_prefix + item for item in table_cols_insert_stmt]\n table_cols_select_str = ', '.join(table_cols_select_stmt)\n \n return table_cols_create_str, table_cols_insert_str, table_cols_select_str\n \n# REQUIRES: two table component strings\n# MODIFIES: nothing\n# EFFECTS: returns full string column component \ndef get_full_column_strings(table1_str, table2_str):\n \n full_cols_str = table1_str + ',' + table2_str\n \n return full_cols_str\n\n\n\n\n\ndef rawbigcount(filename):\n f = open(filename, 'rb')\n bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))\n return sum( buf.count(b'\\n') for buf in bufgen if buf )\n","sub_path":"Development/helpers/general_helpers.py","file_name":"general_helpers.py","file_ext":"py","file_size_in_byte":3992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"443783341","text":"\nimport logging\nimport numpy as np\nimport cvxpy as cvx\n\nfrom opymize import Variable\nfrom opymize.functionals import SplitSum, SSD, PositivityFct, \\\n ZeroFct, IndicatorFct, L1Norms\nfrom opymize.linear import BlockOp, ScaleOp, GradientOp, \\\n MatrixMultR, DiagMatrixMultR\n\nfrom qball.models import ModelHARDI_SHM\nfrom qball.tools.cvx import cvxVariable, sparse_div_op, cvxOp\nfrom qball.operators.bndl1 import MaxFct\n\n# TODO: inpaint mask\n\nclass Model(ModelHARDI_SHM):\n name = \"sh_bndl1_tvc\"\n\n def __init__(self, *args, conf_lvl=0.9, **kwargs):\n ModelHARDI_SHM.__init__(self, *args, **kwargs)\n\n c = self.constvars\n imagedims = c['imagedims']\n n_image = c['n_image']\n d_image = c['d_image']\n l_labels = c['l_labels']\n l_shm = c['l_shm']\n\n self.data.init_bounds(conf_lvl)\n _, f1, f2 = self.data.bounds\n c['f1'], c['f2'] = [np.array(a.T, order='C') for a in [f1,f2]]\n\n self.x = Variable(\n ('u1', (n_image, l_labels)),\n ('u2', (n_image, l_labels)),\n ('v', (n_image, l_shm)),\n )\n\n self.y = Variable(\n ('p', (n_image, d_image, l_shm)),\n ('q0', (n_image,)),\n ('q1', (n_image, l_labels)),\n ('q2', (n_image, l_labels)),\n ('q3', (n_image, l_labels)),\n ('q4', (n_image, l_labels)),\n )\n\n # start with a uniform distribution in each voxel\n self.state = (self.x.new(), self.y.new())\n u1k, u2k, vk = self.x.vars(self.state[0])\n u1k[:] = 1.0/np.einsum('k->', c['b'])\n vk[:,0] = .5 / np.sqrt(np.pi)\n\n def setup_solver_pdhg(self):\n x, y = self.x.vars(named=True), self.y.vars(named=True)\n c = self.constvars\n imagedims = c['imagedims']\n n_image = c['n_image']\n d_image = c['d_image']\n l_labels = c['l_labels']\n l_shm = c['l_shm']\n\n self.pdhg_G = SplitSum([\n PositivityFct(x['u1']['size']), # \\delta_{u1 >= 0}\n ZeroFct(x['u1']['size']), # 0\n ZeroFct(x['v']['size']) # 0\n ])\n\n GradOp = GradientOp(imagedims, l_shm)\n\n bMult = MatrixMultR(n_image, c['b_precond']*c['b'][:,None])\n YMult = MatrixMultR(n_image, c['Y'], trans=True)\n YMMult = MatrixMultR(n_image, c['YM'], trans=True)\n\n m_u = ScaleOp(x['u1']['size'], -1)\n\n dbMult = DiagMatrixMultR(n_image, c['b'])\n mdbMult = DiagMatrixMultR(n_image, -c['b'])\n\n self.pdhg_linop = BlockOp([\n [ 0, 0, GradOp], # p = Dv\n [bMult, 0, 0], # q0 = \n [ m_u, 0, YMult], # q1 = Yv - u1\n [ 0, m_u, YMMult], # q2 = YMv - u2\n [ 0, mdbMult, 0], # q3 = -diag(b) u2\n [ 0, dbMult, 0] # q4 = diag(b) u2\n ])\n\n l1norms = L1Norms(n_image, (d_image, l_shm), c['lbd'], \"frobenius\")\n LowerBoundFct = MaxFct(np.einsum('ik,k->ik', c['f1'], -c['b']))\n UpperBoundFct = MaxFct(np.einsum('ik,k->ik', c['f2'], c['b']))\n\n self.pdhg_F = SplitSum([\n l1norms, # lbd*\\sum_i |p[i,:,:]|_2\n IndicatorFct(y['q0']['size'], c1=c['b_precond']), # \\delta_{q0 = 1}\n IndicatorFct(x['u1']['size']), # \\delta_{q1 = 0}\n IndicatorFct(x['u1']['size']), # \\delta_{q2 = 0}\n LowerBoundFct, # |max(0, q3 + diag(b)f1)|_1\n UpperBoundFct # |max(0, q4 - diag(b)f2)|_1\n ])\n\n def setup_solver_cvx(self):\n c = self.constvars\n imagedims = c['imagedims']\n n_image = c['n_image']\n d_image = c['d_image']\n l_labels = c['l_labels']\n l_shm = c['l_shm']\n\n self.cvx_x = Variable(\n ('p', (l_shm, d_image, n_image)),\n ('q0', (n_image,)),\n ('q1', (l_labels, n_image)),\n ('q2', (l_labels, n_image)),\n ('q3', (l_labels, n_image)),\n ('q4', (l_labels, n_image)),\n )\n\n self.cvx_y = Variable(\n ('u1', (n_image, l_labels)),\n ('v', (n_image, l_shm)),\n ('misc', (n_image*l_labels*5 + n_image,)),\n )\n\n p, q0, q1, q2, q3, q4 = [cvxVariable(*a['shape']) for a in self.cvx_x.vars()]\n self.cvx_vars = p + [q0,q1,q2,q3,q4]\n\n self.cvx_obj = cvx.Maximize(\n cvx.vec(q3).T*cvx.vec(cvx.diag(c['b'])*c['f1'].T)\n - cvx.vec(q4).T*cvx.vec(cvx.diag(c['b'])*c['f2'].T)\n - cvx.sum(q0))\n\n div_op = sparse_div_op(imagedims)\n\n self.cvx_dual = True\n self.cvx_constr = []\n\n # u1_constr\n for i in range(n_image):\n self.cvx_constr.append(c['b'][:]*q0[i] - q1[:,i] >= 0)\n\n # v_constr\n for i in range(n_image):\n for k in range(l_shm):\n Yk = cvx.vec(c['Y'][:,k])\n self.cvx_constr.append(\n Yk.T*(c['M'][k]*q2[:,i] + q1[:,i]) \\\n - cvxOp(div_op, p[k], i) == 0)\n\n # additional inequality constraints\n for i in range(n_image):\n for k in range(l_labels):\n self.cvx_constr.append(0 <= q3[k,i])\n self.cvx_constr.append(q3[k,i] <= 1)\n self.cvx_constr.append(0 <= q4[k,i])\n self.cvx_constr.append(q4[k,i] <= 1)\n self.cvx_constr.append(q4[k,i] - q3[k,i] - q2[k,i] == 0)\n\n for i in range(n_image):\n self.cvx_constr.append(sum(cvx.sum_squares(p[k][:,i]) \\\n for k in range(l_shm)) <= c['lbd']**2)\n","sub_path":"qball/models/sh_bndl1_tvc.py","file_name":"sh_bndl1_tvc.py","file_ext":"py","file_size_in_byte":5695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"397558888","text":"'''\nDependencies: pip install vk==2.0.2\nCompatible with VK API v5.52\nUsage: python vkpycrawler.py -dir -token \nTo get access token, go to\nhttps://oauth.vk.com/authorize?client_id=5810848&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=messages&response_type=token&v=5.52\n'''\nimport json\nimport os\nimport sys\nimport time\nimport argparse\nimport logging\nfrom urllib import request\nfrom vk import API, Session\n\n\n__author__ = 'ddavydov'\n\nlogger = logging.getLogger('vkpycrawler')\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s - %(levelname)s - %(message)s')\n\nTIME_DELAY = 0.2 # seconds\n\nargparser = argparse.ArgumentParser()\nargparser.add_argument('-dir', required=True)\nargparser.add_argument('-token', required=True)\n\n\nclass VKAPIWrapper(API):\n def __getattr__(self, item):\n if item in ['messages', 'users']:\n # workaround to avoid `too many requests` API error\n time.sleep(TIME_DELAY)\n return super().__getattr__(item)\n\n\nclass VKSessionWrapper(Session):\n def make_request(self, method_request, captcha_response=None):\n response = self.send_api_request(method_request,\n captcha_response=captcha_response)\n return json.loads(response.text)\n\n\nclass Worker(object):\n MESSAGES_PER_PAGE = 200\n PHOTOS_PER_PAGE = 200\n MEDIA_TYPE = 'photo'\n\n def __init__(self, dir, token, *args, **kwargs):\n self.dir = dir\n self.api = VKAPIWrapper(VKSessionWrapper(token))\n\n def _prepare_directory(self):\n if os.path.exists(self.dir):\n if not os.path.isdir(self.dir):\n raise Exception('%s is not a directory!' % self.dir)\n else:\n os.mkdir(self.dir)\n logger.info('Prepared directory')\n\n def _get_user_by_id(self, uids):\n return self.api.users.get(user_ids=uids)['response']\n\n def _scan_dialogues(self):\n logger.info('Getting list of dialogs..')\n offset = 0\n uids = []\n while offset <= len(uids):\n resp = self.api.messages.getDialogs(count=self.MESSAGES_PER_PAGE,\n offset=offset)\n offset += self.MESSAGES_PER_PAGE\n uids.extend([item['uid'] for item in resp['response'][1:]])\n return self._get_user_by_id(uids)\n\n def _scan_chats(self):\n # TODO: implement chat scan and fetch photos sent by user\n # TODO: as well as received by user\n return []\n\n def _get_photo_url(self, object: dict):\n ordered_keys = ['src_xxxbig', 'src_xxbig', 'src_xbig',\n 'src_big', 'src']\n for key in ordered_keys:\n if key in object.keys():\n return object[key]\n\n def _save_images(self, dest_dir, sources):\n logger.info('saving..')\n for url in sources:\n name = url.split('/')[-1]\n dest_file = os.path.join(dest_dir, name)\n if not os.path.exists(dest_file):\n request.urlretrieve(url, dest_file)\n\n def _fetch_files(self, peers_list):\n for item in peers_list:\n logger.info('Fetching files from {first_name} {last_name}..'\n .format(**item))\n sources = []\n start_from = None\n dest_dir = os.path.join(self.dir,\n '{first_name}_{last_name}'.format(**item))\n while start_from != '':\n logger.info('getting photo urls(page {page_num})..'\n .format(page_num=len(sources) // self.PHOTOS_PER_PAGE))\n kwargs = {'peer_id': item['uid'], 'media_type': self.MEDIA_TYPE,\n 'count': self.PHOTOS_PER_PAGE}\n if start_from:\n kwargs.update({'start_from': start_from})\n resp = self.api.messages.getHistoryAttachments(**kwargs)\n if (type(resp) != dict or 'response' not in resp or\n type(resp['response']) != dict): break\n sources.extend([self._get_photo_url(photo['photo'])\n for photo in resp['response'].values()\n if type(photo) == dict])\n if not start_from and sources:\n if not os.path.exists(dest_dir) or not os.path.isdir(dest_dir):\n os.mkdir(dest_dir)\n start_from = resp.get('next_from', '')\n self._save_images(dest_dir, sources)\n\n def run(self):\n self._prepare_directory()\n peers_list = self._scan_dialogues()\n peers_list.extend(self._scan_chats())\n self._fetch_files(peers_list)\n logger.info('Finished!')\n\nif __name__ == '__main__':\n args = argparser.parse_args(sys.argv[1:])\n worker = Worker(args.dir, args.token)\n worker.run()\n","sub_path":"vkpycrawler.py","file_name":"vkpycrawler.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"368916419","text":"import tensorflow as tf\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--activation', type=str, default=\"sigmoid\")\nparser.add_argument('--proc', type=int, default=4)\nparser.add_argument('--optimizer', type=str, default=\"gd\")\nargs = parser.parse_args()\n\n# load data\nmnist = input_data.read_data_sets('data/fashion', one_hot=True)\n# 1. Define Variables and Placeholders\nx = tf.placeholder(tf.float32, shape=[None, 784])\ny_ = tf.placeholder(tf.float32, shape=[None, 10])\n\n# building the model\ndef model(x):\n\n\tW1 = tf.Variable(tf.truncated_normal([784,200], stddev=0.1))\n\tb1 = tf.Variable(tf.zeros([200]))\n\tW2 = tf.Variable(tf.truncated_normal([200,100], stddev=0.1))\n\tb2 = tf.Variable(tf.zeros([100]))\n\tW3 = tf.Variable(tf.truncated_normal([100,60], stddev=0.1))\n\tb3 = tf.Variable(tf.zeros([60]))\n\tW4 = tf.Variable(tf.truncated_normal([60,30], stddev=0.1))\n\tb4 = tf.Variable(tf.zeros([30]))\n\tW5 = tf.Variable(tf.truncated_normal([30,10], stddev=0.1))\n\tb5 = tf.Variable(tf.zeros([10]))\n\n\tx_flat = tf.reshape(x, [-1, 784])\n\n\tdef activation_function(in_):\n\t\tif args.activation == \"relu\":\n\t\t\treturn tf.nn.relu(in_)\n\t\telif args.activation == \"sigmoid\":\n\t\t\treturn tf.nn.sigmoid(in_)\n\n\ty1 = activation_function(tf.matmul(x_flat, W1) + b1)\n\ty2 = activation_function(tf.matmul(y1, W2) + b2) \n\ty3 = activation_function(tf.matmul(y2, W3) + b3) \n\ty4 = activation_function(tf.matmul(y3, W4) + b4) \n\ty_logits = tf.matmul(y4, W5) + b5\n\toutput = tf.nn.softmax(y_logits) \n\n\treturn output, y_logits\n\nprediction, y = model(x)\n\n# 3. Define the loss function\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n# 4. Define the accuracy\ncorrect_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n# 5. Define an optimizer\nif args.optimizer == \"adam\":\n optimizer = tf.train.AdamOptimizer(0.0009) #0.8784\nelif args.optimizer == \"gd\":\n optimizer = tf.train.GradientDescentOptimizer(0.7) #0.859\ntrain_step = optimizer.minimize(cross_entropy)\n\n# initialize\ninit = tf.initialize_all_variables() \nconfig = tf.ConfigProto(intra_op_parallelism_threads=args.proc, inter_op_parallelism_threads=args.proc)\nsess = tf.Session(config=config)\nsess.run(init)\n\ndef training_step(i, update_test_data, update_train_data):\n\n\tif i % 100 == 0:\n\t\tprint(\"\\r\", i)\n ####### actual learning \n # reading batches of 100 images with 100 labels\n\tbatch_X, batch_Y = mnist.train.next_batch(100)\n # the backpropagation training step\n\ttrain_dict = {x: batch_X, y_: batch_Y}\n\tsess.run(train_step, feed_dict=train_dict)\n \n ####### evaluating model performance for printing purposes\n # evaluation used to later visualize how well you did at a particular time in the training\n\ttrain_a = []\n\ttrain_c = []\n\ttest_a = []\n\ttest_c = []\n\tif update_train_data:\n\t\ta, c = sess.run([accuracy, cross_entropy], feed_dict=train_dict)\n\t\ttrain_a.append(a)\n\t\ttrain_c.append(c)\n\n\tif update_test_data:\n\t\ttest_dict = {x: mnist.test.images, y_: mnist.test.labels}\n\t\ta, c = sess.run([accuracy, cross_entropy], feed_dict= test_dict)\n\t\ttest_a.append(a)\n\t\ttest_c.append(c)\n\treturn (train_a, train_c, test_a, test_c)\n\ntrain_a = []\ntrain_c = []\ntest_a = []\ntest_c = []\n \ntraining_iter = 10000\nepoch_size = 100\nfor i in range(training_iter):\n test = False\n if i % epoch_size == 0:\n test = True\n a, c, ta, tc = training_step(i, test, test)\n train_a += a\n train_c += c\n test_a += ta\n test_c += tc\n\nprint(\"Using \"+ args.activation.upper()+ \" + \" + args.optimizer.upper() + \".\")\n\ntest_dictionary = {x: mnist.test.images, y_: mnist.test.labels}\nprint(\"Test accuracy: \", sess.run(accuracy, feed_dict=test_dictionary))\n\n# accuracy training vs testing dataset\nplt.title(\"Accuracy\")\nplt.plot(train_a, label=\"train\")\nplt.plot(test_a, label=\"test\")\nplt.grid(True)\nplt.legend(loc=\"best\")\nplt.show()\n\n# loss training vs testing dataset\nplt.title(\"Loss\")\nplt.plot(train_c, label=\"train\")\nplt.plot(test_c, label=\"test\")\nplt.grid(True)\nplt.legend(loc=\"best\")\nplt.show()\n\n# Zoom in on the tail of the plots\nzoom_point = 50\nx_range = range(zoom_point,int(training_iter/epoch_size))\nplt.title(\"Accuracy Zoom\")\nplt.plot(x_range, train_a[zoom_point:], label=\"train\")\nplt.plot(x_range, test_a[zoom_point:], label=\"test\")\nplt.grid(True)\nplt.legend(loc=\"best\")\nplt.show()\n\nplt.title(\"Loss Zoom\")\nplt.plot(train_c[zoom_point:], label=\"train\")\nplt.plot(test_c[zoom_point:], label=\"test\")\nplt.grid(True)\nplt.legend(loc=\"best\")\nplt.show()\n\n\"\"\"\nQUESTION 1:\nUsing Relu + Adam test accuracy : 0.8673 on test set\nUsing Relu + gd test accuracy : 0.8563 on test set\nUsing Sigmoid + Adam test accuracy : 0.8784 on test set\nUsing Sigmoid + gd test accuracy : 0.86 on test set\n\nQUESTION 2:\nRelu is slightly faster in converging. The reason is that relu tends to reach convergence faster than saturating neurons.\nRelu is also faster from the computational point of view not requiring any exponential computation, this also tends to fasten\nthe training (not the convergence).\n\nQUESTION 3:\nWe use softmax because is the closest differentiable function to max that is thus trainable with gradient descent.\n\nQUESTION 4:\nWith the final implementation we didn't notice any strange behaviour but in a previously built model we had the possibility\nto observe the phenomenon of the dying relu. As a matter of fact due to excessively small gradient propagated through the \nnetwork more and more relu units were dying and after interrupting a certain number of paths we were observing a sudden drop \nin the prediciton capabilities of the network.\n\n\"\"\"","sub_path":"Lab2/final_files/two.py","file_name":"two.py","file_ext":"py","file_size_in_byte":5701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"104700308","text":"import json\nimport re\n\nimport requests\nimport ipaddress\n\nfrom django.db import transaction\nfrom django.core.cache import cache\nfrom django.utils.translation import ugettext_lazy as _\n\nimport reversion\n\nfrom peeringdb_server.models import (\n IXLanIXFMemberImportAttempt,\n IXLanIXFMemberImportLog,\n IXLanIXFMemberImportLogEntry,\n Network,\n NetworkIXLan,\n)\n\n\nclass Importer(object):\n\n allowed_member_types = [\n \"peering\",\n \"ixp\",\n \"routeserver\",\n \"probono\",\n ]\n allowed_states = [\n \"\",\n None,\n \"active\",\n \"inactive\",\n \"connected\",\n \"operational\",\n ]\n\n def __init__(self):\n self.cache_only = False\n self.skip_import = False\n self.reset()\n\n def reset(self, ixlan=None, save=False, asn=None):\n self.reset_log()\n self.netixlans = []\n self.netixlans_deleted = []\n self.ipaddresses = []\n self.asns = []\n self.archive_info = {}\n self.ixlan = ixlan\n self.save = save\n self.asn = asn\n\n def fetch(self, url, timeout=5):\n \"\"\"\n Retrieves ixf member export data from the url\n\n Will do a quick sanity check on the data\n\n Returns dict containing the parsed data.\n\n Arguments:\n - url \n\n Keyword arguments:\n - timeout : max time to spend on request\n \"\"\"\n\n if not url:\n return {\"pdb_error\": _(\"IXF import url not specified\")}\n\n try:\n result = requests.get(url, timeout=timeout)\n except Exception as exc:\n return {\"pdb_error\": exc}\n\n if result.status_code != 200:\n return {\"pdb_error\": \"Got HTTP status {}\".format(result.status_code)}\n\n try:\n data = result.json()\n except Exception as inst:\n data = {\"pdb_error\": _(\"No JSON could be parsed\")}\n return data\n\n data = self.sanitize(data)\n\n # locally cache result\n\n if data and not data.get(\"pdb_error\"):\n cache.set(self.cache_key(url), data, timeout=None)\n\n return data\n\n def cache_key(self, url):\n \"\"\"\n returns the django cache key to use for caching ix-f data\n\n Argument:\n\n url \n \"\"\"\n\n return \"IXF-CACHE-{}\".format(url)\n\n def fetch_cached(self, url):\n \"\"\"\n Returns locally cached IX-F data\n\n Arguments:\n\n url \n \"\"\"\n\n if not url:\n return {\"pdb_error\": _(\"IXF import url not specified\")}\n\n data = cache.get(self.cache_key(url))\n\n if data is None:\n return {\n \"pdb_error\": _(\"IX-F data not locally cached for this resource yet.\")\n }\n\n return data\n\n def sanitize(self, data):\n \"\"\"\n Takes ixf data dict and runs some sanitization on it\n \"\"\"\n\n invalid = None\n vlan_list_found = False\n\n # This fixes instances where ixps provide two separate entries for\n # vlans in vlan_list for ipv4 and ipv6 (AMS-IX for example)\n for member in data.get(\"member_list\", []):\n asn = member.get(\"asnum\")\n for conn in member.get(\"connection_list\", []):\n vlans = conn.get(\"vlan_list\", [])\n if not vlans:\n continue\n vlan_list_found = True\n if len(vlans) == 2:\n # if vlans[0].get(\"vlan_id\") == vlans[1].get(\"vlan_id\"):\n keys = list(vlans[0].keys()) + list(vlans[1].keys())\n if keys.count(\"ipv4\") == 1 and keys.count(\"ipv6\") == 1:\n vlans[0].update(**vlans[1])\n conn[\"vlan_list\"] = [vlans[0]]\n\n if not vlan_list_found:\n invalid = _(\"No entries in any of the vlan_list lists, aborting.\")\n\n data[\"pdb_error\"] = invalid\n\n return data\n\n def update(self, ixlan, save=True, data=None, timeout=5, asn=None):\n \"\"\"\n Sync netixlans under this ixlan from ixf member export json data (specs\n can be found at https://github.com/euro-ix/json-schemas)\n\n Arguments:\n - ixlan (IXLan): ixlan object to update from ixf\n\n Keyword Arguments:\n - save (bool): commit changes to db\n - asn (int): only process changes for this ASN\n\n Returns:\n - Tuple(success, netixlans, log)\n \"\"\"\n\n self.reset(ixlan=ixlan, save=save, asn=asn)\n\n # if data is not provided, retrieve it either from cache or\n # from the remote resource\n if data is None:\n if self.cache_only:\n data = self.fetch_cached(ixlan.ixf_ixp_member_list_url)\n else:\n data = self.fetch(ixlan.ixf_ixp_member_list_url, timeout=timeout)\n\n # bail if there has been any errors during sanitize() or fetch()\n if data.get(\"pdb_error\"):\n self.log_error(data.get(\"pdb_error\"), save=save)\n return (False, [], [], self.log)\n\n # bail if there are no active prefixes on the ixlan\n if ixlan.ixpfx_set_active.count() == 0:\n self.log_error(_(\"No prefixes defined on ixlan\"), save=save)\n return (False, [], [], self.log)\n\n if self.skip_import:\n return (True, [], [], self.log)\n\n try:\n # parse the ixf data\n self.parse(data)\n except KeyError as exc:\n # any key erros mean that the data is invalid, log the error and\n # bail (transactions are atomic and will be rolled back)\n self.log_error(\"Internal Error 'KeyError': {}\".format(exc), save=save)\n return (False, self.netixlans, [], self.log)\n\n # process any netixlans that need to be deleted\n self.process_deletions()\n\n # archive the import so we can roll it back later if needed\n self.archive()\n\n if save:\n self.save_log()\n\n return (True, self.netixlans, self.netixlans_deleted, self.log)\n\n @reversion.create_revision()\n def process_deletions(self):\n \"\"\"\n Cycles all netixlans on the ixlan targeted by the importer and\n will remove any that are no longer found in the ixf data by\n their ip addresses\n\n In order for a netixlan to be removed both it's ipv4 and ipv6 address\n or it's asn need to be gone from the ixf data after validation\n \"\"\"\n\n netixlan_qset = self.ixlan.netixlan_set_active\n\n # if we are only processing a specific asn ignore\n # all that dont match\n\n if self.asn:\n netixlan_qset = netixlan_qset.filter(asn=self.asn)\n\n for netixlan in netixlan_qset:\n\n ipv4 = \"{}-{}\".format(netixlan.asn, netixlan.ipaddr4)\n ipv6 = \"{}-{}\".format(netixlan.asn, netixlan.ipaddr6)\n\n if netixlan.asn not in self.asns:\n self.log_peer(\n netixlan.asn, \"delete\", _(\"ASN no longer in data\"), netixlan\n )\n self.netixlans_deleted.append(netixlan)\n if self.save:\n netixlan.delete()\n elif ipv4 not in self.ipaddresses and ipv6 not in self.ipaddresses:\n self.log_peer(\n netixlan.asn,\n \"delete\",\n _(\n \"Ip addresses no longer exist in validated data or are \"\n \"no longer with this asn\"\n ),\n netixlan,\n )\n self.netixlans_deleted.append(netixlan)\n if self.save:\n netixlan.delete()\n elif (netixlan.ipaddr4 and ipv4 not in self.ipaddresses) or (\n netixlan.ipaddr6 and ipv6 not in self.ipaddresses\n ):\n if not netixlan.network.allow_ixp_update:\n self.log_peer(\n netixlan.asn,\n \"delete\",\n _(\n \"At least one ipaddress mismatched and \"\n \"network has disabled updates\"\n ),\n netixlan,\n )\n self.netixlans_deleted.append(netixlan)\n if self.save:\n netixlan.delete()\n\n @transaction.atomic()\n def archive(self):\n \"\"\"\n Create the IXLanIXFMemberImportLog for this import\n \"\"\"\n\n if self.save and (self.netixlans or self.netixlans_deleted):\n persist_log = IXLanIXFMemberImportLog.objects.create(ixlan=self.ixlan)\n for netixlan in self.netixlans + self.netixlans_deleted:\n versions = reversion.models.Version.objects.get_for_object(netixlan)\n if len(versions) == 1:\n version_before = None\n else:\n version_before = versions[1]\n version_after = versions[0]\n info = self.archive_info.get(netixlan.id, {})\n persist_log.entries.create(\n netixlan=netixlan,\n version_before=version_before,\n action=info.get(\"action\"),\n reason=info.get(\"reason\"),\n version_after=version_after,\n )\n\n def parse(self, data):\n \"\"\"\n Parse ixf data\n\n Arguments:\n - data : result from fetch()\n \"\"\"\n with transaction.atomic():\n self.parse_members(data.get(\"member_list\", []))\n\n def parse_members(self, member_list):\n \"\"\"\n Parse the `member_list` section of the ixf schema\n\n Arguments:\n - member_list \n \"\"\"\n for member in member_list:\n # we only process members of certain types\n member_type = member.get(\"member_type\", \"peering\").lower()\n if member_type in self.allowed_member_types:\n # check that the as exists in pdb\n asn = member[\"asnum\"]\n\n # if we are only processing a specific asn, ignore all\n # that dont match\n if self.asn and asn != self.asn:\n continue\n\n # keep track of asns we find in the ix-f data\n if asn not in self.asns:\n self.asns.append(asn)\n\n if Network.objects.filter(asn=asn).exists():\n network = Network.objects.get(asn=asn)\n if network.status != \"ok\":\n self.log_peer(\n asn,\n \"ignore\",\n _(\"Network status is '{}'\").format(network.status),\n )\n continue\n\n self.parse_connections(\n member.get(\"connection_list\", []), network, member\n )\n else:\n self.log_peer(\n asn, \"ignore\", _(\"Network does not exist in peeringdb\")\n )\n else:\n self.log_peer(\n asn, \"ignore\", _(\"Invalid member type: {}\").format(member_type)\n )\n\n def parse_connections(self, connection_list, network, member):\n \"\"\"\n Parse the 'connection_list' section of the ixf schema\n\n Arguments:\n - connection_list \n - network : pdb network instance\n - member : row from ixf member_list\n \"\"\"\n\n asn = member[\"asnum\"]\n for connection in connection_list:\n state = connection.get(\"state\", \"active\").lower()\n if state in self.allowed_states:\n\n speed = self.parse_speed(connection.get(\"if_list\", []))\n\n self.parse_vlans(\n connection.get(\"vlan_list\", []), network, member, connection, speed\n )\n else:\n self.log_peer(\n asn, \"ignore\", _(\"Invalid connection state: {}\").format(state)\n )\n\n def parse_vlans(self, vlan_list, network, member, connection, speed):\n \"\"\"\n Parse the 'vlan_list' section of the ixf_schema\n\n Arguments:\n - vlan_list \n - network : pdb network instance\n - member : row from ixf member_list\n - connection : row from ixf connection_list\n - speed : interface speed\n \"\"\"\n\n asn = member[\"asnum\"]\n for lan in vlan_list:\n ipv4_valid = False\n ipv6_valid = False\n\n ipv4 = lan.get(\"ipv4\", {})\n ipv6 = lan.get(\"ipv6\", {})\n\n # vlan entry has no ipaddresses set, log and ignore\n if not ipv4 and not ipv6:\n self.log_error(\n _(\n \"Could not find ipv4 or 6 address in \"\n \"vlan_list entry for vlan_id {} (AS{})\"\n ).format(lan.get(\"vlan_id\"), asn)\n )\n continue\n\n ipv4_addr = ipv4.get(\"address\")\n ipv6_addr = ipv6.get(\"address\")\n\n # parse and validate the ipaddresses attached to the vlan\n # append the ipaddresses to self.ipaddresses so we can\n # later check them to see which netixlans need to be\n # dropped during `process_deletions`\n try:\n if ipv4_addr:\n self.ipaddresses.append(\n \"{}-{}\".format(\n asn, ipaddress.ip_address(u\"{}\".format(ipv4_addr))\n )\n )\n if ipv6_addr:\n self.ipaddresses.append(\n \"{}-{}\".format(\n asn, ipaddress.ip_address(u\"{}\".format(ipv6_addr))\n )\n )\n except (ipaddress.AddressValueError, ValueError) as exc:\n self.log_error(\n _(\"Ip address error '{}' in vlan_list entry for vlan_id {}\").format(\n exc, lan.get(\"vlan_id\")\n )\n )\n continue\n\n netixlan_info = NetworkIXLan(\n ixlan=self.ixlan,\n network=network,\n ipaddr4=ipv4_addr,\n ipaddr6=ipv6_addr,\n speed=speed,\n asn=asn,\n is_rs_peer=(\n ipv4.get(\"routeserver\", False) or ipv6.get(\"routeserver\", False)\n ),\n )\n\n if not self.save and (\n not self.ixlan.test_ipv4_address(ipv4_addr)\n and not self.ixlan.test_ipv6_address(ipv6_addr)\n ):\n # for the preview we don't care at all about new ip addresses\n # not at the ixlan if they dont match the prefix\n continue\n\n # if connection state is inactive we won't create or update\n if connection.get(\"state\", \"active\") == \"inactive\":\n self.log_peer(\n asn,\n \"noop\",\n _(\"Connection is currently marked as inactive\"),\n netixlan_info,\n )\n continue\n\n # after this point we either add or modify the netixlan, so\n # now is a good time to check if the related network allows\n # such updates, bail if not\n if not network.allow_ixp_update:\n self.log_peer(\n asn, \"noop\", _(\"Network has disabled ixp updates\"), netixlan_info\n )\n continue\n\n # add / modify the netixlan\n result = self.ixlan.add_netixlan(\n netixlan_info, save=self.save, save_others=self.save\n )\n\n if result[\"netixlan\"] and result[\"changed\"]:\n self.netixlans.append(result[\"netixlan\"])\n if result[\"created\"]:\n action = \"add\"\n reason = _(\"New ip-address\")\n else:\n action = \"modify\"\n reason = _(\"Fields changed: {}\").format(\n \", \".join(result.get(\"changed\"))\n )\n\n self.log_peer(asn, action, reason, result[\"netixlan\"])\n elif result[\"netixlan\"]:\n self.log_peer(asn, \"noop\", _(\"No changes\"), result[\"netixlan\"])\n elif result[\"log\"]:\n self.log_peer(asn, \"ignore\", \"\\n\".join(result[\"log\"]), netixlan_info)\n\n def parse_speed(self, if_list):\n \"\"\"\n Parse speed from the 'if_list' section in the ixf data\n\n Arguments:\n - if_list \n\n Returns:\n - speed \n \"\"\"\n speed = 0\n for iface in if_list:\n try:\n speed += int(iface.get(\"if_speed\", 0))\n except ValueError:\n self.log_error(\n _(\"Invalid speed value: {}\").format(iface.get(\"if_speed\"))\n )\n return speed\n\n def save_log(self):\n \"\"\"\n Save the attempt log\n \"\"\"\n IXLanIXFMemberImportAttempt.objects.update_or_create(\n ixlan=self.ixlan, defaults={\"info\": \"\\n\".join(json.dumps(self.log))}\n )\n\n def reset_log(self):\n \"\"\"\n Reset the attempt log\n \"\"\"\n self.log = {\"data\": [], \"errors\": []}\n\n def log_peer(self, asn, action, reason, netixlan=None):\n \"\"\"\n log peer action in attempt log\n\n Arguments:\n - asn \n - action : add | modify | delete | noop | ignore\n - reason \n\n Keyrword Arguments:\n - netixlan : if set, extra data will be added\n to the log.\n \"\"\"\n peer = {\n \"ixlan_id\": self.ixlan.id,\n \"ix_id\": self.ixlan.ix.id,\n \"ix_name\": self.ixlan.ix.name,\n \"asn\": asn,\n }\n\n if netixlan:\n peer.update(\n {\n \"net_id\": netixlan.network_id,\n \"ipaddr4\": \"{}\".format(netixlan.ipaddr4 or \"\"),\n \"ipaddr6\": \"{}\".format(netixlan.ipaddr6 or \"\"),\n \"speed\": netixlan.speed,\n \"is_rs_peer\": netixlan.is_rs_peer,\n }\n )\n\n if netixlan.id:\n self.archive_info[netixlan.id] = {\n \"action\": action,\n \"reason\": \"{}\".format(reason),\n }\n\n self.log[\"data\"].append(\n {\"peer\": peer, \"action\": action, \"reason\": \"{}\".format(reason),}\n )\n\n def log_error(self, error, save=False):\n \"\"\"\n Append error to the attempt log\n \"\"\"\n self.log[\"errors\"].append(\"{}\".format(error))\n if save:\n self.save_log()\n\n\nclass PostMortem(object):\n\n \"\"\"\n Generate postmortem report for ix-f import\n \"\"\"\n\n def reset(self, asn, **kwargs):\n\n \"\"\"\n Reset for a fresh run\n\n Argument(s):\n\n - asn : asn of the network to run postormem\n report for\n\n Keyword Argument(s):\n\n - limit : limit amount of import logs to process\n max limit is defined by server config `IXF_POSTMORTEM_LIMIT`\n\n \"\"\"\n\n self.asn = asn\n self.limit = kwargs.get(\"limit\", 100)\n self.post_mortem = []\n\n def generate(self, asn, **kwargs):\n \"\"\"\n Generate and return a new postmortem report\n\n Argument(s):\n\n - asn : asn of the network to run postmortem\n report for\n\n Keyword Argument(s):\n\n - limit : limit amount of import logs to process\n max limit is defined by server config `IXF_POSTMORTEM_LIMIT`\n\n Returns:\n\n - dict: postmortem report\n \"\"\"\n\n self.reset(asn, **kwargs)\n self._process_logs(limit=self.limit)\n return self.post_mortem\n\n def _process_logs(self, limit=100):\n\n \"\"\"\n Process IX-F import logs\n\n KeywordArgument(s):\n\n - limit : limit amount of import logs to process\n max limit is defined by server config `IXF_POSTMORTEM_LIMIT`\n \"\"\"\n\n # we only want import logs that actually touched the specified\n # asn\n\n qset = IXLanIXFMemberImportLogEntry.objects.filter(netixlan__asn=self.asn)\n qset = qset.exclude(action__isnull=True)\n qset = qset.order_by(\"-log__created\")\n qset = qset.select_related(\"log\", \"netixlan\", \"log__ixlan\", \"log__ixlan__ix\")\n\n for entry in qset[:limit]:\n self._process_log_entry(entry.log, entry)\n\n def _process_log_entry(self, log, entry):\n\n \"\"\"\n Process a single IX-F import log entry\n\n Argument(s):\n\n - log \n - entry \n\n \"\"\"\n\n if entry.netixlan.asn != self.asn:\n return\n\n data = entry.version_after.field_dict\n if data.get(\"asn\") != self.asn:\n return\n\n if data.get(\"ipaddr4\"):\n ipaddr4 = \"{}\".format(data.get(\"ipaddr4\"))\n else:\n ipaddr4 = None\n\n if data.get(\"ipaddr6\"):\n ipaddr6 = \"{}\".format(data.get(\"ipaddr6\"))\n else:\n ipaddr6 = None\n\n self.post_mortem.append(\n {\n \"ix_id\": log.ixlan.ix.id,\n \"ix_name\": log.ixlan.ix.name,\n \"ixlan_id\": log.ixlan.id,\n \"changes\": entry.changes,\n \"reason\": entry.reason,\n \"action\": entry.action,\n \"asn\": data.get(\"asn\"),\n \"ipaddr4\": ipaddr4,\n \"ipaddr6\": ipaddr6,\n \"speed\": data.get(\"speed\"),\n \"is_rs_peer\": data.get(\"is_rs_peer\"),\n \"created\": log.created.strftime(\"%Y-%m-%d %H:%M:%S\"),\n }\n )\n","sub_path":"peeringdb_server/ixf.py","file_name":"ixf.py","file_ext":"py","file_size_in_byte":22174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"645771787","text":"import synapse.exc as s_exc\n\nimport synapse.lib.stormlib.json as s_json\n\nimport synapse.tests.utils as s_test\n\nclass JsonTest(s_test.SynTest):\n\n async def test_stormlib_json(self):\n\n async with self.getTestCore() as core:\n\n self.eq(((1, 2, 3)), await core.callStorm('return($lib.json.load(\"[1, 2, 3]\"))'))\n self.eq(('[\"foo\", \"bar\", \"baz\"]'), await core.callStorm('return($lib.json.save((foo, bar, baz)))'))\n\n with self.raises(s_exc.BadJsonText):\n await core.callStorm('return($lib.json.load(foo))')\n\n with self.raises(s_exc.MustBeJsonSafe):\n await core.callStorm('return($lib.json.save($lib.print))')\n\n # jsonschema tests\n self.true(s_json.compileJsSchema(s_test.test_schema))\n resp = s_json.runJsSchema(s_test.test_schema, {'key:integer': 137})\n self.eq(137, resp.get('key:integer'))\n self.eq('Default string!', resp.get('key:string'))\n\n opts = {'vars': {'schema': s_test.test_schema}}\n q = '''$schemaObj = $lib.json.schema($schema)\n $item=$lib.dict()\n $item.\"key:integer\"=(4)\n return ( $schemaObj.validate($item) )\n '''\n isok, valu = await core.callStorm(q, opts=opts)\n self.true(isok)\n self.eq(4, valu.get('key:integer'))\n self.eq('Default string!', valu.get('key:string'))\n\n q = '''$schemaObj = $lib.json.schema($schema)\n $item=$lib.dict()\n $item.\"key:integer\"=4\n return ( $schemaObj.validate($item) )\n '''\n isok, valu = await core.callStorm(q, opts=opts)\n self.false(isok)\n self.eq('data.key:integer must be integer', valu.get('mesg'))\n\n with self.raises(s_exc.StormRuntimeError):\n q = '$schemaObj=$lib.json.schema((foo, bar))'\n await core.callStorm(q)\n\n q = '''\n $schemaObj = $lib.json.schema($schema, use_default=$lib.false)\n $item = ({\"key:integer\": 4})\n return($schemaObj.validate($item))\n '''\n isok, valu = await core.callStorm(q, opts={'vars': {'schema': s_test.test_schema}})\n self.true(isok)\n self.eq(4, valu.get('key:integer'))\n self.notin('key:string', valu)\n\n # Print a json schema obj\n q = \"$schemaObj = $lib.json.schema($schema) $lib.print('schema={s}', s=$schemaObj)\"\n msgs = await core.stormlist(q, opts=opts)\n self.stormIsInPrint('json:schema: {', msgs)\n\n q = \"$schemaObj = $lib.json.schema($schema) return ( $schemaObj.schema() )\"\n schema = await core.callStorm(q, opts=opts)\n self.eq(schema, s_test.test_schema)\n","sub_path":"synapse/tests/test_lib_stormlib_json.py","file_name":"test_lib_stormlib_json.py","file_ext":"py","file_size_in_byte":2789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"516963466","text":"import threading\nimport logging\nimport signal\n\n\nclass StoppableThread(threading.Thread):\n \"\"\" Stoppable Thread class prototype, takes a target and a stop_callback\n\n target: Instance to Thread\n stop_callback: Instances self-destruct method.\n\n \"\"\"\n\n # setup the logger\n logger = logging.getLogger(\"StoppableThread\")\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n\n logger.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch.setFormatter(formatter)\n logger.addHandler(ch)\n\n def __init__(self, target=None, stop_callback=None, **kwargs):\n super(StoppableThread, self).__init__(target=target, **kwargs)\n self.logger.debug(\"spawning thread %s\" % self)\n self.kwargs = kwargs\n self.target = target\n self.stop_callback = stop_callback\n self._stop = threading.Event()\n\n def stop(self):\n self.logger.debug(\"stopping thread: %s\" % self)\n self._stop.set()\n\n if self.target:\n self.logger.debug(\"sending SIGINT to %s\" % self.target)\n signal.signal(signal.SIGINT, self.target)\n self.logger.debug(\"SIGINT sent to %s\" % self.target)\n\n self.logger.debug(\"attempting stop_callbacks for %s\" % type(self.stop_callback))\n\n if self.stop_callback:\n try:\n self.logger.debug(\"calling stop_callback: %s\" % self.stop_callback)\n self.stop_callback\n except:\n self.logger.error(\"oops, couldnt stop that, maybe not an instancemethod?\")\n self.logger.debug(\"stop completed for %s\" % self)\n\n def stopped(self):\n self.logger.debug(\"stopped thread: %s\" % self)\n return self._stop.isSet()","sub_path":"libdeblox/threadblox.py","file_name":"threadblox.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"563284828","text":"import math\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass AudioDecoder(nn.Module):\n \"\"\"\n A simple encoder convolutional -> recurrent neural network for\n audio input.\n\n Args:\n num_layers (int): number of encoder layers.\n bidirectional (bool): bidirectional encoder.\n rnn_size (int): size of hidden states of the rnn.\n dropout (float): dropout probablity.\n sample_rate (float): input spec\n window_size (int): input spec\n\n \"\"\"\n def __init__(self, num_layers, bidirectional, rnn_size, dropout,\n downsample, window_size):\n super(AudioEncoder, self).__init__()\n self.num_layers = num_layers\n self.num_directions = 2 if bidirectional else 1\n self.hidden_size = rnn_size\n self.downsample = 8\n self.n_feats = 41\n \n # input_size = 608\n self.rnn = nn.LSTM(rnn_size, rnn_size,\n num_layers=num_layers,\n dropout=dropout,\n bidirectional=bidirectional)\n self.linear = nn.Linear(rnn_size, self.downsample*self.n_feats)\n\n def forward(self, input, context, state, context_lengths=None):\n \"See :obj:`onmt.modules.EncoderBase.forward()`\"\n\n output, hidden = self.rnn(context)\n output = self.linear(output)\n output = output.reshape(output.size(0), -1, self.n_feats)\n\n return output\n","sub_path":"onmt/modules/AudioDecoder.py","file_name":"AudioDecoder.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"425453084","text":"import os\n\nimport numpy as np\nimport pytest\n\nfrom lrspectrum.parsers import detect\nfrom lrspectrum.parsers import _parse_gaussian\nfrom lrspectrum.parsers import _parse_chronus\nfrom lrspectrum.parsers import _parse_delim\n\n\ndef check_same_dicts(dict1, dict2):\n assert len(dict1) == len(dict2)\n for (rk, rv), (ek, ev) in zip(dict1.items(), dict2.items()):\n print((rk, rv))\n print((ek, ev))\n assert rk == ek\n assert np.isclose(rv, ev)\n\n\ndef test_detect():\n \"\"\" Test parsers.detect \"\"\"\n\n filname = '_test_detect.tmp'\n\n # Test custom errors\n with pytest.raises(TypeError):\n detect(0)\n\n # Test default\n fil = open(filname, 'w')\n fil.write('Blah blah blah')\n fil.close()\n expected = 'delim'\n result = detect(filname)\n assert expected == result\n\n # Test Gaussian detection\n fil = open(filname, 'w')\n fil.write('This is part of the Gaussian')\n fil.close()\n expected = 'gaussian'\n result = detect(filname)\n assert expected == result\n\n fil = open(filname, 'w')\n fil.write('Gaussian')\n fil.close()\n result = detect(filname)\n assert expected == result\n\n # Test ChronusQ detection\n fil = open(filname, 'w')\n fil.write('ChronusQ')\n fil.close()\n expected = 'chronus'\n result = detect(filname)\n assert expected == result\n\n os.remove(filname)\n\n\ndef test__parse_gaussian():\n \"\"\" Test parsers._parse_gaussian \"\"\"\n\n # Test custom errors\n with pytest.raises(TypeError):\n _parse_gaussian(0)\n\n # Test parsing\n filname = 'lrspectrum/test/data/single_root.log'\n expected = {'5.182': 0.3}\n result = _parse_gaussian(filname)\n check_same_dicts(expected, result)\n\n\ndef test__parse_chronus():\n \"\"\" Test parsers._parse_chronus \"\"\"\n\n with pytest.raises(TypeError):\n _parse_chronus(0)\n\n # Test parsing\n filname = 'lrspectrum/test/data/chronusq.out'\n expected = {'0.92663078': 0.0001608,\n '1.79614206': 0.00923395,\n '1.82439203': 0.01562033}\n result = _parse_chronus(filname)\n check_same_dicts(expected, result)\n\n\ndef test__parse_delim():\n \"\"\"\" Test parsers._parse_delim \"\"\"\n\n # Test custom errors\n with pytest.raises(TypeError):\n _parse_delim(0)\n\n # Test parsing\n filname = 'lrspectrum/test/data/delim0.txt'\n expected = {'12.568': 0.0213, '1.2789e3': 5.634e-5, '9.825': 10064.0}\n result = _parse_delim(filname)\n check_same_dicts(expected, result)\n\n filname = 'lrspectrum/test/data/delim1.txt'\n result = _parse_delim(filname)\n check_same_dicts(expected, result)\n","sub_path":"lrspectrum/test/test_parsers.py","file_name":"test_parsers.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"26438281","text":"#!/usr/bin/python3\n\nimport re\nimport os\nimport sys\nimport collections\nimport gzip\nimport ihm.reader\nimport ihm.citations\nimport modelcif\nimport modelcif.dumper\nimport modelcif.model\nimport modelcif.alignment\nimport modelcif.reference\nfrom modelcif.alignment import ShorterSequenceIdentity as SequenceIdentity\nimport modelcif.protocol\n\n\n__version__ = \"0.4\"\n\n\nclass RefSeq(modelcif.reference.TargetReference):\n \"\"\"RefSeq\"\"\"\n\n\nclass PlasmoDB(modelcif.reference.TargetReference):\n \"\"\"PlasmoDB\"\"\"\n\n\nclass MPQSMetricType(modelcif.qa_metric.MetricType):\n \"\"\"composite score, values >1.1 are considered reliable\"\"\"\n\n\n# Single sequence in a Modeller alignment\nSequence = collections.namedtuple(\n \"Sequence\", [\"seqtyp\", \"chain\", \"method\", \"gapped\", \"primary\",\n \"primary_can\"])\n\n\n# Reference sequence database\nSequenceDB = collections.namedtuple(\n \"SequenceDB\", [\"name\", \"code\", \"accession\"])\n\n\n# Mapping between one-letter codes and PDB names\nthree_to_one = {\n 'ALA': 'A', 'CYS': 'C', 'ASP': 'D', 'GLU': 'E',\n 'PHE': 'F', 'GLY': 'G', 'HIS': 'H', 'ILE': 'I',\n 'LYS': 'K', 'LEU': 'L', 'MET': 'M', 'ASN': 'N',\n 'PRO': 'P', 'GLN': 'Q', 'ARG': 'R', 'SER': 'S',\n 'THR': 'T', 'VAL': 'V', 'TRP': 'W', 'TYR': 'Y',\n 'GLX': 'Z', 'ASX': 'B'\n}\n\none_to_three = {val: key for key, val in three_to_one.items()}\n\n\n# Some very old ModBase models contain UNK. The \"one-letter\" name for UNK\n# is also UNK, so just map to itself:\nthree_to_one['UNK'] = 'UNK'\n\n\ndef split_resnum(resnum):\n \"\"\"Split a residue number into number and insertion code (or None)\"\"\"\n m = re.match(r'([\\d-]+)(.*)$', resnum)\n return m.group(1), m.group(2) or None\n\n\nclass Alignment:\n \"\"\"Represent a Modeller alignment\"\"\"\n\n def __init__(self, fname):\n with open(fname) as fh:\n self.template, self.target = self._read_seqs(fh)\n\n def _read_seqs(self, fh):\n template, target = None, None\n for line in fh:\n if line.startswith('>P1;'):\n seq = self._read_seq(fh)\n if seq.seqtyp == 'sequence':\n target = seq\n elif seq.seqtyp.startswith('structure'):\n template = seq\n if template is None or target is None:\n raise ValueError(\"Could not read target and template \"\n \"from alignment\")\n # All current ModBase models have only template\n return template, target\n\n def _read_seq(self, fh):\n header = fh.readline().split(':')\n seqlines = []\n while True:\n line = fh.readline()\n if line == '':\n raise ValueError(\"End of file while reading sequence\")\n seqlines.append(line.rstrip('\\r\\n'))\n if seqlines[-1].endswith('*'):\n break\n gapped = \"\".join(seqlines)[:-1]\n # \"Canonical\" primary sequence is always a sequence of one-letter\n # codes; regular primary sequence is 1-letter for standard amino\n # acids, but can be longer for any non-standard residues (currently\n # only UNK is handled here, assuming X always means UNK in the\n # template).\n primary_can = gapped.replace('-', '')\n primary = ['UNK' if x == 'X' else x for x in primary_can]\n return Sequence(\n seqtyp=header[0], chain=header[3], method=header[7],\n gapped=gapped, primary=primary, primary_can=primary_can)\n\n\nclass _PolySeqSchemeHandler(ihm.reader.Handler):\n \"\"\"Read pdbx_poly_seq_scheme table and map PDB to mmCIF numbering\"\"\"\n def __init__(self, m):\n self.m = m\n\n def __call__(self, asym_id, entity_id, seq_id, pdb_seq_num, pdb_ins_code,\n pdb_strand_id):\n mk = (pdb_strand_id, pdb_seq_num, pdb_ins_code)\n if mk in self.m:\n self.m[mk] = (asym_id, entity_id, seq_id)\n\n\nclass Repository:\n \"\"\"Point to a directory containing a mirror of PDB in mmCIF format\"\"\"\n def __init__(self, topdir):\n self.topdir = topdir\n\n def open_mmcif(self, pdb_code):\n \"\"\"Given a PDB code, return a file handle to the corresponding mmCIF\"\"\"\n code = pdb_code.lower()\n fname = os.path.join(self.topdir, code[1:3], code + '.cif.gz')\n return gzip.open(fname, 'rt', encoding='latin1')\n\n def map_ranges(self, fh, ranges):\n \"\"\"Map a list of PDB (chain, resnum_start, resnum_end) tuples to the\n corresponding mmCIF (asym_id, entity_id, seq_id_start, seq_id_end)\n values and return. This is done by reading the pdbx_poly_seq_scheme\n table in the given mmCIF file.\"\"\"\n m = collections.OrderedDict()\n for r in ranges:\n # If we can't find the PDB numbering, return it unchanged\n m[r] = (r[0], None, r[1])\n h = _PolySeqSchemeHandler(m)\n r = ihm.format.CifReader(fh, {'_pdbx_poly_seq_scheme': h})\n r.read_file()\n return m.values()\n\n\nclass Structure:\n \"\"\"Handle read of PDB structure and write of mmCIF\"\"\"\n\n def __init__(self, repo):\n self.repo = repo\n\n def _read_pdb(self, fh):\n self.remarks = {}\n self.seqdb = []\n self.expdta = None\n self.title = None\n self.modpipe_version = None\n self.atoms = []\n\n for line in fh:\n # Handle standard ModBase headers\n if line.startswith('REMARK 220 SEQDB:'):\n val = [x.strip() for x in line[17:].split()]\n if len(val) == 3:\n self.seqdb.append(SequenceDB(\n name=val[0], accession=val[1], code=val[2]))\n elif len(val) == 2 and val[0] == 'RefSeq' and '.' in val[1]:\n self.seqdb.append(SequenceDB(\n name=val[0], accession=val[1].split('.', 1)[0],\n code=val[1]))\n elif len(val) == 2 and val[0] in ('PlasmoDB',):\n self.seqdb.append(SequenceDB(\n name=val[0], accession=val[1], code='.'))\n elif line.startswith('REMARK 6 GENERATED BY MODPIPE VERSION '):\n self.modpipe_version = line[40:].strip()\n elif line.startswith('REMARK') and line.count(':') == 1:\n key, val = [x.strip() for x in line[11:].split(':')]\n self.remarks[key] = val\n elif line.startswith('TITLE '):\n self.title = line[10:].strip()\n elif line.startswith('EXPDTA '):\n self.expdta = line[10:].strip()\n elif line.startswith('ATOM') or line.startswith('HETATM'):\n self.atoms.append(line)\n # All ModBase models are single chain\n if self.atoms:\n self.chain_id = self.atoms[0][21]\n\n def get_modeller_version(self):\n if self.expdta:\n m = re.search(r'MODELLER\\s+(Version\\s+)?(\\S+)', self.expdta)\n if m:\n return m.group(2)\n\n def get_mmcif_template_info(self, pdb_beg, pdb_end, pdb_chain, pdb_code):\n \"\"\"Given PDB (\"author-provided\") template information, map to\n mmCIF seq_id range, asym_id and entity_id, and return.\"\"\"\n # Split TEMPLATE BEGIN/END records into residue number and\n # insertion code\n pdb_beg, pdb_beg_ins = split_resnum(pdb_beg)\n pdb_end, pdb_end_ins = split_resnum(pdb_end)\n pdb_ranges = [(pdb_chain, pdb_beg, pdb_beg_ins),\n (pdb_chain, pdb_end, pdb_end_ins)]\n # Open the mmCIF file and map PDB ranges to mmCIF\n with self.repo.open_mmcif(pdb_code) as fh:\n cif_ranges = list(self.repo.map_ranges(fh, pdb_ranges))\n # Handle start==end\n if len(cif_ranges) == 1:\n cif_ranges = [cif_ranges[0], cif_ranges[0]]\n # asym_id of start and end should be the same\n assert cif_ranges[0][0] == cif_ranges[1][0]\n # If either end of the range has an entity_id, provide it\n entity_id = cif_ranges[0][1] or cif_ranges[1][1]\n return (int(cif_ranges[0][2]), int(cif_ranges[1][2]),\n cif_ranges[0][0], entity_id)\n\n def get_sequence3(self):\n \"\"\"Get PDB sequence as a sequence of 3-letter residue names\"\"\"\n resnum = None\n for a in self.atoms:\n this_resnum = a[22:26] # residue sequence number\n if this_resnum != resnum:\n yield a[17:20].strip() # residue name\n resnum = this_resnum\n\n def get_system(self, align):\n \"\"\"Create and return a modelcif.System object\"\"\"\n if align:\n align = Alignment(align)\n tgt_primary = [three_to_one[x] for x in self.get_sequence3()]\n\n model_id = self.remarks['MODPIPE MODEL ID']\n s = modelcif.System(\n title=self.title, id='model_' + model_id,\n database=modelcif.Database(id='MODBASE', code=model_id))\n c = ihm.Citation(\n title=\"ModBase, a database of annotated comparative protein \"\n \"structure models and associated resources\",\n journal=\"Nucleic Acids Res\", volume=42,\n page_range=('D336', 'D346'), year=2014, pmid=24271400,\n authors=['Pieper, U.', 'Webb, B.M.', 'Dong, G.Q.',\n 'Schneidman-Duhovny, D.', 'Fan, H.', 'Kim, S.J.',\n 'Khuri, N.', 'Spill, Y.G.', 'Weinkam, P.', 'Hammel, M.',\n 'Tainer, J.A.', 'Nilges, M.', 'Sali, A.'],\n doi='10.1093/nar/gkt1144', is_primary=True)\n s.citations.append(c)\n\n s.authors.extend(('Pieper, U.', 'Webb, B.', 'Narayanan, E.',\n 'Sali, A.'))\n modpipe_software = modelcif.Software(\n name='ModPipe', classification='comparative modeling',\n location='https://salilab.org/modpipe/', type='program',\n version=self.modpipe_version,\n description='Comparative modeling pipeline')\n modeller_software = modelcif.Software(\n name='MODELLER', classification='comparative modeling',\n location='https://salilab.org/modeller/', type='program',\n version=self.get_modeller_version(),\n citation=ihm.citations.modeller,\n description='Comparative modeling by satisfaction of '\n 'spatial restraints')\n this_software = modelcif.Software(\n name='modbase_pdb_to_cif.py', classification=\"format conversion\",\n location='https://github.com/salilab/modbase_utils',\n version=__version__,\n description=\"Conversion of ModBase PDB and alignment files \"\n \"to mmCIF format\")\n s.software.extend((modpipe_software, modeller_software, this_software))\n\n tgtbeg = int(self.remarks['TARGET BEGIN'])\n tgtend = int(self.remarks['TARGET END'])\n if align:\n template_e = modelcif.Entity(align.template.primary,\n description=\"Template\")\n template_pdb = self.remarks['TEMPLATE PDB']\n # Some very old models use single-chain PDB templates with no\n # chain ID. These have all since been remediated, almost certainly\n # to use chain ID 'A'.\n template_chain = self.remarks['TEMPLATE CHAIN'] or 'A'\n tmpbeg, tmpend, tmpasym, tmpentity = self.get_mmcif_template_info(\n self.remarks['TEMPLATE BEGIN'], self.remarks['TEMPLATE END'],\n template_chain, template_pdb)\n template = modelcif.Template(\n entity=template_e, asym_id=tmpasym, model_num=1,\n strand_id=template_chain, entity_id=tmpentity,\n name=\"Template structure\",\n transformation=modelcif.Transformation.identity(),\n references=[modelcif.reference.PDB(template_pdb)])\n if align and align.template.primary == tgt_primary:\n target_e = template_e\n target_e.description = \"Target and template\"\n else:\n target_e = modelcif.Entity(tgt_primary, description=\"Target\")\n target_e.references.extend(self.get_target_refs(tgtbeg, tgtend))\n chain_id = self.chain_id.strip() or 'A'\n asym = modelcif.AsymUnit(target_e, details='Model subunit',\n id=chain_id, auth_seq_id_map=tgtbeg-1)\n asmb = modelcif.Assembly((asym,), name='Modeled assembly')\n\n class OurAlignment(modelcif.alignment.Global,\n modelcif.alignment.Pairwise):\n pass\n if align:\n p = modelcif.alignment.Pair(\n template=template.segment(align.template.gapped,\n tmpbeg, tmpend),\n target=asym.segment(align.target.gapped,\n 1, len(align.target.primary)),\n score=modelcif.alignment.BLASTEValue(self.remarks['EVALUE']),\n identity=SequenceIdentity(self.remarks['SEQUENCE IDENTITY']))\n aln = OurAlignment(name=\"Target Template Alignment\",\n software=modpipe_software, pairs=[p])\n else:\n aln = OurAlignment(name=\"Target Template Alignment\",\n software=modpipe_software, pairs=[])\n s.alignments.append(aln)\n modeling_input = modelcif.data.DataGroup((aln, target_e))\n if align:\n modeling_input.append(template)\n\n model = self.get_model_class(asym, self.atoms)(\n assembly=asmb, name='Target Structure')\n model.qa_metrics.extend(self.get_scores(modeller_software,\n modpipe_software))\n\n model_group = modelcif.model.ModelGroup([model], name='All models')\n s.model_groups.append(model_group)\n\n protocol = modelcif.protocol.Protocol()\n mth = \" %s\" % align.template.method if align else ''\n modpipe_db = modelcif.ReferenceDatabase(\n name='ModPipe sequence and structure database',\n url='https://salilab.org/modpipe/doc/databases.html')\n protocol.steps.append(modelcif.protocol.TemplateSearchStep(\n name='ModPipe%s' % mth, software=modpipe_software,\n input_data=modelcif.data.DataGroup([target_e, modpipe_db]),\n output_data=aln))\n protocol.steps.append(modelcif.protocol.ModelingStep(\n software=modeller_software, input_data=modeling_input,\n output_data=model))\n protocol.steps.append(modelcif.protocol.ModelSelectionStep(\n software=modpipe_software, input_data=model, output_data=model))\n s.protocols.append(protocol)\n\n return s\n\n def get_target_refs(self, tgtbeg, tgtend):\n refmap = {'UniProt': modelcif.reference.UniProt,\n 'RefSeq': RefSeq,\n 'PlasmoDB': PlasmoDB}\n for db in self.seqdb:\n cls = refmap.get(db.name)\n if cls:\n yield cls(code=db.code, accession=db.accession,\n align_begin=tgtbeg, align_end=tgtend,\n isoform=ihm.unknown)\n\n def get_model_class(self, asym, atoms):\n class MyModel(modelcif.model.HomologyModel):\n def get_atoms(self):\n pdb_resnum = None\n seqid = 1\n for a in atoms:\n # Detect new residue if PDB resnum changed\n pdb_this_resnum = a[22:26]\n if (pdb_resnum is not None\n and pdb_this_resnum != pdb_resnum):\n seqid += 1\n pdb_resnum = pdb_this_resnum\n element = a[76:78].strip() or ihm.unknown\n # Very old PDBs don't have sequence where the element\n # should be, so ignore that; guess element as the first\n # character of name\n if a[73:76] == '1SG':\n element = a[13:14].strip() or ihm.unknown\n yield modelcif.model.Atom(\n asym_unit=asym, type_symbol=element,\n seq_id=seqid, atom_id=a[12:16].strip(),\n x=a[30:38].strip(), y=a[38:46].strip(),\n z=a[46:54].strip(),\n biso=a[60:66].strip(),\n occupancy=a[54:60].strip())\n return MyModel\n\n def get_scores(self, modeller_software, modpipe_software):\n tsvmod_method = self.remarks.get('TSVMOD METHOD')\n tsvmod_rmsd = self.remarks.get('TSVMOD RMSD')\n tsvmod_no35 = self.remarks.get('TSVMOD NO35')\n ga341 = self.remarks.get('GA341 SCORE',\n self.remarks.get('MODEL SCORE'))\n zdope = self.remarks.get('zDOPE SCORE',\n self.remarks.get('ZDOPE SCORE'))\n mpqs = self.remarks.get('MPQS',\n self.remarks.get('MODPIPE QUALITY SCORE'))\n if not mpqs:\n return\n\n class GA341(modelcif.qa_metric.Global,\n modelcif.qa_metric.NormalizedScore):\n \"\"\"GA341 fold reliability score\"\"\"\n software = modeller_software\n\n class MPQS(modelcif.qa_metric.Global, MPQSMetricType):\n \"\"\"ModPipe Quality Score\"\"\"\n software = modpipe_software\n\n class zDOPE(modelcif.qa_metric.Global, modelcif.qa_metric.ZScore):\n \"\"\"Normalized DOPE\"\"\"\n software = modeller_software\n\n yield GA341(ga341)\n yield MPQS(mpqs)\n yield zDOPE(zdope)\n\n if tsvmod_rmsd:\n class TSVModRMSD(modelcif.qa_metric.Global,\n modelcif.qa_metric.Distance):\n __doc__ = \"TSVMod predicted RMSD (%s)\" % tsvmod_method\n name = \"TSVMod RMSD\"\n software = None\n\n class TSVModNO35(modelcif.qa_metric.Global,\n modelcif.qa_metric.NormalizedScore):\n __doc__ = (\"TSVMod predicted native overlap (%s)\"\n % tsvmod_method)\n name = \"TSVMod NO35\"\n software = None\n\n yield TSVModRMSD(tsvmod_rmsd)\n yield TSVModNO35(tsvmod_no35)\n\n\ndef read_pdb(fh, repo):\n \"\"\"Read PDB file from filehandle and return a new Structure\"\"\"\n s = Structure(repo)\n s._read_pdb(fh)\n return s\n\n\nif __name__ == '__main__':\n import argparse\n a = argparse.ArgumentParser(\n description=\"Utility to convert ModBase PDB files to mmCIF\",\n epilog=\"\"\"\nConvert a PDB file, downloaded from ModBase, to mmCIF format. This should\npreserve all information in the PDB file. If the corresponding alignment is\nalso provided (-a flag) alignment information is added to the mmCIF (in which\ncase the resulting mmCIF file should match that downloaded directly from\nModBase).\n\"\"\")\n a.add_argument(\"-a\", \"--align\", metavar=\"FILE\",\n help=\"Input alignment file\")\n a.add_argument(\"-r\", \"--repo\", default='.',\n help=\"Directory containing repository of mmCIF files\")\n a.add_argument(\"pdb\", help=\"Input PDB file\")\n a.add_argument(\"mmcif\", help=\"Output mmCIF file\")\n args = a.parse_args()\n\n r = Repository(args.repo)\n if args.pdb == '-':\n s = read_pdb(sys.stdin, r)\n else:\n with open(args.pdb) as fh:\n s = read_pdb(fh, r)\n system = s.get_system(args.align)\n\n if args.mmcif == '-':\n modelcif.dumper.write(sys.stdout, [system])\n else:\n if args.mmcif.endswith('.bcif'):\n mode, fmt = \"wb\", \"BCIF\"\n else:\n mode, fmt = \"w\", \"mmCIF\"\n with open(args.mmcif, mode) as fh:\n modelcif.dumper.write(fh, [system], format=fmt)\n","sub_path":"modbase_pdb_to_cif.py","file_name":"modbase_pdb_to_cif.py","file_ext":"py","file_size_in_byte":19763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"448820597","text":"import ctypes\r\nimport functools\r\nimport io\r\nimport math\r\nimport queue\r\n\r\n\r\n\r\n########################################################################################################################\r\n##################################################### HELPERS ######################################################\r\n########################################################################################################################\r\n\r\ndef wcscmp (str_a, str_b):\r\n \"\"\"\r\n Standard library wcscmp\r\n \"\"\"\r\n for a, b in zip(str_a, str_b):\r\n tmp = ord(a) - ord(b)\r\n if tmp != 0: return -1 if tmp < 0 else 1\r\n\r\n tmp = len(str_a) - len(str_b)\r\n return -1 if tmp < 0 else 1 if tmp > 0 else 0\r\n\r\n\r\n\r\n########################################################################################################################\r\n#################################################### EXCEPTIONS ####################################################\r\n########################################################################################################################\r\n\r\nclass Ext4Error (Exception):\r\n \"\"\"\r\n Base class for all custom errors\r\n \"\"\"\r\n pass\r\n\r\nclass BlockMapError (Ext4Error):\r\n \"\"\"\r\n Raised, when a requested file_block is not mapped to disk\r\n \"\"\"\r\n pass\r\n\r\nclass EndOfStreamError (Ext4Error):\r\n \"\"\"\r\n Raised, when BlockReader reads beyond the end of the volume's underlying stream\r\n \"\"\"\r\n pass\r\n\r\nclass MagicError (Ext4Error):\r\n \"\"\"\r\n Raised, when a structures magic value is wrong and ignore_magic is False\r\n \"\"\"\r\n pass\r\n\r\n\r\n\r\n########################################################################################################################\r\n#################################################### LOW LEVEL #####################################################\r\n########################################################################################################################\r\n\r\nclass ext4_struct (ctypes.LittleEndianStructure):\r\n \"\"\"\r\n Simplifies access to *_lo and *_hi fields\r\n \"\"\"\r\n def __getattr__ (self, name):\r\n \"\"\"\r\n Enables reading *_lo and *_hi fields together.\r\n \"\"\"\r\n try:\r\n # Combining *_lo and *_hi fields\r\n lo_field = ctypes.LittleEndianStructure.__getattribute__(type(self), name + \"_lo\")\r\n size = lo_field.size\r\n\r\n lo = lo_field.__get__(self)\r\n hi = ctypes.LittleEndianStructure.__getattribute__(self, name + \"_hi\")\r\n\r\n return (hi << (8 * size)) | lo\r\n except AttributeError:\r\n return ctypes.LittleEndianStructure.__getattribute__(self, name)\r\n\r\n def __setattr__ (self, name, value):\r\n \"\"\"\r\n Enables setting *_lo and *_hi fields together.\r\n \"\"\"\r\n try:\r\n # Combining *_lo and *_hi fields\r\n lo_field = lo_field = ctypes.LittleEndianStructure.__getattribute__(type(self), name + \"_lo\")\r\n size = lo_field.size\r\n\r\n lo_field.__set__(self, value & ((1 << (8 * size)) - 1))\r\n ctypes.LittleEndianStructure.__setattr__(self, name + \"_hi\", value >> (8 * size))\r\n except AttributeError:\r\n ctypes.LittleEndianStructure.__setattr__(self, name, value)\r\n\r\n\r\n\r\nclass ext4_dir_entry_2 (ext4_struct):\r\n _fields_ = [\r\n (\"inode\", ctypes.c_uint), # 0x0\r\n (\"rec_len\", ctypes.c_ushort), # 0x4\r\n (\"name_len\", ctypes.c_ubyte), # 0x6\r\n (\"file_type\", ctypes.c_ubyte) # 0x7\r\n # Variable length field \"name\" missing at 0x8\r\n ]\r\n\r\n def _from_buffer_copy (raw, offset = 0, platform64 = True):\r\n struct = ext4_dir_entry_2.from_buffer_copy(raw, offset)\r\n struct.name = raw[offset + 0x8 : offset + 0x8 + struct.name_len]\r\n return struct\r\n\r\n\r\n\r\nclass ext4_extent (ext4_struct):\r\n _fields_ = [\r\n (\"ee_block\", ctypes.c_uint), # 0x0000\r\n (\"ee_len\", ctypes.c_ushort), # 0x0004\r\n (\"ee_start_hi\", ctypes.c_ushort), # 0x0006\r\n (\"ee_start_lo\", ctypes.c_uint) # 0x0008\r\n ]\r\n\r\n\r\n\r\nclass ext4_extent_header (ext4_struct):\r\n _fields_ = [\r\n (\"eh_magic\", ctypes.c_ushort), # 0x0000, Must be 0xF30A\r\n (\"eh_entries\", ctypes.c_ushort), # 0x0002\r\n (\"eh_max\", ctypes.c_ushort), # 0x0004\r\n (\"eh_depth\", ctypes.c_ushort), # 0x0006\r\n (\"eh_generation\", ctypes.c_uint) # 0x0008\r\n ]\r\n\r\n\r\n\r\nclass ext4_extent_idx (ext4_struct):\r\n _fields_ = [\r\n (\"ei_block\", ctypes.c_uint), # 0x0000\r\n (\"ei_leaf_lo\", ctypes.c_uint), # 0x0004\r\n (\"ei_leaf_hi\", ctypes.c_ushort), # 0x0008\r\n (\"ei_unused\", ctypes.c_ushort) # 0x000A\r\n ]\r\n\r\n\r\n\r\nclass ext4_group_descriptor (ext4_struct):\r\n _fields_ = [\r\n (\"bg_block_bitmap_lo\", ctypes.c_uint), # 0x0000\r\n (\"bg_inode_bitmap_lo\", ctypes.c_uint), # 0x0004\r\n (\"bg_inode_table_lo\", ctypes.c_uint), # 0x0008\r\n (\"bg_free_blocks_count_lo\", ctypes.c_ushort), # 0x000C\r\n (\"bg_free_inodes_count_lo\", ctypes.c_ushort), # 0x000E\r\n (\"bg_used_dirs_count_lo\", ctypes.c_ushort), # 0x0010\r\n (\"bg_flags\", ctypes.c_ushort), # 0x0012\r\n (\"bg_exclude_bitmap_lo\", ctypes.c_uint), # 0x0014\r\n (\"bg_block_bitmap_csum_lo\", ctypes.c_ushort), # 0x0018\r\n (\"bg_inode_bitmap_csum_lo\", ctypes.c_ushort), # 0x001A\r\n (\"bg_itable_unused_lo\", ctypes.c_ushort), # 0x001C\r\n (\"bg_checksum\", ctypes.c_ushort), # 0x001E\r\n\r\n # 64-bit fields\r\n (\"bg_block_bitmap_hi\", ctypes.c_uint), # 0x0020\r\n (\"bg_inode_bitmap_hi\", ctypes.c_uint), # 0x0024\r\n (\"bg_inode_table_hi\", ctypes.c_uint), # 0x0028\r\n (\"bg_free_blocks_count_hi\", ctypes.c_ushort), # 0x002C\r\n (\"bg_free_inodes_count_hi\", ctypes.c_ushort), # 0x002E\r\n (\"bg_used_dirs_count_hi\", ctypes.c_ushort), # 0x0030\r\n (\"bg_itable_unused_hi\", ctypes.c_ushort), # 0x0032\r\n (\"bg_exclude_bitmap_hi\", ctypes.c_uint), # 0x0034\r\n (\"bg_block_bitmap_csum_hi\", ctypes.c_ushort), # 0x0038\r\n (\"bg_inode_bitmap_csum_hi\", ctypes.c_ushort), # 0x003A\r\n (\"bg_reserved\", ctypes.c_uint), # 0x003C\r\n ]\r\n\r\n def _from_buffer_copy (raw, platform64 = True):\r\n struct = ext4_group_descriptor.from_buffer_copy(raw)\r\n\r\n if not platform64:\r\n struct.bg_block_bitmap_hi = 0\r\n struct.bg_inode_bitmap_hi = 0\r\n struct.bg_inode_table_hi = 0\r\n struct.bg_free_blocks_count_hi = 0\r\n struct.bg_free_inodes_count_hi = 0\r\n struct.bg_used_dirs_count_hi = 0\r\n struct.bg_itable_unused_hi = 0\r\n struct.bg_exclude_bitmap_hi = 0\r\n struct.bg_block_bitmap_csum_hi = 0\r\n struct.bg_inode_bitmap_csum_hi = 0\r\n struct.bg_reserved = 0\r\n\r\n return struct\r\n\r\n\r\n\r\nclass ext4_inode (ext4_struct):\r\n EXT2_GOOD_OLD_INODE_SIZE = 128 # Every field passing 128 bytes is \"additional data\", whose size is specified by i_extra_isize.\r\n\r\n # i_mode\r\n S_IXOTH = 0x1 # Others can execute\r\n S_IWOTH = 0x2 # Others can write\r\n S_IROTH = 0x4 # Others can read\r\n S_IXGRP = 0x8 # Group can execute\r\n S_IWGRP = 0x10 # Group can write\r\n S_IRGRP = 0x20 # Group can read\r\n S_IXUSR = 0x40 # Owner can execute\r\n S_IWUSR = 0x80 # Owner can write\r\n S_IRUSR = 0x100 # Owner can read\r\n S_ISVTX = 0x200 # Sticky bit (only owner can delete)\r\n S_ISGID = 0x400 # Set GID (execute with privileges of group owner of the file's group)\r\n S_ISUID = 0x800 # Set UID (execute with privileges of the file's owner)\r\n S_IFIFO = 0x1000 # FIFO device (named pipe)\r\n S_IFCHR = 0x2000 # Character device (raw, unbuffered, aligned, direct access to hardware storage)\r\n S_IFDIR = 0x4000 # Directory\r\n S_IFBLK = 0x6000 # Block device (buffered, arbitrary access to storage)\r\n S_IFREG = 0x8000 # Regular file\r\n S_IFLNK = 0xA000 # Symbolic link\r\n S_IFSOCK = 0xC000 # Socket\r\n\r\n # i_flags\r\n EXT4_INDEX_FL = 0x1000 # Uses hash trees\r\n EXT4_EXTENTS_FL = 0x80000 # Uses extents\r\n EXT4_EA_INODE_FL = 0x200000 # Inode stores large xattr\r\n EXT4_INLINE_DATA_FL = 0x10000000 # Has inline data\r\n\r\n _fields_ = [\r\n (\"i_mode\", ctypes.c_ushort), # 0x0000\r\n (\"i_uid_lo\", ctypes.c_ushort), # 0x0002, Originally named i_uid\r\n (\"i_size_lo\", ctypes.c_uint), # 0x0004\r\n (\"i_atime\", ctypes.c_uint), # 0x0008\r\n (\"i_ctime\", ctypes.c_uint), # 0x000C\r\n (\"i_mtime\", ctypes.c_uint), # 0x0010\r\n (\"i_dtime\", ctypes.c_uint), # 0x0014\r\n (\"i_gid_lo\", ctypes.c_ushort), # 0x0018, Originally named i_gid\r\n (\"i_links_count\", ctypes.c_ushort), # 0x001A\r\n (\"i_blocks_lo\", ctypes.c_uint), # 0x001C\r\n (\"i_flags\", ctypes.c_uint), # 0x0020\r\n (\"osd1\", ctypes.c_uint), # 0x0024\r\n (\"i_block\", ctypes.c_uint * 15), # 0x0028\r\n (\"i_generation\", ctypes.c_uint), # 0x0064\r\n (\"i_file_acl_lo\", ctypes.c_uint), # 0x0068\r\n (\"i_size_hi\", ctypes.c_uint), # 0x006C, Originally named i_size_high\r\n (\"i_obso_faddr\", ctypes.c_uint), # 0x0070\r\n (\"i_osd2_blocks_high\", ctypes.c_ushort), # 0x0074, Originally named i_osd2.linux2.l_i_blocks_high\r\n (\"i_file_acl_hi\", ctypes.c_ushort), # 0x0076, Originally named i_osd2.linux2.l_i_file_acl_high\r\n (\"i_uid_hi\", ctypes.c_ushort), # 0x0078, Originally named i_osd2.linux2.l_i_uid_high\r\n (\"i_gid_hi\", ctypes.c_ushort), # 0x007A, Originally named i_osd2.linux2.l_i_gid_high\r\n (\"i_osd2_checksum_lo\", ctypes.c_ushort), # 0x007C, Originally named i_osd2.linux2.l_i_checksum_lo\r\n (\"i_osd2_reserved\", ctypes.c_ushort), # 0x007E, Originally named i_osd2.linux2.l_i_reserved\r\n (\"i_extra_isize\", ctypes.c_ushort), # 0x0080\r\n (\"i_checksum_hi\", ctypes.c_ushort), # 0x0082\r\n (\"i_ctime_extra\", ctypes.c_uint), # 0x0084\r\n (\"i_mtime_extra\", ctypes.c_uint), # 0x0088\r\n (\"i_atime_extra\", ctypes.c_uint), # 0x008C\r\n (\"i_crtime\", ctypes.c_uint), # 0x0090\r\n (\"i_crtime_extra\", ctypes.c_uint), # 0x0094\r\n (\"i_version_hi\", ctypes.c_uint), # 0x0098\r\n (\"i_projid\", ctypes.c_uint), # 0x009C\r\n ]\r\n\r\n\r\n\r\nclass ext4_superblock (ext4_struct):\r\n EXT2_DESC_SIZE = 0x20 # Default value for s_desc_size, if INCOMPAT_64BIT is not set (NEEDS CONFIRMATION)\r\n\r\n # s_feature_incompat\r\n INCOMPAT_64BIT = 0x80 # Uses 64-bit features (e.g. *_hi structure fields in ext4_group_descriptor)\r\n INCOMPAT_FILETYPE = 0x2 # Directory entries record file type (instead of inode flags)\r\n _fields_ = [\r\n (\"s_inodes_count\", ctypes.c_uint), # 0x0000\r\n (\"s_blocks_count_lo\", ctypes.c_uint), # 0x0004\r\n (\"s_r_blocks_count_lo\", ctypes.c_uint), # 0x0008\r\n (\"s_free_blocks_count_lo\", ctypes.c_uint), # 0x000C\r\n (\"s_free_inodes_count\", ctypes.c_uint), # 0x0010\r\n (\"s_first_data_block\", ctypes.c_uint), # 0x0014\r\n (\"s_log_block_size\", ctypes.c_uint), # 0x0018\r\n (\"s_log_cluster_size\", ctypes.c_uint), # 0x001C\r\n (\"s_blocks_per_group\", ctypes.c_uint), # 0x0020\r\n (\"s_clusters_per_group\", ctypes.c_uint), # 0x0024\r\n (\"s_inodes_per_group\", ctypes.c_uint), # 0x0028\r\n (\"s_mtime\", ctypes.c_uint), # 0x002C\r\n (\"s_wtime\", ctypes.c_uint), # 0x0030\r\n (\"s_mnt_count\", ctypes.c_ushort), # 0x0034\r\n (\"s_max_mnt_count\", ctypes.c_ushort), # 0x0036\r\n (\"s_magic\", ctypes.c_ushort), # 0x0038, Must be 0xEF53\r\n (\"s_state\", ctypes.c_ushort), # 0x003A\r\n (\"s_errors\", ctypes.c_ushort), # 0x003C\r\n (\"s_minor_rev_level\", ctypes.c_ushort), # 0x003E\r\n (\"s_lastcheck\", ctypes.c_uint), # 0x0040\r\n (\"s_checkinterval\", ctypes.c_uint), # 0x0044\r\n (\"s_creator_os\", ctypes.c_uint), # 0x0048\r\n (\"s_rev_level\", ctypes.c_uint), # 0x004C\r\n (\"s_def_resuid\", ctypes.c_ushort), # 0x0050\r\n (\"s_def_resgid\", ctypes.c_ushort), # 0x0052\r\n (\"s_first_ino\", ctypes.c_uint), # 0x0054\r\n (\"s_inode_size\", ctypes.c_ushort), # 0x0058\r\n (\"s_block_group_nr\", ctypes.c_ushort), # 0x005A\r\n (\"s_feature_compat\", ctypes.c_uint), # 0x005C\r\n (\"s_feature_incompat\", ctypes.c_uint), # 0x0060\r\n (\"s_feature_ro_compat\", ctypes.c_uint), # 0x0064\r\n (\"s_uuid\", ctypes.c_ubyte * 16), # 0x0068\r\n (\"s_volume_name\", ctypes.c_char * 16), # 0x0078\r\n (\"s_last_mounted\", ctypes.c_char * 64), # 0x0088\r\n (\"s_algorithm_usage_bitmap\", ctypes.c_uint), # 0x00C8\r\n (\"s_prealloc_blocks\", ctypes.c_ubyte), # 0x00CC\r\n (\"s_prealloc_dir_blocks\", ctypes.c_ubyte), # 0x00CD\r\n (\"s_reserved_gdt_blocks\", ctypes.c_ushort), # 0x00CE\r\n (\"s_journal_uuid\", ctypes.c_ubyte * 16), # 0x00D0\r\n (\"s_journal_inum\", ctypes.c_uint), # 0x00E0\r\n (\"s_journal_dev\", ctypes.c_uint), # 0x00E4\r\n (\"s_last_orphan\", ctypes.c_uint), # 0x00E8\r\n (\"s_hash_seed\", ctypes.c_uint * 4), # 0x00EC\r\n (\"s_def_hash_version\", ctypes.c_ubyte), # 0x00FC\r\n (\"s_jnl_backup_type\", ctypes.c_ubyte), # 0x00FD\r\n (\"s_desc_size\", ctypes.c_ushort), # 0x00FE\r\n (\"s_default_mount_opts\", ctypes.c_uint), # 0x0100\r\n (\"s_first_meta_bg\", ctypes.c_uint), # 0x0104\r\n (\"s_mkfs_time\", ctypes.c_uint), # 0x0108\r\n (\"s_jnl_blocks\", ctypes.c_uint * 17), # 0x010C\r\n\r\n # 64-bit fields\r\n (\"s_blocks_count_hi\", ctypes.c_uint), # 0x0150\r\n (\"s_r_blocks_count_hi\", ctypes.c_uint), # 0x0154\r\n (\"s_free_blocks_count_hi\", ctypes.c_uint), # 0x0158\r\n (\"s_min_extra_isize\", ctypes.c_ushort), # 0x015C\r\n (\"s_want_extra_isize\", ctypes.c_ushort), # 0x015E\r\n (\"s_flags\", ctypes.c_uint), # 0x0160\r\n (\"s_raid_stride\", ctypes.c_ushort), # 0x0164\r\n (\"s_mmp_interval\", ctypes.c_ushort), # 0x0166\r\n (\"s_mmp_block\", ctypes.c_ulonglong), # 0x0168\r\n (\"s_raid_stripe_width\", ctypes.c_uint), # 0x0170\r\n (\"s_log_groups_per_flex\", ctypes.c_ubyte), # 0x0174\r\n (\"s_checksum_type\", ctypes.c_ubyte), # 0x0175\r\n (\"s_reserved_pad\", ctypes.c_ushort), # 0x0176\r\n (\"s_kbytes_written\", ctypes.c_ulonglong), # 0x0178\r\n (\"s_snapshot_inum\", ctypes.c_uint), # 0x0180\r\n (\"s_snapshot_id\", ctypes.c_uint), # 0x0184\r\n (\"s_snapshot_r_blocks_count\", ctypes.c_ulonglong), # 0x0188\r\n (\"s_snapshot_list\", ctypes.c_uint), # 0x0190\r\n (\"s_error_count\", ctypes.c_uint), # 0x0194\r\n (\"s_first_error_time\", ctypes.c_uint), # 0x0198\r\n (\"s_first_error_ino\", ctypes.c_uint), # 0x019C\r\n (\"s_first_error_block\", ctypes.c_ulonglong), # 0x01A0\r\n (\"s_first_error_func\", ctypes.c_ubyte * 32), # 0x01A8\r\n (\"s_first_error_line\", ctypes.c_uint), # 0x01C8\r\n (\"s_last_error_time\", ctypes.c_uint), # 0x01CC\r\n (\"s_last_error_ino\", ctypes.c_uint), # 0x01D0\r\n (\"s_last_error_line\", ctypes.c_uint), # 0x01D4\r\n (\"s_last_error_block\", ctypes.c_ulonglong), # 0x01D8\r\n (\"s_last_error_func\", ctypes.c_ubyte * 32), # 0x01E0\r\n (\"s_mount_opts\", ctypes.c_ubyte * 64), # 0x0200\r\n (\"s_usr_quota_inum\", ctypes.c_uint), # 0x0240\r\n (\"s_grp_quota_inum\", ctypes.c_uint), # 0x0244\r\n (\"s_overhead_blocks\", ctypes.c_uint), # 0x0248\r\n (\"s_backup_bgs\", ctypes.c_uint * 2), # 0x024C\r\n (\"s_encrypt_algos\", ctypes.c_ubyte * 4), # 0x0254\r\n (\"s_encrypt_pw_salt\", ctypes.c_ubyte * 16), # 0x0258\r\n (\"s_lpf_ino\", ctypes.c_uint), # 0x0268\r\n (\"s_prj_quota_inum\", ctypes.c_uint), # 0x026C\r\n (\"s_checksum_seed\", ctypes.c_uint), # 0x0270\r\n (\"s_reserved\", ctypes.c_uint * 98), # 0x0274\r\n (\"s_checksum\", ctypes.c_uint) # 0x03FC\r\n ]\r\n\r\n def _from_buffer_copy (raw, platform64 = True):\r\n struct = ext4_superblock.from_buffer_copy(raw)\r\n\r\n if not platform64:\r\n struct.s_blocks_count_hi = 0\r\n struct.s_r_blocks_count_hi = 0\r\n struct.s_free_blocks_count_hi = 0\r\n struct.s_min_extra_isize = 0\r\n struct.s_want_extra_isize = 0\r\n struct.s_flags = 0\r\n struct.s_raid_stride = 0\r\n struct.s_mmp_interval = 0\r\n struct.s_mmp_block = 0\r\n struct.s_raid_stripe_width = 0\r\n struct.s_log_groups_per_flex = 0\r\n struct.s_checksum_type = 0\r\n struct.s_reserved_pad = 0\r\n struct.s_kbytes_written = 0\r\n struct.s_snapshot_inum = 0\r\n struct.s_snapshot_id = 0\r\n struct.s_snapshot_r_blocks_count = 0\r\n struct.s_snapshot_list = 0\r\n struct.s_error_count = 0\r\n struct.s_first_error_time = 0\r\n struct.s_first_error_ino = 0\r\n struct.s_first_error_block = 0\r\n struct.s_first_error_func = 0\r\n struct.s_first_error_line = 0\r\n struct.s_last_error_time = 0\r\n struct.s_last_error_ino = 0\r\n struct.s_last_error_line = 0\r\n struct.s_last_error_block = 0\r\n struct.s_last_error_func = 0\r\n struct.s_mount_opts = 0\r\n struct.s_usr_quota_inum = 0\r\n struct.s_grp_quota_inum = 0\r\n struct.s_overhead_blocks = 0\r\n struct.s_backup_bgs = 0\r\n struct.s_encrypt_algos = 0\r\n struct.s_encrypt_pw_salt = 0\r\n struct.s_lpf_ino = 0\r\n struct.s_prj_quota_inum = 0\r\n struct.s_checksum_seed = 0\r\n struct.s_reserved = 0\r\n struct.s_checksum = 0\r\n\r\n if (struct.s_feature_incompat & ext4_superblock.INCOMPAT_64BIT) == 0:\r\n struct.s_desc_size = ext4_superblock.EXT2_DESC_SIZE\r\n\r\n return struct\r\n\r\n\r\n\r\nclass ext4_xattr_entry (ext4_struct):\r\n _fields_ = [\r\n (\"e_name_len\", ctypes.c_ubyte), # 0x00\r\n (\"e_name_index\", ctypes.c_ubyte), # 0x01\r\n (\"e_value_offs\", ctypes.c_ushort), # 0x02\r\n (\"e_value_inum\", ctypes.c_uint), # 0x04\r\n (\"e_value_size\", ctypes.c_uint), # 0x08\r\n (\"e_hash\", ctypes.c_uint) # 0x0C\r\n # Variable length field \"e_name\" missing at 0x10\r\n ]\r\n\r\n def _from_buffer_copy (raw, offset = 0, platform64 = True):\r\n struct = ext4_xattr_entry.from_buffer_copy(raw, offset)\r\n struct.e_name = raw[offset + 0x10 : offset + 0x10 + struct.e_name_len]\r\n return struct\r\n\r\n @property\r\n def _size (self): return 4 * ((ctypes.sizeof(type(self)) + self.e_name_len + 3) // 4) # 4-byte alignment\r\n\r\n\r\n\r\nclass ext4_xattr_header (ext4_struct):\r\n _fields_ = [\r\n (\"h_magic\", ctypes.c_uint), # 0x0, Must be 0xEA020000\r\n (\"h_refcount\", ctypes.c_uint), # 0x4\r\n (\"h_blocks\", ctypes.c_uint), # 0x8\r\n (\"h_hash\", ctypes.c_uint), # 0xC\r\n (\"h_checksum\", ctypes.c_uint), # 0x10\r\n (\"h_reserved\", ctypes.c_uint * 3), # 0x14\r\n ]\r\n\r\n\r\n\r\nclass ext4_xattr_ibody_header (ext4_struct):\r\n _fields_ = [\r\n (\"h_magic\", ctypes.c_uint) # 0x0, Must be 0xEA020000\r\n ]\r\n\r\n\r\n\r\nclass InodeType:\r\n UNKNOWN = 0x0 # Unknown file type\r\n FILE = 0x1 # Regular file\r\n DIRECTORY = 0x2 # Directory\r\n CHARACTER_DEVICE = 0x3 # Character device\r\n BLOCK_DEVICE = 0x4 # Block device\r\n FIFO = 0x5 # FIFO\r\n SOCKET = 0x6 # Socket\r\n SYMBOLIC_LINK = 0x7 # Symbolic link\r\n CHECKSUM = 0xDE # Checksum entry; not really a file type, but a type of directory entry\r\n\r\n\r\n\r\n########################################################################################################################\r\n#################################################### HIGH LEVEL ####################################################\r\n########################################################################################################################\r\n\r\nclass MappingEntry:\r\n \"\"\"\r\n Helper class: This class maps block_count file blocks indexed by file_block_idx to the associated disk blocks indexed\r\n by disk_block_idx.\r\n \"\"\"\r\n def __init__ (self, file_block_idx, disk_block_idx, block_count = 1):\r\n \"\"\"\r\n Initialize a MappingEntry instance with given file_block_idx, disk_block_idx and block_count.\r\n \"\"\"\r\n self.file_block_idx = file_block_idx\r\n self.disk_block_idx = disk_block_idx\r\n self.block_count = block_count\r\n\r\n def __iter__ (self):\r\n \"\"\"\r\n Can be used to convert an MappingEntry into a tuple (file_block_idx, disk_block_idx, block_count).\r\n \"\"\"\r\n yield self.file_block_idx\r\n yield self.disk_block_idx\r\n yield self.block_count\r\n\r\n def __repr__ (self):\r\n return f\"{type(self).__name__:s}({self.file_block_idx!r:s}, {self.disk_block_idx!r:s}, {self.block_count!r:s})\"\r\n\r\n def copy (self):\r\n return MappingEntry(self.file_block_idx, self.disk_block_idx, self.block_count)\r\n\r\n def create_mapping (*entries):\r\n \"\"\"\r\n Converts a list of 2-tuples (disk_block_idx, block_count) into a list of MappingEntry instances\r\n \"\"\"\r\n file_block_idx = 0\r\n result = [None] * len(entries)\r\n\r\n for i, entry in enumerate(entries):\r\n disk_block_idx, block_count = entry\r\n result[i] = MappingEntry(file_block_idx, disk_block_idx, block_count)\r\n file_block_idx += block_count\r\n\r\n return result\r\n\r\n def optimize (entries):\r\n \"\"\"\r\n Sorts and stiches together a list of MappingEntry instances\r\n \"\"\"\r\n entries.sort(key = lambda entry: entry.file_block_idx)\r\n\r\n idx = 0\r\n while idx < len(entries):\r\n while idx + 1 < len(entries) \\\r\n and entries[idx].file_block_idx + entries[idx].block_count == entries[idx + 1].file_block_idx \\\r\n and entries[idx].disk_block_idx + entries[idx].block_count == entries[idx + 1].disk_block_idx:\r\n tmp = entries.pop(idx + 1)\r\n entries[idx].block_count += tmp.block_count\r\n\r\n idx += 1\r\n\r\n# None of the following classes preserve the underlying stream's current seek.\r\n\r\nclass Volume:\r\n \"\"\"\r\n Provides functionality for reading ext4 volumes\r\n \"\"\"\r\n\r\n ROOT_INODE = 2\r\n\r\n def __init__ (self, stream, offset = 0, ignore_flags = False, ignore_magic = False):\r\n \"\"\"\r\n Initializes a new ext4 reader at a given offset in stream. If ignore_magic is True, no exception will be thrown,\r\n when a structure with wrong magic number is found. Analogously passing True to ignore_flags suppresses Exception\r\n caused by wrong flags.\r\n \"\"\"\r\n self.ignore_flags = ignore_flags\r\n self.ignore_magic = ignore_magic\r\n self.offset = offset\r\n self.platform64 = True # Initial value needed for Volume.read_struct\r\n self.stream = stream\r\n\r\n # Superblock\r\n self.superblock = self.read_struct(ext4_superblock, 0x400)\r\n self.platform64 = (self.superblock.s_feature_incompat & ext4_superblock.INCOMPAT_64BIT) != 0\r\n\r\n if not ignore_magic and self.superblock.s_magic != 0xEF53:\r\n raise MagicError(f\"Invalid magic value in superblock: 0x{self.superblock.s_magic:04X} (expected 0xEF53)\")\r\n\r\n # Group descriptors\r\n self.group_descriptors = [None] * (self.superblock.s_inodes_count // self.superblock.s_inodes_per_group)\r\n\r\n group_desc_table_offset = (0x400 // self.block_size + 1) * self.block_size # First block after superblock\r\n for group_desc_idx in range(len(self.group_descriptors)):\r\n group_desc_offset = group_desc_table_offset + group_desc_idx * self.superblock.s_desc_size\r\n self.group_descriptors[group_desc_idx] = self.read_struct(ext4_group_descriptor, group_desc_offset)\r\n\r\n def __repr__ (self):\r\n return f\"{type(self).__name__:s}(volume_name = {self.superblock.s_volume_name!r:s}, uuid = {self.uuid!r:s}, last_mounted = {self.superblock.s_last_mounted!r:s})\"\r\n\r\n @property\r\n def block_size (self):\r\n \"\"\"\r\n Returns the volume's block size in bytes.\r\n \"\"\"\r\n return 1 << (10 + self.superblock.s_log_block_size)\r\n\r\n def get_inode (self, inode_idx, file_type = InodeType.UNKNOWN):\r\n \"\"\"\r\n Returns an Inode instance representing the inode specified by its index inode_idx.\r\n \"\"\"\r\n group_idx, inode_table_entry_idx = self.get_inode_group(inode_idx)\r\n\r\n inode_table_offset = self.group_descriptors[group_idx].bg_inode_table * self.block_size\r\n inode_offset = inode_table_offset + inode_table_entry_idx * self.superblock.s_inode_size\r\n\r\n return Inode(self, inode_offset, inode_idx, file_type)\r\n\r\n def get_inode_group (self, inode_idx):\r\n \"\"\"\r\n Returns a tuple (group_idx, inode_table_entry_idx)\r\n \"\"\"\r\n group_idx = (inode_idx - 1) // self.superblock.s_inodes_per_group\r\n inode_table_entry_idx = (inode_idx - 1) % self.superblock.s_inodes_per_group\r\n return (group_idx, inode_table_entry_idx)\r\n\r\n def read (self, offset, byte_len):\r\n \"\"\"\r\n Returns byte_len bytes at offset within this volume.\r\n \"\"\"\r\n if self.offset + offset != self.stream.tell():\r\n self.stream.seek(self.offset + offset, io.SEEK_SET)\r\n\r\n return self.stream.read(byte_len)\r\n\r\n def read_struct (self, structure, offset, platform64 = None):\r\n \"\"\"\r\n Interprets the bytes at offset as structure and returns the interpreted instance\r\n \"\"\"\r\n raw = self.read(offset, ctypes.sizeof(structure))\r\n\r\n if hasattr(structure, \"_from_buffer_copy\"):\r\n return structure._from_buffer_copy(raw, platform64 = platform64 if platform64 != None else self.platform64)\r\n else:\r\n return structure.from_buffer_copy(raw)\r\n\r\n @property\r\n def root (self):\r\n \"\"\"\r\n Returns the volume's root inode\r\n \"\"\"\r\n return self.get_inode(Volume.ROOT_INODE, InodeType.DIRECTORY)\r\n\r\n @property\r\n def uuid (self):\r\n \"\"\"\r\n Returns the volume's UUID in the format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX.\r\n \"\"\"\r\n uuid = self.superblock.s_uuid\r\n uuid = [uuid[:4], uuid[4 : 6], uuid[6 : 8], uuid[8 : 10], uuid[10:]]\r\n return \"-\".join(\"\".join(f\"{c:02X}\" for c in part) for part in uuid)\r\n\r\n\r\n\r\nclass Inode:\r\n \"\"\"\r\n Provides functionality for parsing inodes and accessing their raw data\r\n \"\"\"\r\n\r\n def __init__ (self, volume, offset, inode_idx, file_type = InodeType.UNKNOWN):\r\n \"\"\"\r\n Initializes a new inode parser at the specified offset within the specified volume. file_type is the file type\r\n of the inode as given by the directory entry referring to this inode.\r\n \"\"\"\r\n self.inode_idx = inode_idx\r\n self.offset = offset\r\n self.volume = volume\r\n\r\n self.file_type = file_type\r\n self.inode = volume.read_struct(ext4_inode, offset)\r\n\r\n def __len__ (self):\r\n \"\"\"\r\n Returns the length in bytes of the content referenced by this inode.\r\n \"\"\"\r\n return self.inode.i_size\r\n\r\n def __repr__ (self):\r\n if self.inode_idx != None:\r\n return f\"{type(self).__name__:s}(inode_idx = {self.inode_idx!r:s}, offset = 0x{self.offset:X}, volume_uuid = {self.volume.uuid!r:s})\"\r\n else:\r\n return f\"{type(self).__name__:s}(offset = 0x{self.offset:X}, volume_uuid = {self.volume.uuid!r:s})\"\r\n\r\n def _parse_xattrs (self, raw_data, offset, prefix_override = {}):\r\n \"\"\"\r\n Generator: Parses raw_data (bytes) as ext4_xattr_entry structures and their referenced xattr values and yields\r\n tuples (xattr_name, xattr_value) where xattr_name (str) is the attribute name including its prefix and\r\n xattr_value (bytes) is the raw attribute value.\r\n raw_data must start with the first ext4_xattr_entry structure and offset specifies the offset to the \"block start\"\r\n for ext4_xattr_entry.e_value_offs.\r\n prefix_overrides allows specifying attributes apart from the default prefixes. The default prefix dictionary is\r\n updated with prefix_overrides.\r\n \"\"\"\r\n prefixes = {\r\n 0: \"\",\r\n 1: \"user.\",\r\n 2: \"system.posix_acl_access\",\r\n 3: \"system.posix_acl_default\",\r\n 4: \"trusted.\",\r\n 6: \"security.\",\r\n 7: \"system.\",\r\n 8: \"system.richacl\"\r\n }\r\n prefixes.update(prefixes)\r\n\r\n # Iterator over ext4_xattr_entry structures\r\n i = 0\r\n while i < len(raw_data):\r\n xattr_entry = ext4_xattr_entry._from_buffer_copy(raw_data, i, platform64 = self.volume.platform64)\r\n\r\n if (xattr_entry.e_name_len | xattr_entry.e_name_index | xattr_entry.e_value_offs | xattr_entry.e_value_inum) == 0:\r\n # End of ext4_xattr_entry list\r\n break\r\n\r\n if not xattr_entry.e_name_index in prefixes:\r\n raise Ext4Error(f\"Unknown attribute prefix {xattr_entry.e_name_index:d} in inode {self.inode_idx:d}\")\r\n\r\n xattr_name = prefixes[xattr_entry.e_name_index] + xattr_entry.e_name.decode(\"iso-8859-2\")\r\n\r\n if xattr_entry.e_value_inum != 0:\r\n # external xattr\r\n xattr_inode = self.volume.get_inode(xattr.e_value_inum, InodeType.FILE)\r\n\r\n if not self.volume.ignore_flags and (xattr_inode.inode.i_flags & ext4_inode.EXT4_EA_INODE_FL) != 0:\r\n raise Ext4Error(f\"Inode {xattr_inode.inode_idx:d} associated with the extended attribute {xattr_name!r:s} of inode {self.inode_idx:d} is not marked as large extended attribute value.\")\r\n\r\n # TODO Use xattr_entry.e_value_size or xattr_inode.inode.i_size?\r\n xattr_value = xattr_inode.open_read().read()\r\n else:\r\n # internal xattr\r\n xattr_value = raw_data[xattr_entry.e_value_offs + offset : xattr_entry.e_value_offs + offset + xattr_entry.e_value_size]\r\n\r\n yield (xattr_name, xattr_value)\r\n\r\n i += xattr_entry._size\r\n\r\n\r\n\r\n def directory_entry_comparator (dir_a, dir_b):\r\n \"\"\"\r\n Sort-key for directory entries. It sortes entries in a way that directories come before anything else and within\r\n a group (directory / anything else) entries are sorted by their lower-case name. Entries whose lower-case names\r\n are equal are sorted by their actual names.\r\n \"\"\"\r\n file_name_a, _, file_type_a = dir_a\r\n file_name_b, _, file_type_b = dir_b\r\n\r\n if file_type_a == InodeType.DIRECTORY == file_type_b or file_type_a != InodeType.DIRECTORY != file_type_b:\r\n tmp = wcscmp(file_name_a.lower(), file_name_b.lower())\r\n return tmp if tmp != 0 else wcscmp(file_name_a, file_name_b)\r\n else:\r\n return -1 if file_type_a == InodeType.DIRECTORY else 1\r\n\r\n directory_entry_key = functools.cmp_to_key(directory_entry_comparator)\r\n\r\n def get_inode (self, *relative_path, decode_name = None):\r\n \"\"\"\r\n Returns the inode specified by the path relative_path (list of entry names) relative to this inode. \".\" and \"..\"\r\n usually are supported too, however in special cases (e.g. manually crafted volumes) they might not be supported\r\n due to them being real on-disk directory entries that might be missing or pointing somewhere else.\r\n decode_name is directly passed to open_dir.\r\n NOTE: Whitespaces will not be trimmed off the path's parts and \"\\\\0\" and \"\\\\0\\\\0\" as well as b\"\\\\0\" and b\"\\\\0\\\\0\" are\r\n seen as different names (unless decode_name actually trims the name).\r\n NOTE: Along the path file_type != FILETYPE_DIR will be ignored, however i_flags will not be ignored.\r\n \"\"\"\r\n if not self.is_dir:\r\n raise Ext4Error(f\"Inode {self.inode_idx:d} is not a directory.\")\r\n\r\n current_inode = self\r\n\r\n for i, part in enumerate(relative_path):\r\n if not self.volume.ignore_flags and not current_inode.is_dir:\r\n current_path = \"/\".join(relative_path[:i])\r\n raise Ext4Error(f\"{current_path!r:s} (Inode {inode_idx:d}) is not a directory.\")\r\n\r\n file_name, inode_idx, file_type = next(filter(lambda entry: entry[0] == part, current_inode.open_dir(decode_name)), (None, None, None))\r\n\r\n if inode_idx == None:\r\n current_path = \"/\".join(relative_path[:i])\r\n raise FileNotFoundError(f\"{part!r:s} not found in {current_path!r:s} (Inode {current_inode.inode_idx:d}).\")\r\n\r\n current_inode = current_inode.volume.get_inode(inode_idx, file_type)\r\n\r\n\r\n return current_inode\r\n\r\n @property\r\n def is_dir (self):\r\n \"\"\"\r\n Indicates whether the inode is marked as a directory.\r\n \"\"\"\r\n if (self.volume.superblock.s_feature_incompat & ext4_superblock.INCOMPAT_FILETYPE) == 0:\r\n return (self.inode.i_mode & ext4_inode.S_IFDIR) != 0\r\n else:\r\n return self.file_type == InodeType.DIRECTORY\r\n\r\n @property\r\n def is_file (self):\r\n \"\"\"\r\n Indicates whether the inode is marker as a regular file.\r\n \"\"\"\r\n if (self.volume.superblock.s_feature_incompat & ext4_dir_entry_2.INCOMPAT_FILETYPE) == 0:\r\n return (self.inode.i_mode & ext4_inode.S_IFREG) != 0\r\n else:\r\n return self.file_type == InodeType.FILE\r\n\r\n @property\r\n def is_in_use (self):\r\n \"\"\"\r\n Indicates whether the inode's associated bit in the inode bitmap is set.\r\n \"\"\"\r\n group_idx, bitmap_bit = self.volume.get_inode_group(self.inode_idx)\r\n\r\n inode_usage_bitmap_offset = self.volume.group_descriptors[group_idx].bg_inode_bitmap * self.volume.block_size\r\n inode_usage_byte = self.volume.read(inode_usage_bitmap_offset + bitmap_bit // 8, 1)[0]\r\n\r\n return ((inode_usage_byte >> (7 - bitmap_bit % 8)) & 1) != 0\r\n\r\n @property\r\n def mode_str (self):\r\n \"\"\"\r\n Returns the inode's permissions in form of a unix string (e.g. \"-rwxrw-rw\" or \"drwxr-xr--\").\r\n \"\"\"\r\n special_flag = lambda letter, execute, special: {\r\n (False, False): \"-\",\r\n (False, True): letter.upper(),\r\n (True, False): \"x\",\r\n (True, True): letter.lower()\r\n }[(execute, special)]\r\n\r\n try:\r\n if (self.volume.superblock.s_feature_incompat & ext4_superblock.INCOMPAT_FILETYPE) == 0:\r\n device_type = {\r\n ext4_inode.S_IFIFO : \"p\",\r\n ext4_inode.S_IFCHR : \"c\",\r\n ext4_inode.S_IFDIR : \"d\",\r\n ext4_inode.S_IFBLK : \"b\",\r\n ext4_inode.S_IFREG : \"-\",\r\n ext4_inode.S_IFLNK : \"l\",\r\n ext4_inode.S_IFSOCK : \"s\",\r\n }[self.inode.i_mode & 0xF000]\r\n else:\r\n device_type = {\r\n InodeType.FILE : \"-\",\r\n InodeType.DIRECTORY : \"d\",\r\n InodeType.CHARACTER_DEVICE : \"c\",\r\n InodeType.BLOCK_DEVICE : \"b\",\r\n InodeType.FIFO : \"p\",\r\n InodeType.SOCKET : \"s\",\r\n InodeType.SYMBOLIC_LINK : \"l\"\r\n }[self.file_type]\r\n except KeyError:\r\n device_type = \"?\"\r\n\r\n return \"\".join([\r\n device_type,\r\n\r\n \"r\" if (self.inode.i_mode & ext4_inode.S_IRUSR) != 0 else \"-\",\r\n \"w\" if (self.inode.i_mode & ext4_inode.S_IWUSR) != 0 else \"-\",\r\n special_flag(\"s\", (self.inode.i_mode & ext4_inode.S_IXUSR) != 0, (self.inode.i_mode & ext4_inode.S_ISUID) != 0),\r\n\r\n \"r\" if (self.inode.i_mode & ext4_inode.S_IRGRP) != 0 else \"-\",\r\n \"w\" if (self.inode.i_mode & ext4_inode.S_IWGRP) != 0 else \"-\",\r\n special_flag(\"s\", (self.inode.i_mode & ext4_inode.S_IXGRP) != 0, (self.inode.i_mode & ext4_inode.S_ISGID) != 0),\r\n\r\n \"r\" if (self.inode.i_mode & ext4_inode.S_IROTH) != 0 else \"-\",\r\n \"w\" if (self.inode.i_mode & ext4_inode.S_IWOTH) != 0 else \"-\",\r\n special_flag(\"t\", (self.inode.i_mode & ext4_inode.S_IXOTH) != 0, (self.inode.i_mode & ext4_inode.S_ISVTX) != 0),\r\n ])\r\n\r\n def open_dir (self, decode_name = None):\r\n \"\"\"\r\n Generator: Yields the directory entries as tuples (decode_name(name), inode, file_type) in their on-disk order,\r\n where name is the raw on-disk directory entry name (bytes). file_type is one of the Inode.IT_* constants. For\r\n special cases (e.g. invalid utf8 characters in entry names) you can try a different decoder (e.g.\r\n decode_name = lambda raw: raw).\r\n Default of decode_name = lambda raw: raw.decode(\"utf8\")\r\n \"\"\"\r\n # Parse args\r\n if decode_name == None:\r\n decode_name = lambda raw: raw.decode(\"utf8\")\r\n\r\n if not self.volume.ignore_flags and not self.is_dir:\r\n raise Ext4Error(f\"Inode ({self.inode_idx:d}) is not a directory.\")\r\n\r\n # # Hash trees are compatible with linear arrays\r\n if (self.inode.i_flags & ext4_inode.EXT4_INDEX_FL) != 0:\r\n raise NotImplementedError(\"Hash trees are not implemented yet.\")\r\n\r\n # Read raw directory content\r\n raw_data = self.open_read().read()\r\n offset = 0\r\n\r\n while offset < len(raw_data):\r\n dirent = ext4_dir_entry_2._from_buffer_copy(raw_data, offset, platform64 = self.volume.platform64)\r\n\r\n if dirent.file_type != InodeType.CHECKSUM:\r\n yield (decode_name(dirent.name), dirent.inode, dirent.file_type)\r\n\r\n offset += dirent.rec_len\r\n\r\n def open_read (self):\r\n \"\"\"\r\n Returns an BlockReader instance for reading this inode's raw content.\r\n \"\"\"\r\n if (self.inode.i_flags & ext4_inode.EXT4_EXTENTS_FL) != 0:\r\n # Obtain mapping from extents\r\n mapping = [] # List of MappingEntry instances\r\n\r\n nodes = queue.Queue()\r\n nodes.put_nowait(self.offset + ext4_inode.i_block.offset)\r\n\r\n while nodes.qsize() != 0:\r\n header_offset = nodes.get_nowait()\r\n header = self.volume.read_struct(ext4_extent_header, header_offset)\r\n\r\n if not self.volume.ignore_magic and header.eh_magic != 0xF30A:\r\n raise MagicError(f\"Invalid magic value in extent header at offset 0x{header_offset:X} of inode {self.inode_idx:d}: 0x{header.eh_magic:04X} (expected 0xF30A)\")\r\n\r\n if header.eh_depth != 0:\r\n indices = self.volume.read_struct(ext4_extent_idx * header.eh_entries, header_offset + ctypes.sizeof(ext4_extent_header))\r\n for idx in indices: nodes.put_nowait(idx.ei_leaf * self.volume.block_size)\r\n else:\r\n extents = self.volume.read_struct(ext4_extent * header.eh_entries, header_offset + ctypes.sizeof(ext4_extent_header))\r\n for extent in extents:\r\n mapping.append(MappingEntry(extent.ee_block, extent.ee_start, extent.ee_len))\r\n\r\n MappingEntry.optimize(mapping)\r\n return BlockReader(self.volume, len(self), mapping)\r\n else:\r\n # Inode uses inline data\r\n i_block = self.volume.read(self.offset + ext4_inode.i_block.offset, ext4_inode.i_block.size)\r\n return io.BytesIO(i_block[:self.inode.i_size])\r\n\r\n @property\r\n def size_readable (self):\r\n \"\"\"\r\n Returns the inode's content length in a readable format (e.g. \"123 bytes\", \"2.03 KiB\" or \"3.00 GiB\"). Possible\r\n units are bytes, KiB, MiB, GiB, TiB, PiB, EiB, ZiB, YiB.\r\n \"\"\"\r\n if self.inode.i_size < 1024:\r\n return f\"{self.inode.i_size} bytes\" if self.inode.i_size != 1 else \"1 byte\"\r\n else:\r\n units = [\"KiB\", \"MiB\", \"GiB\", \"TiB\", \"PiB\", \"EiB\", \"ZiB\", \"YiB\"]\r\n unit_idx = min(int(math.log(self.inode.i_size, 1024)), len(units))\r\n\r\n return f\"{self.inode.i_size / (1024 ** unit_idx):.2f} {units[unit_idx - 1]:s}\"\r\n\r\n def xattrs (self, check_inline = True, check_block = True, force_inline = False, prefix_override = {}):\r\n \"\"\"\r\n Generator: Yields the inode's extended attributes as tuples (name, value) in their on-disk order, where name (str)\r\n is the on-disk attribute name including its resolved name prefix and value (bytes) is the raw attribute value.\r\n check_inline and check_block control where to read attributes (the inode's inline data and/or the external data block\r\n pointed to by i_file_acl) and if check_inline as well as force_inline are set to True, the inode's inline data\r\n will not be verified to contain actual extended attributes and instead is just interpreted as such. prefix_overrides\r\n is directly passed to Inode._parse_xattrs.\r\n \"\"\"\r\n # Inline xattrs\r\n inline_data_offset = self.offset + ext4_inode.EXT2_GOOD_OLD_INODE_SIZE + self.inode.i_extra_isize\r\n inline_data_length = self.offset + self.volume.superblock.s_inode_size - inline_data_offset\r\n\r\n if check_inline and inline_data_length > ctypes.sizeof(ext4_xattr_ibody_header):\r\n inline_data = self.volume.read(inline_data_offset, inline_data_length)\r\n xattrs_header = ext4_xattr_ibody_header.from_buffer_copy(inline_data)\r\n\r\n # TODO Find way to detect inline xattrs without checking the h_magic field to enable error detection with the h_magic field.\r\n if force_inline or xattrs_header.h_magic == 0xEA020000:\r\n offset = 4 * ((ctypes.sizeof(ext4_xattr_ibody_header) + 3) // 4) # The ext4_xattr_entry following the header is aligned on a 4-byte boundary\r\n for xattr_name, xattr_value in self._parse_xattrs(inline_data[offset:], 0, prefix_override = prefix_override):\r\n yield (xattr_name, xattr_value)\r\n\r\n # xattr block(s)\r\n if check_block and self.inode.i_file_acl != 0:\r\n xattrs_block_start = self.inode.i_file_acl * self.volume.block_size\r\n xattrs_block = self.volume.read(xattrs_block_start, self.volume.block_size)\r\n\r\n xattrs_header = ext4_xattr_header.from_buffer_copy(xattrs_block)\r\n if not self.volume.ignore_magic and xattrs_header.h_magic != 0xEA020000:\r\n raise MagicError(f\"Invalid magic value in xattrs block header at offset 0x{xattrs_block_start:X} of inode {self.inode_idx:d}: 0x{xattrs_header.h_magic} (expected 0xEA020000)\")\r\n\r\n if xattrs_header.h_blocks != 1:\r\n raise Ext4Error(f\"Invalid number of xattr blocks at offset 0x{xattrs_block_start:X} of inode {self.inode_idx:d}: {xattrs_header.h_blocks:d} (expected 1)\")\r\n\r\n offset = 4 * ((ctypes.sizeof(ext4_xattr_header) + 3) // 4) # The ext4_xattr_entry following the header is aligned on a 4-byte boundary\r\n for xattr_name, xattr_value in self._parse_xattrs(xattrs_block[offset:], -offset, prefix_override = prefix_override):\r\n yield (xattr_name, xattr_value)\r\n\r\n\r\n\r\nclass BlockReader:\r\n \"\"\"\r\n Maps disk blocks into a linear byte stream.\r\n NOTE: This class does not implement buffering or caching.\r\n \"\"\"\r\n\r\n # OSError\r\n EINVAL = 22\r\n\r\n def __init__ (self, volume, byte_size, block_map):\r\n \"\"\"\r\n Initializes a new block reader on the specified volume. mapping must be a list of MappingEntry instances. If\r\n you prefer a way to use 2-tuples (disk_block_idx, block_count) with inferred file_block_index entries, see\r\n MappingEntry.create_mapping.\r\n \"\"\"\r\n self.byte_size = byte_size\r\n self.volume = volume\r\n\r\n self.cursor = 0\r\n\r\n block_map = list(map(MappingEntry.copy, block_map))\r\n\r\n # Optimize mapping (stich together)\r\n MappingEntry.optimize(block_map)\r\n self.block_map = block_map\r\n\r\n def __repr__ (self):\r\n return f\"{type(self).__name__:s}(byte_size = {self.byte_size!r:s}, block_map = {self.block_map!r:s}, volume_uuid = {self.volume.uuid!r:s})\"\r\n\r\n def get_block_mapping (self, file_block_idx):\r\n \"\"\"\r\n Returns the disk block index of the file block specified by file_block_idx.\r\n \"\"\"\r\n disk_block_idx = None\r\n\r\n # Find disk block\r\n for entry in self.block_map:\r\n if entry.file_block_idx <= file_block_idx < entry.file_block_idx + entry.block_count:\r\n block_diff = file_block_idx - entry.file_block_idx\r\n disk_block_idx = entry.disk_block_idx + block_diff\r\n break\r\n\r\n return disk_block_idx\r\n\r\n def read (self, byte_len = -1):\r\n \"\"\"\r\n Reades up to byte_len bytes from the block device beginning at the cursor's current position. This operation will\r\n not exceed the inode's size. If -1 is passed for byte_len, the inode is read to the end.\r\n \"\"\"\r\n # Parse args\r\n if byte_len < -1: raise ValueError(\"byte_len must be non-negative or -1\")\r\n\r\n bytes_remaining = self.byte_size - self.cursor\r\n byte_len = bytes_remaining if byte_len == -1 else max(0, min(byte_len, bytes_remaining))\r\n\r\n if byte_len == 0: return b\"\"\r\n\r\n # Reading blocks\r\n start_block_idx = self.cursor // self.volume.block_size\r\n end_block_idx = (self.cursor + byte_len - 1) // self.volume.block_size\r\n end_of_stream_check = byte_len\r\n\r\n blocks = [self.read_block(i) for i in range(start_block_idx, end_block_idx - start_block_idx + 1)]\r\n\r\n start_offset = self.cursor % self.volume.block_size\r\n if start_offset != 0: blocks[0] = blocks[0][start_offset:]\r\n byte_len = (byte_len + start_offset - self.volume.block_size - 1) % self.volume.block_size + 1\r\n blocks[-1] = blocks[-1][:byte_len]\r\n\r\n result = b\"\".join(blocks)\r\n\r\n # Check read\r\n if len(result) != end_of_stream_check:\r\n raise EndOfStreamError(f\"The volume's underlying stream ended {byte_len - len(result):d} bytes before EOF.\")\r\n\r\n self.cursor += len(result)\r\n return result\r\n\r\n def read_block (self, file_block_idx):\r\n \"\"\"\r\n Reads one block from disk (return a zero-block if the file block is not mapped)\r\n \"\"\"\r\n disk_block_idx = self.get_block_mapping(file_block_idx)\r\n\r\n if disk_block_idx != None:\r\n return self.volume.read(disk_block_idx * self.volume.block_size, self.volume.block_size)\r\n else:\r\n return bytes([0] * self.volume.block_size)\r\n\r\n def seek (self, seek, seek_mode = io.SEEK_SET):\r\n \"\"\"\r\n Moves the internal cursor along the file (not the disk) and behaves like BufferedReader.seek\r\n \"\"\"\r\n if seek_mode == io.SEEK_CUR:\r\n seek += self.cursor\r\n elif seek_mode == io.SEEK_END:\r\n seek += self.byte_size\r\n # elif seek_mode == io.SEEK_SET:\r\n # seek += 0\r\n\r\n if seek < 0:\r\n raise OSError(BlockReader.EINVAL, \"Invalid argument\") # Exception behavior copied from IOBase.seek\r\n\r\n self.cursor = seek\r\n return seek\r\n\r\n def tell (self):\r\n \"\"\"\r\n Returns the internal cursor's current file offset.\r\n \"\"\"\r\n return self.cursor\r\n\r\n\r\n\r\nclass Tools:\r\n \"\"\"\r\n Provides helpful utility functions\r\n \"\"\"\r\n\r\n def list_dir (\r\n volume,\r\n identifier,\r\n decode_name = None,\r\n sort_key = Inode.directory_entry_key,\r\n line_format = None,\r\n file_types = {0 : \"unkn\", 1 : \"file\", 2 : \"dir\", 3 : \"chr\", 4 : \"blk\", 5 : \"fifo\", 6 : \"sock\", 7 : \"sym\"}\r\n ):\r\n \"\"\"\r\n Similar to \"ls -la\" this function lists all entries from a directory of volume.\r\n\r\n identifier might be an Inode instance, an integer describing the directory's inode index, a str/bytes describing\r\n the directory's full path or a list of entry names. decode_name is directly passed to open_dir. See Inode.get_inode\r\n for more details.\r\n\r\n sort_key is the key-function used for sorting the directories entries. If None is passed, the call to sorted is\r\n omitted.\r\n\r\n line_format is a format string specifying each line's format or a function formatting each line. It is used as\r\n follows:\r\n\r\n line_format(\r\n file_name = file_name, # Entry name\r\n inode = volume.get_inode(inode_idx, file_type), # Referenced inode\r\n file_type = file_type, # Entry type (int)\r\n file_type_str = file_types[file_type] if file_type in file_types else \"?\" # Entry type (str, see next paragraph)\r\n )\r\n\r\n The default of line_format is the following function:\r\n\r\n def line_format (file_name, inode, file_type, file_type_str):\r\n if file_type == InodeType.SYMBOLIC_LINK:\r\n link_target = inode.open_read().read().decode(\"utf8\")\r\n return f\"{inode.mode_str:s} {inode.size_readable: >10s} {file_name:s} -> {link_target:s}\"\r\n else:\r\n return f\"{inode.mode_str:s} {inode.size_readable: >10s} {file_name:s}\"\r\n\r\n file_types is a dictionary specifying the names of the different entry types.\r\n \"\"\"\r\n # Parse arguments\r\n if isinstance(identifier, Inode):\r\n inode = identifier\r\n elif isinstance(identifier, int):\r\n inode = volume.get_inode(identifier, InodeType.DIRECTORY)\r\n elif isinstance(identifier, str):\r\n identifier = identifier.strip(\" /\").split(\"/\")\r\n\r\n if len(identifier) == 1 and identifier[0] == \"\":\r\n inode = volume.root\r\n else:\r\n inode = volume.root.get_inode(*identifier)\r\n elif isinstance(identifier, list):\r\n inode = volume.root.get_inode(*identifier)\r\n\r\n if line_format == None:\r\n def _line_format (file_name, inode, file_type, file_type_str):\r\n if file_type == InodeType.SYMBOLIC_LINK:\r\n link_target = inode.open_read().read().decode(\"utf8\")\r\n return f\"{inode.mode_str:s} {inode.size_readable: >10s} {file_name:s} -> {link_target:s}\"\r\n else:\r\n return f\"{inode.mode_str:s} {inode.size_readable: >10s} {file_name:s}\"\r\n\r\n line_format = _line_format\r\n elif isinstance(line_format, str):\r\n line_format = line_format.format\r\n\r\n # Print directory\r\n entries = inode.open_dir(decode_name) if sort_key is None else sorted(inode.open_dir(decode_name), key = sort_key)\r\n\r\n for file_name, inode_idx, file_type in entries:\r\n print(line_format(\r\n file_name = file_name,\r\n inode = volume.get_inode(inode_idx, file_type),\r\n file_type = file_type,\r\n file_type_str = file_types[file_type] if file_type in file_types else \"?\"\r\n ))","sub_path":"ext4.py","file_name":"ext4.py","file_ext":"py","file_size_in_byte":52814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"558861621","text":"import hou\nimport husdshadertranslators.utils as utils\nfrom husdshadertranslators.default import DefaultShaderTranslatorHelper, renderContextName, RampParmTranslator\n\nfrom pxr import Usd, UsdShade, Sdf, Vt\n\nfrom itertools import izip\n\n# TODO(pal):\n# - Support putting fetch nodes in the middle of the shader graph.\n# - Investigate animated parameters, especially the ramp.\n# - Filter the extra parameters created on the ramp nodes.\n\n# Arnold shaders have the render mask of VMantra. This would be great to change\n# as mantra and other shader types might share this mask.\nARNOLD_RENDER_MASK = 'VMantra'\nARNOLD_TERMINALS = [hou.shaderType.Surface, hou.shaderType.Displacement, 'volume']\nARNOLD_NODE_PREFIX = 'arnold::'\nARNOLD_USD_PREFIX = 'arnold:'\nARNOLD_FETCH_NAME = 'arnold::fetch'\nARNOLD_RENDER_CONTEXT_NAME = 'arnold'\nARNOLD_RAMP_TYPES = ['arnold::ramp_rgb', 'arnold::ramp_float']\nARNOLD_RAMP_INTERP_REMAP = {\n hou.rampBasis.Constant: 0,\n hou.rampBasis.Linear: 1,\n hou.rampBasis.CatmullRom: 2,\n hou.rampBasis.BSpline: 2,\n hou.rampBasis.MonotoneCubic: 3,\n}\nARNOLD_MATERIAL = 'arnold_material'\nARNOLD_MATERIALBUILDER = 'arnold_materialbuilder'\n\ndef resolve_fetch_vop(node):\n while node.type().name() == ARNOLD_FETCH_NAME:\n if node.isBypassed():\n return None\n node = node.parm('target').evalAsNode()\n if not node:\n return None\n return node\n\ndef find_first_node_of_type(node, node_type):\n for child in node.children():\n child = resolve_fetch_vop(child)\n if child.type().name() == node_type:\n return child\n return None\n\ndef get_shaders_to_translate(shader_node):\n return [(input, terminal) for input, terminal in izip(shader_node.inputs(), ARNOLD_TERMINALS) if input is not None]\n\nclass ArnoldRampParmTranslator(RampParmTranslator):\n \"\"\"\n Translator for Arnold ramp shader params.\n \"\"\"\n\n def createAndSetAttrib(self, usd_shader, time_code):\n \"\"\" Creates an attribute on the usd shader primitive and sets its value\n according to the member node parameter, at the specified time code.\n \"\"\"\n ramp = self.valueFromParm(self.parmTuple(), time_code)[0]\n output_time_code = self.adjustTimeCode(time_code)\n\n position = usd_shader.CreateInput('position', Sdf.ValueTypeNames.FloatArray)\n position.Set(Vt.FloatArray(ramp.keys()), output_time_code)\n\n interpolation = usd_shader.CreateInput('interpolation', Sdf.ValueTypeNames.IntArray)\n interpolation.Set([ARNOLD_RAMP_INTERP_REMAP.get(v, 3) for v in ramp.basis()], output_time_code)\n\n if ramp.isColor():\n value_input = usd_shader.CreateInput('color', Sdf.ValueTypeNames.Color3fArray)\n value = ramp.values()\n else:\n value_input = usd_shader.CreateInput('value', Sdf.ValueTypeNames.FloatArray)\n value = Vt.FloatArray(ramp.values())\n value_input.Set(value, output_time_code)\n\nclass ArnoldShaderHelper(DefaultShaderTranslatorHelper):\n # Just initializing the default shader translator helper.\n def __init__(self, translator_id, usd_stage, usd_material_path, usd_time_code):\n DefaultShaderTranslatorHelper.__init__(self, translator_id, usd_stage, usd_material_path, usd_time_code)\n\n def createShaderPrimID(self, shader_prim, shader_node):\n \"\"\"\n Creates and sets the id parameter on the shader. We are querying the shader_node's type name and removing the\n arnold:: prefix, and setting the id to arnold:\n \"\"\"\n type_name = shader_node.type().name()\n if type_name.startswith(ARNOLD_NODE_PREFIX):\n shader_name = type_name[len(ARNOLD_NODE_PREFIX):]\n shader_prim.SetShaderId(ARNOLD_USD_PREFIX + shader_name)\n # Falling back to the built-in function.\n else:\n DefaultShaderTranslatorHelper.createShaderPrimID(self, shader_prim, shader_node)\n\n def createShaderPrimAttributes(self, shader_prim, shader_node):\n \"\"\" Creates and sets the shader parameters on the usd shader\n based on the given shader node.\n \"\"\"\n for parm_tuple in shader_node.parmTuples():\n parm_template = parm_tuple.parmTemplate()\n if isinstance(parm_template, hou.FolderParmTemplate) or isinstance(parm_template, hou.FolderSetParmTemplate):\n continue\n\n parm_translator = self.getParmTranslator(parm_tuple)\n if parm_translator is None:\n continue\n\n # Create an attribute on the usd prim and set its value.\n parm_translator.createAndSetAttrib(shader_prim, self.timeCode())\n\n def getRampParmTranslator(self, parm_tuple):\n \"\"\" Returns a translator for ramp parameters.\n \"\"\"\n if parm_tuple.node().type().name() not in ARNOLD_RAMP_TYPES:\n return None\n return ArnoldRampParmTranslator(parm_tuple)\n\n def getRenderContextName(self, shader_node, shader_node_output_name):\n \"\"\" Returns the name of the render context to be used in material\n output name.\n \"\"\"\n # We are only calling this helper on arnold shader, so we can just\n # hardcode the value.\n return ARNOLD_RENDER_CONTEXT_NAME\n\nclass ArnoldShaderTranslator(object):\n def __init__(self):\n self.my_id = -1\n\n def setTranslatorID(self, translator_id):\n self.my_id = translator_id\n\n def translatorID(self):\n return self.my_id\n\n def matchesRenderMask(self, render_mask):\n return render_mask == ARNOLD_RENDER_MASK\n\n def createMaterialShader(self, usd_stage, usd_material_path, usd_time_code, shader_node, shader_type, output_name):\n \"\"\" Creates a USD shader primitive that is part of the USD material\n Ie, the translator will connect the shader to the material output.\n\n usd_stage - UsdStage object on which to create the shader.\n usd_material_path - Path to the material primitive\n in which to create the shader.\n usd_time_code - time code (frame) at which to evaluate shader\n parameters and at which to set the primitive attributes.\n shader_node - Houdini node representing a shader.\n shader_type - Requested shader type to use, in case\n the shader node implements several shaders\n (eg, is a material builder).\n outupt_name - Particular output of the Houdini node that was\n used to arrive at the shader node and which represents the\n shader to translate (in case the node has several shaders).\n The output name can be an empty string, if node has no outputs.\n \"\"\"\n shader_node = resolve_fetch_vop(shader_node)\n if shader_node is None:\n return\n type_name = shader_node.type().name()\n # If type name is 'arnold_material' then we are working with an output node, and we need to check the different\n # terminals. Otherwise we are just dealing with the first node.\n shaders_to_translate = []\n # We directly got an arnold material, simply translate.\n if type_name == ARNOLD_MATERIAL:\n shaders_to_translate = get_shaders_to_translate(shader_node)\n # We pointed the material library to an arnold material builder, so we look for the first\n # arnold material inside and translate that.\n elif type_name == ARNOLD_MATERIALBUILDER:\n arnold_material = find_first_node_of_type(shader_node, ARNOLD_MATERIAL)\n if arnold_material:\n shaders_to_translate = get_shaders_to_translate(arnold_material)\n # We pointed to an arnold shader, and we are making the assumption that this is a surface shader.\n elif type_name.startswith(ARNOLD_NODE_PREFIX):\n shaders_to_translate = [(shader_node, ARNOLD_TERMINALS[0])]\n else:\n # If we are dealing with non-arnold materials, we are running the default shader translator.\n helper = DefaultShaderTranslatorHelper(self.translatorID(), usd_stage, usd_material_path, usd_time_code)\n helper.createMaterialShader(shader_node, shader_type, output_name)\n return\n\n for shader, shader_type in shaders_to_translate:\n shader = resolve_fetch_vop(shader)\n if shader and not shader.isBypassed():\n helper = ArnoldShaderHelper(self.translatorID(), usd_stage, usd_material_path, usd_time_code)\n helper.createMaterialShader(shader, shader_type, output_name)\n\narnold_translator = ArnoldShaderTranslator()\n\ndef usdShaderTranslator():\n return arnold_translator\n","sub_path":"third_party/houdini/scripts/python/husdshadertranslators/arnold.py","file_name":"arnold.py","file_ext":"py","file_size_in_byte":8680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"175492813","text":"#!/usr/bin/env python\n\n\"\"\"Takes vehicle heading data from the EKF odometry message as well as orientation, twist, and accel data from the IMU and publishes as an imu message.\n\nNOTE: The EKF assumes a 2-D world so the roll, pitch, roll rate, pitch rate, and linear acceleration must come from the IMU\n\nSubscribes\n----------\nTopic: /odometry/filtered\n Msg: nav_msgs/Odometry\n\nTopic: /localization/rotated_imu\n Msg: sensor_msgs/Imu\n\nPublishes\n---------\nTopic: /localization/ekf_orientation\n Msg: sensor_msgs/Imu\n\n\"\"\"\n\nimport rospy\nfrom tf.transformations import euler_from_quaternion, quaternion_from_euler\nfrom nav_msgs.msg import Odometry\nfrom sensor_msgs.msg import Imu\nfrom geometry_msgs.msg import Quaternion\n\nclass imuMsgConverter(object):\n \"\"\"Takes orientation data from the EKF and republishes as an IMU message\"\"\"\n\n def __init__(self):\n self.imuMsgPublisher = rospy.Publisher(\"/localization/ekf_orientation\", Imu, queue_size = 100)\n\n # Initialize a sensor_msgs/Imu message and assign to the imuMsgConverter object\n self.receivedImuMsg = Imu()\n\n # Initialize a geometry/Quaternion message and assign to the imuMsgConverter object\n self.receivedImuQuat = Quaternion()\n\n def imu_callback(self, imuMsg):\n \"\"\"Callback subscribed to the IMU output\"\"\"\n self.receivedImuMsg = imuMsg\n self.receivedImuQuat = imuMsg.orientation\n\n def ekf_callback(self, ekfMsg):\n \"\"\"Callback subscribed to the EKF output\"\"\"\n updatedImuMsg = self.create_imu_msg(ekfMsg.pose.pose.orientation.x, ekfMsg.pose.pose.orientation.y,\n ekfMsg.pose.pose.orientation.z, ekfMsg.pose.pose.orientation.w,\n self.receivedImuQuat.x, self.receivedImuQuat.y,\n self.receivedImuQuat.z, self.receivedImuQuat.w)\n \n self.imuMsgPublisher.publish(updatedImuMsg)\n\n def create_imu_msg(self, ekf_quat_x, ekf_quat_y, ekf_quat_z, ekf_quat_w, imu_quat_x, imu_quat_y, imu_quat_z, imu_quat_w):\n \"\"\"Compose the Imu message\"\"\"\n updatedImuMsg = self.receivedImuMsg\n\n # Take the roll, pitch, and yaw from the ekf message\n (ekf_roll, ekf_pitch, ekf_yaw) = euler_from_quaternion([ekf_quat_x, ekf_quat_y, ekf_quat_z, ekf_quat_w])\n\n # Take the roll, pitch, and yaw from the imu message\n (imu_roll, imu_pitch, imu_yaw) = euler_from_quaternion([imu_quat_x, imu_quat_y, imu_quat_z, imu_quat_w])\n \n # Place the roll and pitch from the imu and the yaw from the ekf into the updated Imu message\n (new_quat_x, new_quat_y, new_quat_z, new_quat_w) = quaternion_from_euler(imu_roll, imu_pitch, ekf_yaw)\n \n updatedImuMsg.orientation.x = new_quat_x\n updatedImuMsg.orientation.y = new_quat_y\n updatedImuMsg.orientation.z = new_quat_z\n updatedImuMsg.orientation.w = new_quat_w\n\n return updatedImuMsg\n \n def imu_data_converter(self):\n \"\"\"Take the EKF orientation data and IMU data, convert to new IMU message, republish\"\"\"\n rospy.Subscriber(\"/odometry/filtered\", Odometry, self.ekf_callback, queue_size = 100)\n rospy.Subscriber(\"/localization/rotated_imu\", Imu, self.imu_callback, queue_size = 100)\n rospy.spin()\n\ndef main():\n rospy.init_node(\"imu_converter_node\", anonymous=False)\n imuConverter = imuMsgConverter()\n\n try:\n imuConverter.imu_data_converter()\n except rospy.ROSInterruptException:\n pass\n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"src/modules/localization/src/ekf_orientation_to_imu/ekf_orientation_to_imu.py","file_name":"ekf_orientation_to_imu.py","file_ext":"py","file_size_in_byte":3571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"438450147","text":"#!/usr/bin/env python\nimport os\nimport sys\n\n\ndef createEmptyFile(path):\n basedir = os.path.dirname(path)\n if not os.path.exists(basedir):\n os.makedirs(basedir)\n\n with open(path, 'a'):\n os.utime(path, None)\n\ndef createEmptyFileIfNotExistant(path):\n if not os.path.isfile(path):\n createEmptyFile(path)\n\n\nif __name__ == \"__main__\":\n from django.conf import settings\n from django.core.management import execute_from_command_line\n\n # create log file by default to prevent django logger errors\n BASE_DIR = os.path.dirname(os.path.realpath(__file__))\n debugLogs = os.path.join(BASE_DIR, 'logs', 'debug.log')\n createEmptyFileIfNotExistant(debugLogs)\n\n # choose local settings if available\n devSettings = \"boilerplate.settings.dev\"\n localSettings = \"boilerplate.settings.local\"\n\n djangoSettings = localSettings\n if not os.path.isfile(os.path.join(BASE_DIR, 'boilerplate', 'settings', 'local.py')):\n djangoSettings = devSettings\n\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", djangoSettings)\n\n # run manage command\n execute_from_command_line(sys.argv)\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"653801326","text":"# -*- coding: utf-8 -*-\nfrom .auth import Auth\nfrom .model import ThreadModel, PostModel\n\n\nclass TeamThread(Auth):\n def __init__(self, team_id, starred=False):\n \"\"\"\n 用于获取小组话题\n :param team_id: 小组ID\n :param starred: 是否仅获取精华话题\n \"\"\"\n self.team_id = team_id\n self.starred = starred\n\n def fetch(self, page, ipp=20):\n \"\"\"\n 获取话题列表\n :rtype: dict\n :param page: 页数\n :param ipp: 每页多少条\n :return:服务器返回的JSON数据\n \"\"\"\n if self.starred:\n url = 'https://www.shanbay.com/api/v1/team/%s/thread/?starred&page=%d&ipp=%d' % (self.team_id, page, ipp)\n else:\n url = 'https://www.shanbay.com/api/v1/team/%s/thread/?page=%d&ipp=%d' % (self.team_id, page, ipp)\n return __class__.request.get(url).json()\n\n def page_threads(self, page, ipp=20):\n \"\"\"\n 获取该页的话题并解析\n :rtype: list\n :param page: 页数\n :param ipp: 每页多少条\n :return: 该页的话题\n \"\"\"\n _json = self.fetch(page, ipp)\n tmp = []\n for obj in _json['data']['objects']:\n tmp.append(ThreadModel(**obj))\n return tmp\n\n def ithreads(self, start_page=1, end_page=500, ipp=20):\n \"\"\"\n 获取话题并解析,自动翻页。\n 注意:小组的话题可能非常多,使用该方法时注意加条件限制获取条数。\n :param start_page: 起始页码\n :param end_page: 终止页码\n :param ipp: 每页多少条\n \"\"\"\n for page in range(start_page, end_page + 1):\n for thds in self.page_threads(page, ipp):\n yield thds\n\n\nclass Post(Auth):\n def __init__(self, thread_id):\n \"\"\"\n 用于获取帖子\n :param thread_id: 话题ID\n \"\"\"\n self.thread_id = thread_id\n\n def fetch(self, page, ipp=20):\n \"\"\"\n 获取话题下的帖子\n :rtype: dict\n :param page: 页数\n :param ipp: 每页多少条\n :return: 服务器返回的JSON数据\n \"\"\"\n url = 'https://www.shanbay.com/api/v1/forum/thread/%d/post/?page=%d&ipp=%d' % (self.thread_id, page, ipp)\n return __class__.request.get(url).json()\n\n def iposts(self, ipp=20):\n \"\"\"\n 获取话题下的帖子并解析,该方法返回生成器\n :param ipp: 每页多少条\n \"\"\"\n page = 0\n while True:\n page += 1\n _json = self.fetch(page, ipp)\n for post in _json['data']['posts']:\n yield PostModel(**post)\n if _json['data']['total'] <= page * ipp:\n break\n\n def posts(self):\n \"\"\"\n 获取话题下所有帖子并解析\n :rtype: list\n :return: 所有帖子数组\n \"\"\"\n tmp = []\n for p in self.iposts():\n tmp.append(p)\n return tmp\n","sub_path":"bin/shanbay/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"347425980","text":"#!/usr/bin/python\n\nimport sys\n\ndef factorial( n ):\n if n == 0:\n return 1\n else:\n return n*factorial(n-1)\n\n\ndef nchoosek( n, k ):\n #return factorial(n)/(factorial(k)*factorial(n-k))\n answer = 1\n for i in range(1,k+1):\n answer *= (n - (k - i))\n answer /= i\n return answer\n\nprint(\"0\")\nfor N in range(1,(10**6)+1):\n numbers_seen = set()\n for i in range(1,1000):\n multiple = i*N\n digits = str(multiple)\n for digit in digits:\n numbers_seen.add(digit)\n if len(numbers_seen) == 10:\n print(multiple)\n break\n if i == 1000:\n print(\"INSOMNIA\")\n\n","sub_path":"solutions_5652388522229760_1/Python/DAMF/making_table.py","file_name":"making_table.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"289362739","text":"#!/usr/bin/env python\n\n# import argparse\nimport pyphen\n\n\nclass Shortening_Words(object):\n \"\"\"docstring for Shortening_Words\"\"\"\n\n def __init__(self, words, max_len, lang):\n self.dic = pyphen.Pyphen(lang=lang)\n listWords = words.split(\" \")\n self.max_len = int(max_len) - (len(listWords)\n if int(max_len) < len(words) else 0)\n self.phrase = self.short_words(listWords)\n\n def insert(self, index, element, _list):\n pos = 1\n for item in _list:\n if item[index] >= element[index]:\n pos += 1\n elif item[index] < element[index]:\n pos -= 1\n break\n _list.insert(pos, element)\n return _list\n\n def measure_word(self, sizes):\n newListWords = {}\n for i in range(max([len(x) for x in sizes])):\n for idx, s in enumerate(sizes):\n if i < len(s):\n if i not in newListWords:\n newListWords[i] = []\n if i > 0:\n summation = sum([a[2] for a in newListWords[i-1]])\n element = (idx, s[i], s[i]+summation)\n else:\n element = (idx, s[i], s[i])\n newListWords[i] = self.insert(2, element, newListWords[i])\n return newListWords\n\n def length_Word(self, newListWords):\n total = 0\n listWords = {}\n for x in newListWords:\n for y in newListWords[x]:\n if total + y[1] > self.max_len:\n break\n total += y[1]\n if y[0] in listWords:\n listWords[y[0]] += y[1]\n else:\n listWords[y[0]] = y[1]\n return listWords\n\n def short_words(self, listWords):\n sizes = []\n for word in listWords:\n sizes.append(self.get_list_sizes(word))\n newListWords = self.measure_word(sizes)\n listWords2 = self.length_Word(newListWords)\n phrase = [\"\"]*len(sizes)\n for idx, word in enumerate(listWords):\n if idx in listWords2:\n phrase[idx] = word[:listWords2[idx]]\n else:\n phrase[idx] = word[:1]\n if len(phrase[idx]) < len(word):\n phrase[idx] += \".\"\n\n return \" \".join(phrase)\n\n def shortWord(self, word, max_len):\n s = self.dic.inserted(word).split(\"-\")\n pos = 1\n for letters in s:\n if len(letters) < max_len:\n pos += 1\n else:\n \"is too big, we get the rest\"\n break\n res = \"\".join(s[:pos])\n res += \".\" if len(res) < len(word) else \"\"\n return res\n\n def get_list_sizes(self, word):\n return [len(x) for x in self.dic.inserted(word).split(\"-\")]\n\n\n# if __name__ == '__main__':\n# parser = argparse.ArgumentParser(description='Shortening words')\n# parser.add_argument('-w',\n# dest='words',\n# help=\"words to shortening\",\n# type=str,\n# action='store', default='')\n# parser.add_argument('-l',\n# dest='max_len',\n# help=\"word to shortening\",\n# type=str,\n# action='store', default='')\n# parser.add_argument('--lang',\n# dest='lang',\n# help=\"Language to use (ISO 639)\",\n# type=str,\n# action='store', default='en')\n# args = parser.parse_args()\n\n# print(Shortening_Words(**vars(args)).phrase)\n","sub_path":"shortening_words/shortening.py","file_name":"shortening.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"26963713","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nimport logging\nimport re\n\nlogging.basicConfig(level=logging.DEBUG, format='%(message)s')\n\n\ndef create_filename(filename, processing_params):\n\n \"\"\" создает имя файла в зависимости от параметров.\n\n processing_params['v_codec'] - влияет на расширение файла\n processing_params['postfix'] - будет добавлено в конце названия\n\n\n Зависимости:\n os, logging\n\n Возвращает:\n str - имя файла\n \"\"\"\n\n basename = os.path.splitext(filename)[0]\n extension = os.path.splitext(filename)[-1]\n\n output_name = replace_letters(basename)\n\n logging.debug('create_filename')\n\n extension = select_extension(extension, processing_params)\n\n if processing_params['postfix'] is not None and \\\n processing_params['postfix'] != '':\n\n output_name += '_' + processing_params['postfix']\n\n logging.debug(\"output_name \" + output_name)\n\n return output_name + extension\n\n\ndef select_extension(extension, processing_params):\n\n if 'extension' in processing_params and \\\n processing_params['extension'] is not None:\n return processing_params['extension']\n\n if 'vn' in processing_params and \\\n processing_params['vn'] is True:\n\n if processing_params['a_codec'] != 'copy':\n\n return '.mp4'\n\n else:\n\n return extension\n\n if 'v_codec' in processing_params:\n\n if processing_params['v_codec'] == 'h264':\n\n return '.mp4'\n\n elif processing_params['v_codec'] == 'prores':\n\n return '.mov'\n\n return extension\n\n\ndef decode_filename(word):\n \"\"\"При использовании питона 2.7 возникает проблема,\n связанная с тем что для трансилетрации файлов их\n названия сначала приходится декодировать из\n родной кодироваки системы в кодировку UTF-8.\n\n Цикл перебирает разные кодировки, первая из которых\n получена с помощью sys.getdefaultencoding()\n \"\"\"\n\n sys_encoding = str(sys.getdefaultencoding())\n encodings = (sys_encoding, 'utf-8', 'ascii', 'cp1251', 'utf-16')\n\n logging.debug('Filename decoding')\n\n for encoding in encodings:\n logging.debug(encoding)\n try:\n new_word = word.decode(encoding)\n except Exception:\n continue\n else:\n word = new_word\n break\n\n word = word.encode('utf-8', 'ignore')\n word = str(word)\n\n return word\n\n\ndef replace_letters(word):\n\n word = str(word)\n word = word.lower()\n\n logging.debug(word)\n\n for i, j in legend.items():\n word = word.replace(i, j)\n\n word = re.sub(r'[^\\w\\s]', '', word)\n word = word.replace(\"'\", \"\")\n # старая версия замены\n # word = word.translate(None, string.punctuation)\n\n return word\n\n\ndef rename_all_in_directory(file_list, processing_params):\n\n for file_old in file_list:\n\n print(file_old)\n\n file_new = create_filename(file_old, processing_params)\n\n if file_old == file_new:\n print ('{0: <30}'.format(file_old), 'old name and the new one are identic')\n elif file_new == '':\n print ('{0: <30}'.format(file_old), 'invalid name')\n else:\n print ('{0: <30}'.format(file_old), 'will be renamed in ', file_new)\n\n os.rename(file_old, file_new)\n\nlegend = {\n ' ': '_',\n '.': '_',\n ',': '',\n '-': '_',\n '—': '_',\n '#': '',\n '/': '',\n '!': '',\n '?': '',\n ':': '',\n ';': '',\n '«': '',\n '»': '',\n 'а': 'a',\n 'б': 'b',\n 'в': 'v',\n 'г': 'g',\n 'д': 'd',\n 'е': 'e',\n 'ё': 'yo',\n 'ж': 'zh',\n 'з': 'z',\n 'и': 'i',\n 'й': 'y',\n 'к': 'k',\n 'л': 'l',\n 'м': 'm',\n 'н': 'n',\n 'о': 'o',\n 'п': 'p',\n 'р': 'r',\n 'с': 's',\n 'т': 't',\n 'у': 'u',\n 'ф': 'f',\n 'х': 'h',\n 'ц': 'c',\n 'ч': 'ch',\n 'ш': 'sh',\n 'щ': 'shch',\n 'ъ': 'y',\n 'ы': 'y',\n 'ь': '',\n 'э': 'e',\n 'ю': 'yu',\n 'я': 'ya',\n 'А': 'A',\n 'Б': 'B',\n 'В': 'V',\n 'Г': 'G',\n 'Д': 'D',\n 'Е': 'E',\n 'Ё': 'Yo',\n 'Ж': 'Zh',\n 'З': 'Z',\n 'И': 'I',\n 'Й': 'Y',\n 'К': 'K',\n 'Л': 'L',\n 'М': 'M',\n 'Н': 'N',\n 'О': 'O',\n 'П': 'P',\n 'Р': 'R',\n 'С': 'S',\n 'Т': 'T',\n 'У': 'U',\n 'Ф': 'F',\n 'Х': 'H',\n 'Ц': 'Ts',\n 'Ч': 'Ch',\n 'Ш': 'Sh',\n 'Щ': 'Shch',\n 'Ъ': 'Y',\n 'Ы': 'Y',\n 'Ь': '',\n 'Э': 'E',\n 'Ю': 'Yu',\n 'Я': 'Ya',\n '(': '',\n ')': '',\n '[': '',\n ']': '',\n}\n","sub_path":"lib/modules/transliterator.py","file_name":"transliterator.py","file_ext":"py","file_size_in_byte":4890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"304090487","text":"#!/usr/bin/env python\n\"\"\"\n\nCopyright (c) 2018 Alex Forencich\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n\"\"\"\n\nfrom myhdl import *\nimport os\n\nimport pcie\nimport pcie_usp\nimport axi\n\nmodule = 'pcie_us_axi_master_rd'\ntestbench = 'test_%s_512' % module\n\nsrcs = []\n\nsrcs.append(\"../rtl/%s.v\" % module)\nsrcs.append(\"%s.v\" % testbench)\n\nsrc = ' '.join(srcs)\n\nbuild_cmd = \"iverilog -o %s.vvp %s\" % (testbench, src)\n\ndef bench():\n\n # Parameters\n AXIS_PCIE_DATA_WIDTH = 512\n AXIS_PCIE_KEEP_WIDTH = (AXIS_PCIE_DATA_WIDTH/32)\n AXIS_PCIE_CQ_USER_WIDTH = 183\n AXIS_PCIE_CC_USER_WIDTH = 81\n AXI_DATA_WIDTH = AXIS_PCIE_DATA_WIDTH\n AXI_ADDR_WIDTH = 64\n AXI_STRB_WIDTH = (AXI_DATA_WIDTH/8)\n AXI_ID_WIDTH = 8\n AXI_MAX_BURST_LEN = 256\n\n # Inputs\n clk = Signal(bool(0))\n rst = Signal(bool(0))\n current_test = Signal(intbv(0)[8:])\n\n s_axis_cq_tdata = Signal(intbv(0)[AXIS_PCIE_DATA_WIDTH:])\n s_axis_cq_tkeep = Signal(intbv(0)[AXIS_PCIE_KEEP_WIDTH:])\n s_axis_cq_tvalid = Signal(bool(0))\n s_axis_cq_tlast = Signal(bool(0))\n s_axis_cq_tuser = Signal(intbv(0)[AXIS_PCIE_CQ_USER_WIDTH:])\n m_axis_cc_tready = Signal(bool(0))\n m_axi_arready = Signal(bool(0))\n m_axi_rid = Signal(intbv(0)[AXI_ID_WIDTH:])\n m_axi_rdata = Signal(intbv(0)[AXI_DATA_WIDTH:])\n m_axi_rresp = Signal(intbv(0)[2:])\n m_axi_rlast = Signal(bool(0))\n m_axi_rvalid = Signal(bool(0))\n completer_id = Signal(intbv(0)[16:])\n completer_id_enable = Signal(bool(0))\n max_payload_size = Signal(intbv(0)[3:])\n\n # Outputs\n s_axis_cq_tready = Signal(bool(0))\n m_axis_cc_tdata = Signal(intbv(0)[AXIS_PCIE_DATA_WIDTH:])\n m_axis_cc_tkeep = Signal(intbv(0)[AXIS_PCIE_KEEP_WIDTH:])\n m_axis_cc_tvalid = Signal(bool(0))\n m_axis_cc_tlast = Signal(bool(0))\n m_axis_cc_tuser = Signal(intbv(0)[AXIS_PCIE_CC_USER_WIDTH:])\n m_axi_arid = Signal(intbv(0)[AXI_ID_WIDTH:])\n m_axi_araddr = Signal(intbv(0)[AXI_ADDR_WIDTH:])\n m_axi_arlen = Signal(intbv(0)[8:])\n m_axi_arsize = Signal(intbv(6)[3:])\n m_axi_arburst = Signal(intbv(1)[2:])\n m_axi_arlock = Signal(bool(0))\n m_axi_arcache = Signal(intbv(3)[4:])\n m_axi_arprot = Signal(intbv(2)[3:])\n m_axi_arvalid = Signal(bool(0))\n m_axi_rready = Signal(bool(0))\n status_error_cor = Signal(bool(0))\n status_error_uncor = Signal(bool(0))\n\n # Clock and Reset Interface\n user_clk=Signal(bool(0))\n user_reset=Signal(bool(0))\n sys_clk=Signal(bool(0))\n sys_reset=Signal(bool(0))\n\n # AXI4 RAM model\n axi_ram_inst = axi.AXIRam(2**16)\n\n axi_ram_port0 = axi_ram_inst.create_port(\n user_clk,\n s_axi_arid=m_axi_arid,\n s_axi_araddr=m_axi_araddr,\n s_axi_arlen=m_axi_arlen,\n s_axi_arsize=m_axi_arsize,\n s_axi_arburst=m_axi_arburst,\n s_axi_arlock=m_axi_arlock,\n s_axi_arcache=m_axi_arcache,\n s_axi_arprot=m_axi_arprot,\n s_axi_arvalid=m_axi_arvalid,\n s_axi_arready=m_axi_arready,\n s_axi_rid=m_axi_rid,\n s_axi_rdata=m_axi_rdata,\n s_axi_rresp=m_axi_rresp,\n s_axi_rlast=m_axi_rlast,\n s_axi_rvalid=m_axi_rvalid,\n s_axi_rready=m_axi_rready,\n name='port0'\n )\n\n # PCIe devices\n rc = pcie.RootComplex()\n\n dev = pcie_usp.UltrascalePlusPCIe()\n\n dev.pcie_generation = 3\n dev.pcie_link_width = 16\n dev.user_clock_frequency = 250e6\n\n dev.functions[0].configure_bar(0, 16*1024*1024)\n dev.functions[0].configure_bar(1, 32, io=True)\n\n rc.make_port().connect(dev)\n\n cq_pause = Signal(bool(0))\n cc_pause = Signal(bool(0))\n rq_pause = Signal(bool(0))\n rc_pause = Signal(bool(0))\n\n pcie_logic = dev.create_logic(\n # Completer reQuest Interface\n m_axis_cq_tdata=s_axis_cq_tdata,\n m_axis_cq_tuser=s_axis_cq_tuser,\n m_axis_cq_tlast=s_axis_cq_tlast,\n m_axis_cq_tkeep=s_axis_cq_tkeep,\n m_axis_cq_tvalid=s_axis_cq_tvalid,\n m_axis_cq_tready=s_axis_cq_tready,\n #pcie_cq_np_req=pcie_cq_np_req,\n #pcie_cq_np_req_count=pcie_cq_np_req_count,\n\n # Completer Completion Interface\n s_axis_cc_tdata=m_axis_cc_tdata,\n s_axis_cc_tuser=m_axis_cc_tuser,\n s_axis_cc_tlast=m_axis_cc_tlast,\n s_axis_cc_tkeep=m_axis_cc_tkeep,\n s_axis_cc_tvalid=m_axis_cc_tvalid,\n s_axis_cc_tready=m_axis_cc_tready,\n\n # Requester reQuest Interface\n s_axis_rq_tdata=Signal(intbv(0)[AXIS_PCIE_DATA_WIDTH:]),\n s_axis_rq_tuser=Signal(intbv(0)[137:]),\n s_axis_rq_tlast=Signal(bool(0)),\n s_axis_rq_tkeep=Signal(intbv(0)[AXIS_PCIE_KEEP_WIDTH:]),\n s_axis_rq_tvalid=Signal(bool(0)),\n s_axis_rq_tready=Signal(bool(1)),\n # pcie_rq_seq_num0=pcie_rq_seq_num0,\n # pcie_rq_seq_num_vld0=pcie_rq_seq_num_vld0,\n # pcie_rq_seq_num1=pcie_rq_seq_num1,\n # pcie_rq_seq_num_vld1=pcie_rq_seq_num_vld1,\n # pcie_rq_tag0=pcie_rq_tag0,\n # pcie_rq_tag1=pcie_rq_tag1,\n # pcie_rq_tag_av=pcie_rq_tag_av,\n # pcie_rq_tag_vld0=pcie_rq_tag_vld0,\n # pcie_rq_tag_vld1=pcie_rq_tag_vld1,\n\n # Requester Completion Interface\n m_axis_rc_tdata=Signal(intbv(0)[AXIS_PCIE_DATA_WIDTH:]),\n m_axis_rc_tuser=Signal(intbv(0)[161:]),\n m_axis_rc_tlast=Signal(bool(0)),\n m_axis_rc_tkeep=Signal(intbv(0)[AXIS_PCIE_KEEP_WIDTH:]),\n m_axis_rc_tvalid=Signal(bool(0)),\n m_axis_rc_tready=Signal(bool(0)),\n\n # Transmit Flow Control Interface\n # pcie_tfc_nph_av=pcie_tfc_nph_av,\n # pcie_tfc_npd_av=pcie_tfc_npd_av,\n\n # Configuration Control Interface\n # cfg_hot_reset_in=cfg_hot_reset_in,\n # cfg_hot_reset_out=cfg_hot_reset_out,\n # cfg_config_space_enable=cfg_config_space_enable,\n # cfg_dsn=cfg_dsn,\n # cfg_ds_port_number=cfg_ds_port_number,\n # cfg_ds_bus_number=cfg_ds_bus_number,\n # cfg_ds_device_number=cfg_ds_device_number,\n # cfg_ds_function_number=cfg_ds_function_number,\n # cfg_power_state_change_ack=cfg_power_state_change_ack,\n # cfg_power_state_change_interrupt=cfg_power_state_change_interrupt,\n # cfg_err_cor_in=cfg_err_cor_in,\n # cfg_err_uncor_in=cfg_err_uncor_in,\n # cfg_flr_done=cfg_flr_done,\n # cfg_vf_flr_done=cfg_vf_flr_done,\n # cfg_flr_in_process=cfg_flr_in_process,\n # cfg_vf_flr_in_process=cfg_vf_flr_in_process,\n # cfg_req_pm_transition_l23_ready=cfg_req_pm_transition_l23_ready,\n # cfg_link_training_enable=cfg_link_training_enable,\n\n # Clock and Reset Interface\n user_clk=user_clk,\n user_reset=user_reset,\n #user_lnk_up=user_lnk_up,\n sys_clk=sys_clk,\n sys_clk_gt=sys_clk,\n sys_reset=sys_reset,\n\n cq_pause=cq_pause,\n cc_pause=cc_pause,\n rq_pause=rq_pause,\n rc_pause=rc_pause\n )\n\n # DUT\n if os.system(build_cmd):\n raise Exception(\"Error running build command\")\n\n dut = Cosimulation(\n \"vvp -m myhdl %s.vvp -lxt2\" % testbench,\n clk=user_clk,\n rst=user_reset,\n current_test=current_test,\n s_axis_cq_tdata=s_axis_cq_tdata,\n s_axis_cq_tkeep=s_axis_cq_tkeep,\n s_axis_cq_tvalid=s_axis_cq_tvalid,\n s_axis_cq_tready=s_axis_cq_tready,\n s_axis_cq_tlast=s_axis_cq_tlast,\n s_axis_cq_tuser=s_axis_cq_tuser,\n m_axis_cc_tdata=m_axis_cc_tdata,\n m_axis_cc_tkeep=m_axis_cc_tkeep,\n m_axis_cc_tvalid=m_axis_cc_tvalid,\n m_axis_cc_tready=m_axis_cc_tready,\n m_axis_cc_tlast=m_axis_cc_tlast,\n m_axis_cc_tuser=m_axis_cc_tuser,\n m_axi_arid=m_axi_arid,\n m_axi_araddr=m_axi_araddr,\n m_axi_arlen=m_axi_arlen,\n m_axi_arsize=m_axi_arsize,\n m_axi_arburst=m_axi_arburst,\n m_axi_arlock=m_axi_arlock,\n m_axi_arcache=m_axi_arcache,\n m_axi_arprot=m_axi_arprot,\n m_axi_arvalid=m_axi_arvalid,\n m_axi_arready=m_axi_arready,\n m_axi_rid=m_axi_rid,\n m_axi_rdata=m_axi_rdata,\n m_axi_rresp=m_axi_rresp,\n m_axi_rlast=m_axi_rlast,\n m_axi_rvalid=m_axi_rvalid,\n m_axi_rready=m_axi_rready,\n completer_id=completer_id,\n completer_id_enable=completer_id_enable,\n max_payload_size=max_payload_size,\n status_error_cor=status_error_cor,\n status_error_uncor=status_error_uncor\n )\n\n @always(delay(4))\n def clkgen():\n clk.next = not clk\n\n @always_comb\n def clk_logic():\n sys_clk.next = clk\n sys_reset.next = not rst\n\n status_error_cor_asserted = Signal(bool(0))\n status_error_uncor_asserted = Signal(bool(0))\n\n @always(user_clk.posedge)\n def monitor():\n if (status_error_cor):\n status_error_cor_asserted.next = 1\n if (status_error_uncor):\n status_error_uncor_asserted.next = 1\n\n cq_pause_toggle = Signal(bool(0))\n cc_pause_toggle = Signal(bool(0))\n rq_pause_toggle = Signal(bool(0))\n rc_pause_toggle = Signal(bool(0))\n\n @instance\n def pause_toggle():\n while True:\n if (cq_pause_toggle or cc_pause_toggle or rq_pause_toggle or rc_pause_toggle):\n cq_pause.next = cq_pause_toggle\n cc_pause.next = cc_pause_toggle\n rq_pause.next = rq_pause_toggle\n rc_pause.next = rc_pause_toggle\n\n yield user_clk.posedge\n yield user_clk.posedge\n yield user_clk.posedge\n\n cq_pause.next = 0\n cc_pause.next = 0\n rq_pause.next = 0\n rc_pause.next = 0\n\n yield user_clk.posedge\n\n @instance\n def check():\n yield delay(100)\n yield clk.posedge\n rst.next = 1\n yield clk.posedge\n rst.next = 0\n yield clk.posedge\n yield delay(100)\n yield clk.posedge\n\n # testbench stimulus\n\n max_payload_size.next = 0\n\n yield user_clk.posedge\n print(\"test 1: enumeration\")\n current_test.next = 1\n\n yield rc.enumerate()\n\n dev_bar0 = rc.tree[0][0].bar[0]\n dev_bar1 = rc.tree[0][0].bar[1]\n\n yield delay(100)\n\n yield clk.posedge\n print(\"test 2: memory read\")\n current_test.next = 2\n\n pcie_addr = 0x00000000\n test_data = b'\\x11\\x22\\x33\\x44'\n\n axi_ram_inst.write_mem(pcie_addr, test_data)\n\n data = axi_ram_inst.read_mem(0, 32)\n for i in range(0, len(data), 16):\n print(\" \".join((\"{:02x}\".format(c) for c in bytearray(data[i:i+16]))))\n\n val = yield from rc.mem_read(dev_bar0+pcie_addr, len(test_data), 1000)\n\n print(val)\n\n assert val == test_data\n\n assert not status_error_cor_asserted\n assert not status_error_uncor_asserted\n\n yield delay(100)\n\n yield user_clk.posedge\n print(\"test 3: various reads\")\n current_test.next = 3\n\n for length in list(range(1,66))+[1024]:\n for pcie_offset in list(range(8,73))+list(range(4096-64,4096)):\n for pause in [False, True]:\n print(\"length %d, pcie_offset %d\"% (length, pcie_offset))\n #pcie_addr = length * 0x100000000 + pcie_offset * 0x10000 + offset\n pcie_addr = pcie_offset\n test_data = bytearray([x%256 for x in range(length)])\n\n axi_ram_inst.write_mem(pcie_addr & 0xffff80, b'\\x55'*(len(test_data)+256))\n axi_ram_inst.write_mem(pcie_addr, test_data) \n\n data = axi_ram_inst.read_mem(pcie_addr&0xfffff0, 64)\n for i in range(0, len(data), 16):\n print(\" \".join((\"{:02x}\".format(c) for c in bytearray(data[i:i+16]))))\n\n cq_pause_toggle.next = pause\n cc_pause_toggle.next = pause\n\n val = yield from rc.mem_read(dev_bar0+pcie_addr, len(test_data), 1000)\n\n cq_pause_toggle.next = 0\n cc_pause_toggle.next = 0\n\n print(val)\n\n assert val == test_data\n\n assert not status_error_cor_asserted\n assert not status_error_uncor_asserted\n\n yield delay(100)\n\n yield clk.posedge\n print(\"test 4: bad requests\")\n current_test.next = 4\n\n yield from rc.mem_write(dev_bar0, b'\\x11\\x22\\x33\\x44')\n\n yield delay(100)\n\n assert not status_error_cor_asserted\n assert status_error_uncor_asserted\n\n status_error_cor_asserted.next = False\n status_error_uncor_asserted.next = False\n\n try:\n yield from rc.io_write(dev_bar1, b'\\x11\\x22\\x33\\x44')\n except:\n print(\"Caught unsuccessful completion exception\")\n pass\n else:\n assert False\n\n assert status_error_cor_asserted\n assert not status_error_uncor_asserted\n\n status_error_cor_asserted.next = False\n status_error_uncor_asserted.next = False\n\n yield delay(100)\n\n raise StopSimulation\n\n return instances()\n\ndef test_bench():\n sim = Simulation(bench())\n sim.run()\n\nif __name__ == '__main__':\n print(\"Running test...\")\n test_bench()\n","sub_path":"tb/test_pcie_us_axi_master_rd_512.py","file_name":"test_pcie_us_axi_master_rd_512.py","file_ext":"py","file_size_in_byte":14235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"156973481","text":"\"\"\"Binary search\nWe basically ignore half of the elements just after one comparison.\n\nCompare x with the middle element.\nIf x matches with middle element, we return the mid index.\nElse If x is greater than the mid element, then x can only lie in right half subarray after the mid element. So we recur for right half.\nElse (x is smaller) recur for the left half.\n\n\n\"\"\"\n\ndef binarySearch(arr,l,r,x):\n # Check base case\n if r >= l:\n\n mid = 1+(r - 1) // 2\n\n # If element is present at the middle itself\n if arr[mid] == x:\n return mid\n elif arr[mid] > x:\n return binarySearch(arr, l, mid - 1, x)\n\n # Else the element can only be present\n # in right subarray\n else:\n return binarySearch(arr, mid + 1, r, x)\n else:\n # Element is not present in the array\n return -1\n\n # Driver Code\n arr = [2, 3, 4, 10, 40]\n x = 10\n\n # Function call\n result = binarySearch(arr, 0, len(arr) - 1, x)\n\n if result != -1:\n print(\"Element is present at index % d\" % result)\n else:\n print(\"Element is not present in array\")","sub_path":"BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"525586849","text":"#!/usr/bin/env python\n# coding:utf-8\n# **********************************************************\n# * Author : Navin Xu\n# * Email : admin@navinxu.com\n# * Create time : 2019-12-28 20:09\n# * Filename : test-isinstace.py\n# * Description :\n# **********************************************************\n\naStr = \"\"\nif isinstance(aStr, str):\n print(\"str\")\n\naList = [1, 2, 3]\nif isinstance(aList, list):\n print(\"list\")\n\nif isinstance(aStr, list):\n print(\"list\")\n\naNone = None\nif aNone is None:\n print(\"None\")\n","sub_path":"test-isinstace.py","file_name":"test-isinstace.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"641272870","text":"from dwave.system.samplers import DWaveSampler\r\nfrom dwave.system.composites import EmbeddingComposite\r\nfrom sympy import symbols, Poly\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom _tokens import get_sapi_token, get_dwave_url\r\n\r\nsapi_token = get_sapi_token()\r\ndwave_url = get_dwave_url()\r\n\r\nDWaveSamplerInstance = DWaveSampler(token = sapi_token, endpoint = dwave_url, solver = 'DW_2000Q_2_1')\r\n\r\n###############################################################################################################################################################################################\r\ndef reduce_squares(polynomial, symb):\r\n Coeffs = [coeff for (nums, coeff) in polynomial.terms() if any(nums)!=0]\r\n\r\n n_list = []\r\n\r\n for i in range(len(polynomial.terms()[0][0])):\r\n n = tuple([1 if nums[i] == 2 else nums[i] for (nums, coeff) in polynomial.terms()])\r\n n_list.append(n)\r\n\r\n new_terms = tuple(zip(tuple(zip(*n_list)), Coeffs))\r\n Poly(sum([np.prod([x**n for (x,n) in zip(symb, nums)])*coeff for (nums, coeff) in new_terms]))\r\n new_polynomial = Poly(sum([np.prod([x**n for (x,n) in zip(symb, nums)])*coeff for (nums, coeff) in new_terms]))\r\n\r\n return new_polynomial\r\n\r\ndef translate_indexes(polynomial):\r\n translate_dict = {}\r\n\r\n # create tuples of type (n,n) for linear terms and (n,m) for quadratic terms\r\n for polynomial_index in polynomial.as_dict().keys():\r\n d = dict(enumerate(polynomial_index, 1))\r\n qubit_index = tuple([key for key, value in d.items() if value == 1])\r\n\r\n # for linear terms, tuple of type (n,) needs to be transformed to (n,n)\r\n if len(qubit_index) == 1:\r\n #qubit_index = qubit_index + qubit_index\r\n translate_dict[polynomial_index] = tuple(qubit_index + qubit_index)\r\n else:\r\n translate_dict[polynomial_index] = qubit_index\r\n\r\n qubit_dict = {}\r\n\r\n for polynomial_index in polynomial.as_dict().keys():\r\n qubit_index = translate_dict[polynomial_index]\r\n qubit_dict[qubit_index] = int(polynomial.as_dict()[polynomial_index])\r\n return qubit_dict\r\n\r\n###############################################################################################################################################################################################\r\n### Problem: 2x1 + 3x2 -> min\r\n### x1 + x2 = 1\r\n### x1,x2 - bin\r\n### H = 2x1 + 3x2 + P*(x1 + x2 - 1)^2\r\n### for P = 5: H = -3x1 - 2x2 + 10x1x2\r\n\r\nx1,x2 = symbols('x1:3')\r\nobj = Poly(2*x1 + 3*x2) # ----> min\r\nc1 = Poly(x1 + x2 - 1) # constraint\r\nP = 5 # 0.5 # penalty\r\nH = obj + P*c1**2\r\n\r\n# reduce x**2 to x as x is binary\r\nH1 = reduce_squares(H, [x1,x2])\r\nQ = translate_indexes(H1)\r\n\r\nresponse = EmbeddingComposite(DWaveSamplerInstance).sample_qubo(Q, num_reads=1000)\r\nfor sample in response.data():\r\n print(sample[0], \"Energy: \", sample[1], \"Occurrences: \",sample[2])\r\n\r\n###############################################################################################################################################################################################\r\n### Problem: 2x1 - 3x2 -> min\r\n### x1 + x2 <= 1 ----> x1 + x2 + s = 1, s - bin\r\n### x1,x2 - bin\r\n### H = 2x1 - 3x2 + P*(x1 + x2 + s - 1)^2\r\n### for P = 1: x1 - 4x2 - s + 2s*x1 + 2s*x2 + 2x1x2 + 1\r\n\r\nx1,x2,s = symbols('x1:3,s')\r\n\r\nobj = Poly(2*x1 - 3*x2) # ----> min\r\nc1 = Poly(x1 + x2 + s - 1) # constraint\r\nP = 1 # penalty\r\nH = obj + P*c1**2\r\n\r\n# reduce x**2 to x as x is binary\r\nH1 = reduce_squares(H, (x1,x2,s))\r\nQ = translate_indexes(H1)\r\n\r\nresponse = EmbeddingComposite(DWaveSamplerInstance).sample_qubo(Q, num_reads=1000)\r\nfor sample in response.data():\r\n print(sample[0], \"Energy: \", sample[1], \"Occurrences: \",sample[2])\r\n\r\n\r\n###############################################################################################################################################################################################\r\n### Problem: 2x1 - 3x2 -> min\r\n### 2x1 + x2 <= 3 -----> 2x1 + x2 + s = 3, s<=3\r\n### x1 + x2 = 1\r\n### x1, x2 - bin; s - int -> s = 2s1 + s2, s1,s2 - bin\r\n### H = 2x1 - 3x2 + P1*(2x1 + x2 + 2s1 + s2 - 3)^2 + P2*(x1 + x2 - 1)^2\r\n\r\nx1,x2,s1,s2 = symbols('x1:3,s1:3')\r\n\r\nobj = Poly(2*x1 - 3*x2) # ----> min\r\nc1 = Poly(2*x1 + x2 + 2*s1 + s2 - 3) # constraint 1\r\nc2 = Poly(x1 + x2 - 1) # constraint 2\r\nP1 = 1 # penalty 1\r\nP2 = 1 # penalty 2\r\nH = obj + P1*c1**2 + P2*c2**2\r\n\r\n# reduce x**2 to x as x is binary\r\nH1 = reduce_squares(H, (x1,x2,s1,s2))\r\nQ = translate_indexes(H1)\r\n\r\nresponse = EmbeddingComposite(DWaveSamplerInstance).sample_qubo(Q, num_reads=1000)\r\nfor sample in response.data():\r\n print(sample[0], \"Energy: \", sample[1], \"Occurrences: \",sample[2])\r\n\r\n# with P=2 it gives wrong result\r\n\r\n\r\n################################################################################################################################\r\n# S O L V E R T Y P E S\r\n################################################################################################################################\r\n\r\nfrom dwave.cloud import Client\r\nclient = Client.from_config(token=sapi_token)\r\nclient.get_solvers() #[Solver(id='DW_2000Q_5'), Solver(id='DW_2000Q_2_1')]\r\nfrom dwave.system.samplers import DWaveSampler\r\nsampler = DWaveSampler(token = sapi_token, endpoint = dwave_url, solver = 'DW_2000Q_2_1')\r\nsampler.parameters\r\n\r\n################################################################################################################################\r\n# S I M U L A T O R\r\n################################################################################################################################\r\n\r\nimport dimod\r\n\r\n# cannot put no of repetitions\r\n#solver = dimod.ExactSolver().sample(bqm)\r\n#solver = dimod.SimulatedAnnealingSampler()\r\n#response = solver.sample_qubo(Q)\r\n\r\nbqm = dimod.BinaryQuadraticModel.from_qubo(Q)\r\n#response = dimod.ExactSolver().sample(bqm) # other solver simulator?\r\nresponse = dimod.SimulatedAnnealingSampler().sample(bqm, num_reads = 10)\r\n#for sample, energy, num_occurrences in response.data(['sample', 'energy', 'num_occurrences']):\r\n# print(\"sample: \", sample, \"energy: \", energy, \"num_occurences: \", num_occurrences)\r\n\r\n# rearrange the response\r\nresponse_df = pd.DataFrame([(str(sample), energy, num_occurrences) for sample, energy, num_occurrences in response.data(['sample', 'energy', 'num_occurrences'])])\r\nresponse_df.columns = ['sample', 'energy', 'num_occurrences']\r\nresponse_pv = response_df.pivot_table(index = ['sample','energy'], values = 'num_occurrences', aggfunc = sum)\r\nprint(response_pv.sort_values(by = 'num_occurrences', ascending = False))\r\n\r\n###############################################################################################################################################################################################\r\na0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12 = symbols('a0:13')\r\nb0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12 = symbols('b0:13')\r\n\r\nobj = Poly(2*(a0+2*a1+4*a2+8*a3+16*a4+32*a5+64*a6+128*a7+256*a8+512*a9+1024*a10+2048*a11+4096*a12) - b0+2*b1+4*b2+8*b3+16*b4+32*b5+64*b6+128*b7+256*b8+512*b9+1024*b10+2048*b11+4096*b12) # ----> min\r\nc1 = Poly(a0+2*a1+4*a2+8*a3+16*a4+32*a5+64*a6+128*a7+256*a8+512*a9+1024*a10+2048*a11+4096*a12 - 4000) # constraint 1\r\nc2 = Poly(b0+2*b1+4*b2+8*b3+16*b4+32*b5+64*b6+128*b7+256*b8+512*b9+1024*b10+2048*b11+4096*b12 - 4000) # constraint 2\r\nP1 = 10 # penalty 1\r\nP2 = 10 # penalty 2\r\nH = obj + P1*c1**2 + P2*c2**2\r\n\r\n# reduce x**2 to x as x is binary\r\nH1 = reduce_squares(H, (a0,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,b0,b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12))\r\nQ = translate_indexes(H1)\r\n\r\nresponse = EmbeddingComposite(DWaveSamplerInstance).sample_qubo(Q, num_reads=1000)\r\nfor sample in response.data():\r\n print(sample[0], \"Energy: \", sample[1], \"Occurrences: \",sample[2])\r\n","sub_path":"dwave scripts/dwave-4-integer_programming.py","file_name":"dwave-4-integer_programming.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"175144543","text":"minNumber=0\r\nmaxNumber=1000\r\n\r\ndef isPrime(x):\r\n count = 0\r\n for i in range(int(x/2)):\r\n if x % (i+1) == 0:\r\n count = count+1\r\n return count == 1\r\n\r\ndef getPrimes(minPrime, maxPrime):\r\n if(minPrimemaxNumber):\r\n print(\"Başlangıç ve bitiş değerleri 0-1000 aralığında olmalı!\")\r\n return ''\r\n primes = [i for i in range(minPrime,maxPrime) if isPrime(i)]\r\n return primes\r\n\r\ndef prime_first():\r\n return getPrimes(0, 501)\r\n\r\n\r\ndef prime_second():\r\n return getPrimes(501, 1000)\r\n\r\nprint(prime_first())\r\nprint(prime_second())","sub_path":"HomeWork/Day4.py","file_name":"Day4.py","file_ext":"py","file_size_in_byte":604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"437823058","text":"import numpy as np\r\nimport numpy.ma as ma\r\nfrom scipy.integrate import quad, dblquad, nquad\r\nfrom matplotlib import pyplot as plt\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nfrom scipy import integrate as intg\r\nimport random as rd\r\n\r\nclass Task(object):\r\n def __init__(self,AgentsConfig, InitializationConfig, FieldConfig, SimuConfig):\r\n self.field = Field(AgentsConfig, InitializationConfig, FieldConfig)\r\n self.dt = SimuConfig['dt']\r\n self.endTime = SimuConfig['endTime']\r\n self.fig = plt.figure()\r\n\r\n self.ax = self.fig.add_subplot(111)\r\n self.ax.grid(True)\r\n plt.draw()\r\n def run(self):\r\n for i in range(200):\r\n #### calculate velocities ####\r\n if self.field.isDeadLocked():\r\n if self.field.isReachedDestin():\r\n self.field.setDeadLckToFalse()\r\n else:\r\n pass\r\n if not(self.field.getIsDeadLck()):\r\n self.field.calculateVels()\r\n else:\r\n self.field.calculateVels()\r\n self.field.combVCol()\r\n\r\n #### move agents ####\r\n self.field.moveAgents(self.dt)\r\n self.field.calculateErr()\r\n #### plots ####\r\n plt.pause(0.01)\r\n self.ax.scatter(self.field.agents.getPos()[:, 0], self.field.agents.getPos()[:, 1])\r\n plt.draw()\r\n # self.field.plotErrMesh()\r\n # self.field.plotAgentPos()\r\n # plt.clf()\r\n print(self.field.getTotalErr())\r\n\r\nclass Agents(object):\r\n def __init__(self, AgentsConfig, InitializationConfig):\r\n self.numberOfAgents = AgentsConfig['numberOfAgents']\r\n self.MaxValue = AgentsConfig['MaxValue']\r\n self.r = AgentsConfig['r']\r\n self.rForCalculCapacity = self.r * 1.2\r\n self.degreeOfCostFunc = AgentsConfig['degreeOfCostFunc']\r\n self.InitialResolution = InitializationConfig['resolutionMesh']\r\n self.Velocities = np.zeros([self.numberOfAgents, 2])\r\n self.AgentPositions = np.zeros([self.numberOfAgents, 2])\r\n self.basicFunc = BasicFunctions()\r\n self.calInitCapacity()\r\n\r\n def moveAgents(self, dt):\r\n self.AgentPositions = self.Velocities * dt\r\n\r\n def setPos(self, pos):\r\n self.AgentPositions = pos\r\n def getPos(self):\r\n return self.AgentPositions\r\n\r\n def setVelos(self, vel):\r\n self.Velocities = vel\r\n def getVelos(self):\r\n return self.Velocities\r\n\r\n def getNumerOfAgents(self):\r\n return self.numberOfAgents\r\n\r\n def get_r(self):\r\n return self.r\r\n\r\n def calInitCapacity(self):\r\n step = 2 * self.rForCalculCapacity / self.InitialResolution\r\n X = np.arange(-self.rForCalculCapacity, self.rForCalculCapacity + 1e-5, step)\r\n Y = np.arange(-self.rForCalculCapacity, self.rForCalculCapacity + 1e-5, step)\r\n X, Y = np.meshgrid(X, Y)\r\n capacities, deriv_s = self.calCapacitiesMesh(X, Y)\r\n self.plotOneCapFunc(X, Y, capacities[0])\r\n print(\"totla capacity under the Effective function: \" , self.integrateCap())\r\n return capacities[0], deriv_s\r\n\r\n def plotOneCapFunc(self, X, Y, capacities):\r\n fig = plt.figure()\r\n ax = Axes3D(fig)\r\n ax.plot_surface(X, Y, capacities)\r\n plt.show()\r\n\r\n def integrateCap(self):\r\n return dblquad(lambda x,y: self.calCapacitiesPts([0, 0], x,y), -self.rForCalculCapacity,self.rForCalculCapacity,\r\n lambda y: -self.rForCalculCapacity,self.rForCalculCapacity)\r\n\r\n def calCapacitiesPts(self, pt, x, y):\r\n dist = self.basicFunc.distSquarePtToPt(pt, x, y)\r\n return (dist < self.r * self.r) * self.MaxValue / pow(self.r, 4) * pow(dist - self.r * self.r, 2)\r\n\r\n def calCapacitiesMesh(self, X, Y):\r\n dists = self.basicFunc.distSquarePtsToMesh(self.AgentPositions, X, Y)\r\n capacities = [(dist <= self.r * self.r) * self.MaxValue / pow(self.r, 4) * pow(dist - self.r * self.r, 2) for dist in dists]\r\n deriv_s = [(dist <= self.r * self.r) * 2 * self.MaxValue / pow(self.r, 4) * (dist - self.r * self.r) for dist in dists]\r\n return capacities, deriv_s\r\n\r\nclass Field(object):\r\n def __init__(self, AgentsConfig, InitializationConfig, FieldConfig):\r\n self.agents = Agents(AgentsConfig, InitializationConfig)\r\n step_x, step_y = FieldConfig['size_x'] / FieldConfig['resolution'], FieldConfig['size_y'] / FieldConfig['resolution']\r\n self.xMin, self.xMax = -FieldConfig['size_x'] / 2, FieldConfig['size_x'] / 2\r\n self.yMin, self.yMax = -FieldConfig['size_y'] / 2, FieldConfig['size_y'] / 2\r\n self.k_cov = FieldConfig['k_cov']\r\n self.k_col = FieldConfig['k_col']\r\n self.k_linear = FieldConfig['k_linear']\r\n self.R_col = self.agents.get_r() * 1.5\r\n self.r_col = self.agents.get_r() * 1.2\r\n # self.frame = plt.figure()\r\n # self.ax_mesh = self.frame.add_subplot(211, projection='3d')\r\n # self.ax_pos = self.frame.add_subplot(111)\r\n # self.ax_pos.grid(True)\r\n #\r\n # plt.tight_layout()\r\n # plt.draw()\r\n\r\n self.x = np.arange(self.xMin, self.xMax + 1e-5, step_x)\r\n self.y = np.arange(self.yMin, self.yMax + 1e-5, step_y)\r\n self.X, self.Y = np.meshgrid(self.x, self.y)\r\n self.MeshErr = FieldConfig['C_star'] * np.ones(self.X.shape)\r\n self.totalErr = FieldConfig['C_star'] * (self.xMax - self.xMin) * (self.yMax - self.yMin)\r\n self.totalErrBuffer = self.totalErr\r\n self.isDeadLck = False\r\n self.minDistPt = np.zeros([self.agents.getNumerOfAgents(), 2])\r\n self.randomInit()\r\n self.calculateErr()\r\n self.plotErrMesh()\r\n\r\n def randomInit(self):\r\n # randomly init the positions near the edge of the field\r\n dice = np.random.random_integers(1, 4 , [self.agents.numberOfAgents, ])\r\n pos = np.zeros([self.agents.numberOfAgents, 2])\r\n for i_dice in range(self.agents.numberOfAgents):\r\n if dice[i_dice] == 1:\r\n pos[i_dice] = [self.xMin + (2 * np.random.rand() - 1) * self.agents.r,\r\n self.yMin + np.random.rand() * (self.yMax - self.yMin)]\r\n elif dice[i_dice] == 2:\r\n pos[i_dice] = [self.xMax + (2 * np.random.rand() - 1) * self.agents.r,\r\n self.yMin + np.random.rand() * (self.yMax - self.yMin)]\r\n elif dice[i_dice] == 3:\r\n pos[i_dice] = [self.xMin + np.random.rand() * (self.xMax - self.xMin),\r\n self.yMin + (2 * np.random.rand() - 1) * self.agents.r]\r\n elif dice[i_dice] == 4:\r\n pos[i_dice] = [self.xMin + np.random.rand() * (self.xMax - self.xMin),\r\n self.yMax + (2 * np.random.rand() - 1) * self.agents.r]\r\n\r\n self.agents.setPos(pos)\r\n return True\r\n\r\n def calculateErr(self):\r\n for i_capacity in self.agents.calCapacitiesMesh(self.X, self.Y)[0]:\r\n self.MeshErr = self.MeshErr - i_capacity\r\n self.MeshErr[self.MeshErr < 0] = 0\r\n\r\n def getTotalErr(self):\r\n self.totalErrBuffer = self.totalErr\r\n self.totalErr = intg.trapz(intg.trapz(self.MeshErr,self.x),self.y)\r\n return self.totalErr\r\n\r\n def isDeadLocked(self):\r\n self.isDeadLck = self.totalErr - self.totalErrBuffer <= 1e-4\r\n return self.getIsDeadLck()\r\n\r\n def getIsDeadLck(self):\r\n return self.isDeadLck\r\n def setDeadLckToFalse(self):\r\n self.isDeadLck = False\r\n def findNewDestInDeadLck(self):\r\n pts = self.agents.getPos()\r\n dists = np.array(self.agents.basicFunc.distSquarePtsToMesh(pts, self.X, self.Y))\r\n x = self.X.reshape(-1)\r\n y = self.X.reshape(-1)\r\n ds = dists.reshape(self.agents.getNumerOfAgents(), -1)\r\n err = self.MeshErr.reshape(-1)\r\n mask = (err <= 0)\r\n\r\n d_arrays = [[ma.array(d, mask=mask)] for d in ds]\r\n min_dists = [ma.min(d) for d in d_arrays]\r\n ds_list = [d.tolist() for d in ds]\r\n x = x.tolist()\r\n y = y.tolist()\r\n min_indxs = []\r\n for i in range(len(ds_list)):\r\n min_indxs.append(ds_list[i].index(min_dists[i]))\r\n self.minDistPt = [[x[i_minIndx], y[i_minIndx]] for i_minIndx in min_indxs]\r\n\r\n def isReachedDestin(self):\r\n return np.sum(np.sum(np.abs(self.agents.getPos() - self.minDistPt), axis=1)\\\r\n < self.agents.get_r() * self.agents.get_r()) == self.agents.getNumerOfAgents()\r\n def calVelDeadLck(self):\r\n self.findNewDestInDeadLck()\r\n v_tmp = -self.k_linear * (self.agents.getPos() - self.minDistPt)\r\n self.agents.setVelos(v_tmp)\r\n\r\n # def GiveIntegFuncVel(self, x, y):\r\n def calculateVels(self):\r\n diffVec_x, diffVec_y = self.agents.basicFunc.diffVecMesh(self.agents.AgentPositions, self.X, self.Y)\r\n capacities, derivs = self.agents.calCapacitiesMesh(X=self.X, Y=self.Y)\r\n dervCostFunc = self.agents.basicFunc.dervCostFunction(self.agents.degreeOfCostFunc, self.MeshErr)\r\n dists = self.agents.basicFunc.distSquarePtsToMesh(self.agents.AgentPositions, self.X, self.Y)\r\n\r\n ElemToInteg_x = [(dists[i] < self.agents.r * self.agents.r) * derivs[i] * dervCostFunc * diffVec_x[i]\r\n for i in range(self.agents.getNumerOfAgents())]\r\n ElemToInteg_y = [(dists[i] < self.agents.r * self.agents.r) * derivs[i] * dervCostFunc * diffVec_y[i]\r\n for i in range(self.agents.getNumerOfAgents())]\r\n v_x = intg.trapz(intg.trapz(ElemToInteg_x, self.x), self.y)\r\n v_y = intg.trapz(intg.trapz(ElemToInteg_y, self.x), self.y)\r\n velocities_new = self.k_cov * np.array([[v_x[i_agent],v_y[i_agent]] for i_agent in range(self.agents.getNumerOfAgents())])\r\n self.agents.setVelos(velocities_new)\r\n return\r\n\r\n\r\n\r\n def calColAvoidVel(self):\r\n agent_x, agent_y = [[x] for x in self.agents.getPos()[:, 0]], [[y] for y in self.agents.getPos()[:, 1]]\r\n\r\n diff_dist_x, diff_dist_y = np.transpose(agent_x) - agent_x, np.transpose(agent_y) - agent_y\r\n diff_dist_x_sq, diff_dist_y_sq = diff_dist_x * diff_dist_x, diff_dist_y * diff_dist_y\r\n\r\n diff_dist = np.sqrt(diff_dist_x_sq + diff_dist_y_sq)\r\n diff_dist_sq = diff_dist * diff_dist\r\n\r\n isInRange = (diff_dist < self.R_col) * (diff_dist > self.r_col)\r\n\r\n coeff = 4 * (self.R_col * self.R_col - self.r_col * self.r_col) * (diff_dist_sq - self.R_col * self.R_col)\\\r\n / pow((diff_dist_sq - self.r_col * self.r_col), 3) * isInRange\r\n v_x = np.sum(coeff * diff_dist_x)\r\n v_y = np.sum(coeff * diff_dist_y)\r\n\r\n return -self.k_col * np.array([v_x, v_y])\r\n\r\n def combVCol(self):\r\n v_tmp = self.agents.getVelos()\r\n v_tmp += self.calColAvoidVel()\r\n self.agents.setVelos(v_tmp)\r\n return\r\n\r\n def plotErrMesh(self):\r\n # self.ax_mesh.clear()\r\n # self.ax_mesh.plot_surface(self.X, self.Y, self.MeshErr)\r\n # self.frame.colorbar(surf, shrink=0.5, aspect=5)\r\n plt.draw()\r\n\r\n def plotAgentPos(self):\r\n # self.ax_pos.scatter(self.agents.getPos()[:, 0], self.agents.getPos()[:, 1])\r\n # plt.draw()\r\n return\r\n\r\n def moveAgents(self, dt):\r\n self.agents.moveAgents(dt)\r\n\r\nclass Results(object):\r\n def __init__(self):\r\n self.err_time = []\r\n self.velocities_time = []\r\n self.positions_time = []\r\n self.mesh_diff = []\r\n\r\n def plotResults(self):\r\n pass\r\n def saveResults(self, filePath):\r\n pass\r\n def loadResults(self, filePath):\r\n pass\r\n\r\nclass BasicFunctions(object):\r\n def __init__(self):\r\n pass\r\n\r\n def distSquarePtToMesh(self, Pt, X, Y):\r\n return (Pt[0]-X)*(Pt[0]-X) + (Pt[1]-Y)*(Pt[1]-Y)\r\n\r\n def distSquarePtsToMesh(self, Pts, X, Y):\r\n res = [self.distSquarePtToMesh(i_Pt, X, Y) for i_Pt in Pts[:]]\r\n return res\r\n\r\n def distSquarePtToPt(self, Pt, x, y):\r\n return (Pt[0] - x) * (Pt[0] - x) + (Pt[1] - y) * (Pt[1] - y)\r\n\r\n def dervCostFunction(self, degree, ErrMesh):\r\n return (ErrMesh > 0) * degree * pow(ErrMesh, degree - 1)\r\n\r\n def diffVecMesh(self, Pts, X, Y):\r\n return [i_Pt[0] - X for i_Pt in Pts], [i_Pt[1] - Y for i_Pt in Pts]\r\n\r\n def diffVecPt(self, Pts, x, y):\r\n return [i_Pt[0] - x for i_Pt in Pts], [[i_Pt[1] - y for i_Pt in Pts[:]]]\r\n","sub_path":"pyProject/includes/taskDef.py","file_name":"taskDef.py","file_ext":"py","file_size_in_byte":12528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"631512493","text":"import torch\n\n\ni = torch.LongTensor([[0, 1, 1],\n [2, 0, 2]])\n\nv = torch.FloatTensor([3, 4, 5])\n\ntorch.sparse.FloatTensor(i, v, torch.Size([2,3])).to_dense()\n\n\n\na = torch.randn(2,3).to_sparse().requires_grad_()\na\nb = torch.randn(3,2,requires_grad=True)\nb\n\ny = torch.sparse.mm(a,b)\ny = torch.nn.Softmax(dim=-1)(y)\ny.sum().backward()\na.grad\n\nS = torch.sparse_coo_tensor(indices = torch.tensor([[0,0,1,2],[2,3,0,3]]), values = torch.tensor([1,2,1,3]), size=[3,4])","sub_path":"agent/test/sparse_tensor.py","file_name":"sparse_tensor.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"413032789","text":"import copy\nimport json\nimport sys\n\nfrom pkg_resources import resource_string, resource_listdir\n\nfrom installer.utils import resolve_platform, clean_json_str, fill_dict\n\n\n# noinspection PyPep8Naming\nclass BaseApplicationDetails:\n \"\"\"\n :type name: str\n :type version: str\n \"\"\"\n\n @classmethod\n def from_dict(cls, d):\n return cls(**d)\n\n def __init__(self, name, version):\n \"\"\"\n :type name: str\n :type version: str\n \"\"\"\n self.name = name\n self.version = version\n\n\n# noinspection PyPep8Naming\nclass TargetInstallationPlatform:\n \"\"\"\n :type identifier: str\n :type packageManagerInitCommands: list[str]\n :type packageManagerInstallationCommand: str\n :type requiredPlatformPackages: list[str]\n \"\"\"\n\n @classmethod\n def from_dict(cls, d):\n return cls(**d)\n\n def __init__(self, identifier, packageManagerInitCommands, packageManagerInstallationCommand,\n requiredPlatformPackages):\n \"\"\"\n :type identifier: str\n :type packageManagerInitCommands: list[str]\n :type packageManagerInstallationCommand: str\n :type requiredPlatformPackages: list[str]\n \"\"\"\n self.identifier = identifier\n self.packageManagerInitCommands = packageManagerInitCommands\n self.packageManagerInstallationCommand = packageManagerInstallationCommand\n self.requiredPlatformPackages = requiredPlatformPackages\n\n\n# noinspection PyPep8Naming\nclass SubInstallerConfiguration:\n \"\"\"\n :type installationCommand: str\n :type packageList: list[str]\n \"\"\"\n\n @classmethod\n def from_dict(cls, d):\n return cls(**d)\n\n def __init__(self, installationCommand, packageList):\n \"\"\"\n :type installationCommand: str\n :type packageList: list[str]\n \"\"\"\n self.installationCommand = installationCommand\n self.packageList = packageList\n\n\n# noinspection PyPep8Naming\nclass InstallerConfiguration:\n @classmethod\n def from_dict(cls, source_dict):\n platform = sys.platform\n\n d2 = copy.deepcopy(source_dict)\n if 'osx' in d2:\n d2.pop('osx')\n if 'linux' in d2:\n d2.pop('linux')\n\n if platform == 'darwin' and 'osx' in source_dict:\n k = source_dict['osx']\n d2.update(k)\n\n elif (platform == 'linux' or platform == 'linux2') and 'linux' in source_dict:\n distro = resolve_platform()\n\n l_d = copy.deepcopy(source_dict['linux'])\n target = copy.deepcopy(source_dict['linux'])\n\n if 'ubuntu' in target:\n target.pop('ubuntu')\n\n if distro in l_d:\n k = l_d[distro]\n target.update(k)\n\n d2.update(target)\n\n if 'subInstaller' in d2:\n d2['subInstaller'] = SubInstallerConfiguration.from_dict(d2['subInstaller'])\n else:\n d2['subInstaller'] = None\n\n if 'version' not in d2:\n d2['version'] = None\n if 'versionExtractionCommand' not in d2:\n d2['versionExtractionCommand'] = None\n if 'versionExtractionRegex' not in d2:\n d2['versionExtractionRegex'] = None\n if 'home' not in d2:\n d2['home'] = None\n if 'homeExportVariable' not in d2:\n d2['homeExportVariable'] = None\n if 'pathExports' not in d2:\n d2['pathExports'] = list()\n\n return cls(**d2)\n\n def __init__(self, identifier, setupCommands, requiredExecutables, homeExportRequired, pathExports,\n version, home, versionExtractionCommand, versionExtractionRegex, homeExportVariable,\n packageDependencies, subInstaller, sudoSetupCommands=None):\n \"\"\"\n :type identifier: str\n :type setupCommands: list[str]\n :type requiredExecutables: list[str]\n :type homeExportRequired: bool\n :type pathExports: list[str]\n :type version: str\n :type home: str\n :type versionExtractionCommand: str\n :type versionExtractionRegex: str\n :type homeExportVariable: str\n :type packageDependencies: list[str]\n :type subInstaller: SubInstallerConfiguration\n :type sudoSetupCommands: list[str]\n \"\"\"\n self.identifier = identifier\n self.version = version\n self.home = home\n self.versionExtractionCommand = versionExtractionCommand\n self.versionExtractionRegex = versionExtractionRegex\n self.setupCommands = setupCommands\n self.requiredExecutables = requiredExecutables\n self.pathExports = pathExports\n self.homeExportVariable = homeExportVariable\n self.homeExportRequired = homeExportRequired\n self.packageDependencies = [] if packageDependencies is None else packageDependencies\n self.subInstaller = subInstaller\n self.sudoSetupCommands = [] if sudoSetupCommands is None else sudoSetupCommands\n\n\n# noinspection PyPep8Naming\nclass InstallationConfiguration:\n @classmethod\n def from_dict(cls, d):\n \"\"\"\n :type d: dict[str]\n :rtype: InstallerConfiguration\n \"\"\"\n\n d2 = copy.deepcopy(d)\n target_installation_platforms = dict()\n for key in d['targetInstallationPlatforms']:\n target_installation_platforms[key] = \\\n TargetInstallationPlatform.from_dict(d['targetInstallationPlatforms'][key])\n d2['targetInstallationPlatforms'] = target_installation_platforms\n\n applications = list()\n for val in d['applications']:\n applications.append(InstallerConfiguration.from_dict(val))\n d2['applications'] = applications\n\n return cls(**d2)\n\n def __init__(self, installationRoot, tempDirectory, targetInstallationPlatforms, applications):\n \"\"\"\n :type installationRoot: str\n :type tempDirectory: str\n :type targetInstallationPlatforms: dict[str, TargetInstallationPlatform]\n :type applications: list[InstallerConfiguration]\n \"\"\"\n self.installationRoot = installationRoot\n self.tempDirectory = tempDirectory\n self.applications = applications\n self.targetInstallationPlatforms = targetInstallationPlatforms\n\n\ninstallation_configuration_d = None # type: dict\n\ninstallation_configuration = None # type: InstallationConfiguration\n\n\ndef init_configuration(installation_root, configuration_profile):\n \"\"\"\n :type installation_root: str\n :type configuration_profile: str\n \"\"\"\n global installation_configuration_d, installation_configuration\n\n basic_configuration_d = json.loads(clean_json_str(\n resource_string('installer.resources', 'installation_configuration.json')))\n\n if configuration_profile not in basic_configuration_d['configurationProfiles']:\n raise Exception(\"Invalid override value of '\" + configuration_profile + \"'! Valid values: \" +\n str(list(basic_configuration_d['configurationProfiles'].keys())))\n else:\n configuration_override_d = basic_configuration_d['configurationProfiles'][configuration_profile]\n basic_configuration_d.pop('configurationProfiles')\n basic_configuration_d.update(configuration_override_d)\n\n app_packages = list(filter(lambda x: not x.startswith('_') and x.endswith('.json'),\n resource_listdir('installer.resources.app_configurations', '')))\n\n for appIdentifier in basic_configuration_d['applicationIdentifiers']:\n if appIdentifier.startswith('__') or not appIdentifier + '.json' in app_packages:\n raise Exception(\"Invalid package name '\" + appIdentifier +\n \"' specified within configuration file! Valid values: \" +\n str(list(map(lambda x: x[0:-5], app_packages))))\n\n else:\n basic_configuration_d['applications'].append(json.loads(clean_json_str(\n resource_string('installer.resources.app_configurations', appIdentifier + \".json\")\n )))\n\n basic_configuration_d.pop(\"applicationIdentifiers\")\n\n installation_configuration_d = fill_dict(basic_configuration_d,\n {'installationRoot': installation_root,\n \"dataRoot\": '/dev/null',\n \"logFile\": \"/dev/null\",\n \"artifactRoot\": '/dev/null'\n })\n\n installation_configuration = InstallationConfiguration.from_dict(installation_configuration_d)\n\n\ndef get_configuration_profiles():\n \"\"\"\n :rtype: list[str]\n \"\"\"\n basic_configuration_d = json.loads(clean_json_str(\n resource_string('installer.resources', 'installation_configuration.json')))\n return list(basic_configuration_d['configurationProfiles'].keys())\n\n\nif __name__ == '__main__':\n init_configuration('/meh', \"phase2\")\n config = installation_configuration\n print('hi')\n","sub_path":"immortals_repo/shared/tools/installer/datatypes.py","file_name":"datatypes.py","file_ext":"py","file_size_in_byte":9023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"88768268","text":"import pandas as pd\nfrom torch.utils.data import DataLoader\nimport torch\nimport numpy as np\nimport torchvision.transforms as tt\n\nfrom vgg16 import VGG16\nfrom datasets import InferenceDataset, GDataset\nimport sys\n\n\ndef train_model(index, dir_, model_file=\"\", \n epochs=32, \n model_save=False, model_save_name=\"vgg16_iter\"):\n \"\"\" Training the model\n @param index: index file of the train data\n @param dir_: directory name that stores the properly formatted data\n @param model_file: model state file for continuous training\n @param epochs: number of iterations to run\n @param model_save: whether to save as a model file\n @param model_save_name: name of the saving model file\n \"\"\"\n \n df = pd.read_csv(index).sample(frac=0.1)\n dataset = GDataset(df, dir_)\n \n batch_size = 108\n dataloader = DataLoader(dataset, batch_size=batch_size)\n\n model = VGG16()\n \n if model_file != \"\":\n model.load_state_dict(torch.load(model_file))\n for param in model.features[:34].parameters():\n param.requires_grad = False\n \n model.cuda()\n \n criterion = torch.nn.CrossEntropyLoss()\n softmax = torch.nn.Softmax(dim=1)\n optimizer = torch.optim.Adam(model.parameters())\n\n # train the model\n for e in range(epochs):\n\n train_loss = 0\n accuracy = 0\n counter = 0\n for x, t in dataloader:\n counter += 1\n print(round(counter / len(dataloader) * 100, 2), \"% \", end=\"\\r\")\n x, t = x.cuda(), t.cuda()\n optimizer.zero_grad()\n z = model(x)\n loss = criterion(z, t)\n loss.backward()\n optimizer.step()\n train_loss += loss.item()\n\n y = softmax(z)\n top_p, top_class = y.topk(1, dim=1)\n accuracy += (top_class[:, 0] == t).sum().item()\n\n print(e, train_loss / len(dataloader), accuracy / len(dataset))\n if model_save:\n torch.save(model.state_dict(), model_save_name + str(e) +\".pth\")\n \n\n \n \ndef inference(index, dir_, model_file):\n \"\"\" Inferencing the model\n @param index: index file of the train data\n @param dir_: directory name that stores the properly formatted data\n @param model_file: model state file for continuous training\n \"\"\"\n df = pd.read_csv(index)\n dataset = InferenceDataset(df, dir_)\n \n model = VGG16()\n model.load_state_dict(torch.load(model_file))\n model.cuda()\n model.eval()\n\n criterion = torch.nn.CrossEntropyLoss()\n softmax = torch.nn.Softmax(dim=1)\n transform = tt.Compose([\n tt.Resize((128, 128)),\n tt.ToTensor(),\n tt.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n ])\n\n loss_sum = 0\n accuracy = 0\n top_5_accuracy = 0\n counter = 0\n for x, t_cpu in dataset:\n counter += 1\n x_cpu = np.array(x)\n x, t = transform(x).unsqueeze(0).cuda(), t_cpu.unsqueeze(0).cuda()\n z = model(x)\n y = softmax(z)\n top_p, top_class = y.topk(5, dim=1)\n accuracy += (top_class[:, 0] == t).sum().item()\n top_5_accuracy += (top_class == t.unsqueeze(1).repeat(1, 5)).max(axis=1).values.sum().item()\n \n print(\"Top 1 Accuracy:\", accuracy / len(dataset))\n print(\"Top 5 accuracy:\", top_5_accuracy / len(dataset))\n \nif __name__ == \"__main__\":\n print(\"Loading dataset:\", sys.argv[2])\n print(\"Dataset folder:\", sys.argv[3])\n print(\"Model:\", sys.argv[4])\n mode = sys.argv[1]\n index = sys.argv[2]\n dir_ = sys.argv[3]\n model_file = sys.argv[4] if sys.argv[4] else \"\"\n if mode == \"inference\":\n inference(index, dir_, model_file)\n elif mode == \"train\":\n train_model(index, dir_, model_file=model_file, epochs=32, model_save=True)\n \n\n\n\n","sub_path":"run_model.py","file_name":"run_model.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"133761018","text":"# coding = utf-8\n\"\"\"\ncreate on : 2017/12/13\nproject name : NLP_100\nfile name : problem_no_53 \n\nThis problem using nlp.txt\nThis file is available at \"http://www.cl.ecei.tohoku.ac.jp/nlp100/\".\nThis file NOT include this repository.\nIf you need file, please get above web site.\n\nproblem : Stanford Core NLPを用い,入力テキストの解析結果をXML形式で得よ.\n また,このXMLファイルを読み込み,入力テキストを1行1単語の形式で出力せよ.\n\"\"\"\nfrom bs4 import BeautifulSoup\n\n\ndef get_nlp_soup():\n \"\"\" read tokenize result xml to BeautifulSoup Class\n\n :return: tokenize result BeautifulSoup Class\n \"\"\"\n\n with open(\"./nlp.txt.xml\", mode=\"r\") as f:\n xml = f.read()\n\n soup = BeautifulSoup(xml, \"xml\")\n\n return soup\n\n\ndef problem_no_53():\n \"\"\" tokenize nlp.txt to get result on xml format by Stanford NLP Core,\n and read xml output result get tokenize word.\n\n :return: tokenize words\n \"\"\"\n\n soup = get_nlp_soup()\n\n words_list = [word.string for word in soup.find_all(\"word\")]\n\n word = \"\\n\".join(words_list)\n\n return word\n\n\nif __name__ == \"__main__\":\n print(problem_no_53())\n","sub_path":"codes/chapter_06/problem_no_53.py","file_name":"problem_no_53.py","file_ext":"py","file_size_in_byte":1176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"150531988","text":"import numpy as np\nimport math\nimport cv2\n\n\nclass Q1:\n def __init__(self):\n self.ImageData = self.normalize_to_0to1(self.loadImage_data())\n\n def loadImage_data(self):\n return np.loadtxt(\"../2_1.asc\")\n\n def normalize_to_0to1(self, imageData):\n return imageData / 255\n\n def showImage(self, ImageName, ImageData):\n cv2.imshow(ImageName, ImageData)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def Part_a_i(self, ImageData):\n rows, columns = np.shape(ImageData)\n return ImageData[0:rows:4, 0:columns:4]\n\n def Part_a_ii(self, ImageData):\n # finding rows and columns of the given image data\n rows, columns = np.shape(ImageData)\n\n # now lets calculate the average of 4x4 area and add it to our matrix\n rows_select = [x * 4 for x in range(0, int(rows / 4) + 1)]\n columns_select = [x * 4 for x in range(0, int(columns / 4) + 1)]\n\n average_array = []\n\n for x in range(len(rows_select) - 1):\n for y in range(len(columns_select) - 1):\n average_array.append(\n np.mean(ImageData[rows_select[x]:rows_select[x + 1], columns_select[y]:columns_select[y + 1]]))\n\n # convert list to np array\n new_array = np.array(average_array)\n\n # reshape it to 4 times smaller matrix\n return new_array.reshape(int(rows / 4), int(columns / 4))\n\n def Part_b_i(self, ImageData, Enlarge):\n # finding rows and columns of the given image data\n rows, columns = np.shape(ImageData)\n\n # lets create a list\n Elements_to_repeat = []\n\n # horizontally adding more pixels\n for x in range(rows):\n temp = []\n for y in range(columns):\n for z in range(Enlarge):\n temp.append(ImageData[x][y])\n Elements_to_repeat.append(temp)\n\n Enlarged_image_data = []\n\n # Vertically adding more pixels\n for x in Elements_to_repeat:\n for y in range(Enlarge):\n Enlarged_image_data.append(x)\n\n return np.array(Enlarged_image_data)\n\n def Part_b_ii(self, image, Enlarge):\n # Getting Original image height and width\n img_height, img_width = image.shape\n\n # Calculating height and width of the enlarged image using the passed in Enlarge factor\n new_height, new_width = img_height * Enlarge, img_width * Enlarge\n\n # lets create an empty NxM matrix for the dimensions of the enlarged image\n enlarged_imge_data = np.empty([new_height, new_width])\n\n # Calculating x and y ratios\n Xratio = float(img_width - 1) / (new_width - 1) if new_width > 1 else 0\n Yratio = float(img_height - 1) / (new_height - 1) if new_height > 1 else 0\n\n # Performing Bilinear interpolation\n for x in range(new_height):\n for y in range(new_width):\n x_l, y_l = math.floor(Xratio * y), math.floor(Yratio * x)\n x_h, y_h = math.ceil(Xratio * y), math.ceil(Yratio * x)\n\n Xweight, Yweight = (Xratio * y) - x_l, (Yratio * x) - y_l\n\n a, b, c, d = image[y_l, x_l], image[y_l, x_h], image[y_h, x_l], image[y_h, x_h]\n\n pixel = a * (1 - Xweight) * (1 - Yweight) + b * Xweight * (1 - Yweight) + c * Yweight * (1 - Xweight) + d * Xweight * Yweight\n\n enlarged_imge_data[x][y] = pixel\n\n return enlarged_imge_data\n\n\ndef main():\n Q1_ = Q1()\n\n # Part a i\n Y1 = Q1_.Part_a_i(Q1_.ImageData)\n Q1_.showImage(\"Y1\", Y1)\n\n # Part a_ii\n Y2 = Q1_.Part_a_ii(Q1_.ImageData)\n Q1_.showImage(\"Y2\", Y2)\n\n # Part b_i\n Q1_.showImage(\"Blocky Enlarged Image\", Q1_.Part_b_i(Y1, 4))\n\n # Part b_ii\n Q1_.showImage(\"Enlarged Image using Bilinear Interpolation \", Q1_.Part_b_ii(Y1, 4))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"HW2/Q1/Q1.py","file_name":"Q1.py","file_ext":"py","file_size_in_byte":3859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"524701410","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n# vim:fenc=utf-8\n#\n# Copyright © 2018 qiang.zhou \n\nimport cv2\nimport numpy as np\n\n\"\"\" Put boxes on image, image and color should keep consist in channel dim.\n :image: Numpy array image in HxWxC.\n :box: Nx4 contains N boxes, it should in cross format, (minx, miny, maxx, maxy).\n :thickness: \n\"\"\"\ndef overlay_box(image, box, color=(255, 255, 255), thickness=1, lineType=8):\n if len(box.shape) == 1:\n box = np.array([box])\n for i_box in box:\n minx, miny, maxx, maxy = i_box\n cv2.rectangle(image, (int(minx), int(miny)), (int(maxx), int(maxy)), \\\n color=color, thickness=thickness, lineType=lineType)\n return image\n\n","sub_path":"codexamples/overlay_box.py","file_name":"overlay_box.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"225817463","text":"from hyperdash import Experiment\nfrom agent.trainer import Trainer\nfrom agent.util import EpsilonExponentialDecay\nfrom marlenv.goldmine.historic import GoldmineHRV\nfrom marlenv.util import GoldmineRecorder\nfrom agent.deepq.simple_dqn import SimpleDQN\n\nname = 'hrv_n2_v3_h10'\nexp = Experiment(name)\n\nagent_num = 6\ntask_num = 2\nview_range = 3\nmem_period = 10\nenv = GoldmineHRV(agent_num, task_num, view_range, mem_period)\nenv.seed(0)\n\nparams = {\n 'name' : name,\n 'episodes' : 30000,\n 'steps' : 200,\n 'no_op_episodes' : 100,\n 'epsilon' : EpsilonExponentialDecay(init=1.0, rate=0.9998),\n 'train_every' : 8,\n 'save_model_every' : 1000,\n 'is_centralized' : False,\n\n 'agent_num' : agent_num,\n 'env' : env,\n 'action_space' : env.action_space,\n 'observation_space' : env.observation_space,\n 'preprocess' : None,\n 'recorder' : GoldmineRecorder(agent_num),\n\n 'agent': [\n SimpleDQN(\n action_space = env.action_space,\n observation_space = env.observation_space,\n memory_size = 100000,\n batch_size = 256,\n learning_rate = 0.0002,\n gamma = 0.92,\n target_update = 100,\n use_dueling = False\n ) for _ in range(agent_num)\n ],\n\n 'hyperdash': exp\n}\n\ntrainer = Trainer(**params)\ntrainer.train()\n\nexp.end()\n","sub_path":"scripts/hrv_simple.py","file_name":"hrv_simple.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"142744102","text":"encontradas = []\nsecreto = []\ndigitadas = []\n\npalavra_secreta = 'PYTHON'\n\nfor p in palavra_secreta:\n secreto.append(\"_\")\n\ncont = 0\nprint(\"------------------------\")\nprint(\" JOGO DA FORCA \")\nprint(\"------------------------\")\n\n\nwhile True:\n print()\n print('A palavra é: ', end='')\n print(' '.join(secreto))\n print(f\"Letras digitadas: {' / '.join(digitadas)}\")\n letra = input(\"Digite uma letra: \").upper()\n\n if not letra.isnumeric() and len(letra) == 1:\n\n if letra not in palavra_secreta and letra not in digitadas:\n cont += 1\n print(f\"-> \\033[31mVocê errou pela {cont}ª vez. Tente novamente!\\033[0;0m\")\n\n if letra in digitadas:\n print(\"-> \\033[31mVocê já digitou essa letra!\\033[0;0m\")\n else:\n digitadas.append(letra)\n for pos, char in enumerate(palavra_secreta):\n if char == letra:\n encontradas.append(pos)\n secreto.pop(pos)\n secreto.insert(pos, palavra_secreta[pos])\n\n if len(palavra_secreta) == len(encontradas):\n print()\n print(f'A palavra secreta é {palavra_secreta}')\n print(\"Você VENCEU!!! Parabéns !!!\")\n break\n elif cont == 7:\n print()\n print(\"Você PERDEU!!! Tente novamente.\")\n break\n else:\n if letra.isnumeric():\n print(f\"-> \\033[31mDigite apenas letras.\\033[0;0m\")\n elif letra == '':\n print(f\"-> \\033[31mVocê precisar digitar algo.\\033[0;0m\")\n elif letra != 1:\n print(f\"-> \\033[31mDigite apenas uma letra por vez.\\033[0;0m\")\n\n\n\n","sub_path":"jogodaforca.py","file_name":"jogodaforca.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"468364333","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 18-5-20 下午2:31\n# @Author : 闫继龙\n# @File : jidong_code.py\n# @Software: PyCharm\n\nfrom selenium import webdriver\nimport numpy as np\nimport time\n\nbrowser = webdriver.Chrome()\nbrowser.set_page_load_timeout(30)\n\n# 1.查看多少页面\nbrowser.get(\n 'https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&wq=%E6%89%8B%E6%9C%BA&pvid=8c843bd7216f4f6eaff661b402cb7b51')\n\npages_count = browser.find_element_by_css_selector('#J_bottomPage > span.p-skip > em:nth-child(1) > b')\npages = int(pages_count.text)\nprint('共有商品 %d 页' % pages)\n\n# 2. 抓取每页数据\nfor i in range(5):\n print('当前第 %d 页' % (i + 1))\n url = 'https://search.jd.com/Search?keyword=%E6%89%8B%E6%9C%BA&enc=utf-8&qrst=1&rt=1&stop=1&vt=2&wq=%E6%89%8B%E6%9C%BA&cid2=653&cid3=655&page=' \\\n + str((1 + 2 * (i - 1))) + '&s=232&click=0'\n browser.get(url)\n\n # 模拟页面滚动,获取动态数据\n browser.execute_script('window.scrollTo(0,document.body.scrollHeight);')\n time.sleep(1)\n\n goods = browser.find_element_by_css_selector('#J_goodsList > ul').find_elements_by_class_name('gl-item')\n print('第 %d 页,有 %d 件商品' % ((i + 1), len(goods)))\n\n # 获取每页每件商品信息\n for i in np.arange(len(goods)):\n good = goods[i]\n\n try:\n name = browser.find_element_by_css_selector(\n 'li:nth-child(' + str(i + 1) + ') > div > div.p-name.p-name-type-2 > a > em').text\n price = browser.find_element_by_css_selector(\n 'li:nth-child(' + str(i + 1) + ') > div > div.p-price > strong > i').text\n print('商品序号:%d, 商品名称:%s, 商品价格:%s' % (i, name, price))\n except:\n print(good.text)\n","sub_path":"browser_creeper/jidong_code.py","file_name":"jidong_code.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"240267526","text":"## Bulk image resizer\n# Usage: place this script in a folder of images you want to shrink,\n# and then run it.\n\nimport numpy as np\nimport cv2, os\nfrom PIL import Image, ExifTags\nimport traceback, functools\nfrom math import floor\n\ndir_path = os.getcwd() + \"\\playdohRaw\"\nprint(dir_path)\nclass_name = 'PLAYDOH'\nos.mkdir('resized')\n \nfor filename in os.listdir(dir_path):\n # If the images are not .JPG images, change the line below to match the image type.\n if filename.endswith(\".jpg\"):\n img = Image.open(filename)\n \n width, height = img.size\n if width > height: \n basewidth = 720\n new_height = floor(basewidth * height / width)\n\n img = img.resize((basewidth, new_height), Image.ANTIALIAS)\n else:\n baseheight = 720\n new_width = floor(baseheight * width / height)\n img = img.resize((new_width, baseheight), Image.ANTIALIAS)\n\n img.save('resized/' + class_name + '_' + str(idx+1).zfill(3) + '.jpg')\n\n\n \n\n \n \n \n","sub_path":"scripts/resizer.py","file_name":"resizer.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"401284802","text":"from collections import deque\n\nnum = int(input())\n\nfor i in range(num):\n # n = 문서 수, m = 몇번째로 인쇄되는지 궁금한 문서 인덱스\n n, m = map(int, input().split())\n # 중요도 입력받기\n queue = deque(map(int, input().split()))\n target = [0] * len(queue)\n target[m] = 1\n count = 0\n\n if n == 1:\n print(\"1\")\n else:\n while queue:\n if queue[0] < max(queue):\n queue.append(queue[0])\n queue.popleft()\n target.append(target.pop(0))\n elif queue[0] == max(queue):\n val = queue.popleft()\n count += 1\n if target.pop(0) == 1:\n break\n print(count)\n","sub_path":"BOJ/BJ_1966.py","file_name":"BJ_1966.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"279955384","text":"# coding: utf-8\n\nimport json\nimport lib.post\nimport mock\nimport report\nimport unittest\nimport urllib\nimport urllib2\n\nclass TestPost(unittest.TestCase):\n def setUp(self):\n self.data = {\n 'created_at': '0000-00-00T00:00:00Z',\n 'headline': 'fake headline',\n 'published_at': '0000-00-00T00:00:00Z',\n 'updated_at': '0000-00-00T00:00:00Z'\n }\n\n reload(lib.post)\n\n json.loads = mock.Noop(return_value = {'status': True})\n urllib.urlencode = mock.Noop()\n urllib2.Request = mock.Noop()\n urllib2.urlopen = mock.Noop(return_value = mock.Noop())\n\n def test_should_raise_when_created_at_is_missing(self):\n del self.data['created_at']\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_headline_is_missing(self):\n del self.data['headline']\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_published_at_is_missing(self):\n del self.data['published_at']\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_updated_at_is_missing(self):\n del self.data['updated_at']\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_set_default_values_for_missing_keys(self):\n expected_data = {\n 'allow_comments': True,\n 'article_body': '',\n 'created_at': '0000-00-00T00:00:00Z',\n 'deck': '',\n 'editor_email': '',\n 'editor_image_id': '',\n 'editor_name': '',\n 'featured': False,\n 'featured_image_id': '',\n 'featured_image_legend': '',\n 'headline': 'fake headline',\n 'keywords': '',\n 'published_at': '0000-00-00T00:00:00Z',\n 'section': '',\n 'site': '',\n 'support_line': '',\n 'updated_at': '0000-00-00T00:00:00Z',\n 'usercreated': ''\n }\n\n lib.post.post(self.data)\n arguments, keyword_arguments = urllib.urlencode.called_with\n returned_data = arguments[0]\n\n self.assertDictEqual(expected_data, returned_data)\n\n def test_should_raise_when_service_returns_false_as_status(self):\n json.loads = mock.Noop(return_value = {'status': False})\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_service_returns_nothing(self):\n json.loads = mock.Noop(return_value = '')\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_raise_when_service_returns_false_as_status(self):\n json.loads = mock.Noop(return_value = {'status': False})\n self.assertRaises(lib.post.PostError, lib.post.post, self.data)\n\n def test_should_return_the_service_response_when_ok(self):\n expected_data = {\n 'status': True\n }\n\n returned_data = lib.post.post(self.data)\n self.assertDictEqual(expected_data, returned_data)\n","sub_path":"test/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":2792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"355448631","text":"import sys\nimport re\nimport os\nimport subprocess\n\nwork_dir = \"./build/times/\"\ncompiler_logs = open(work_dir + \"times_logs.txt\", \"w\")\n\n\ndef try_compile():\n p = subprocess.call([\"g++\", \"-c\", \"main.cpp\"], cwd=work_dir, stdout=compiler_logs, stderr=compiler_logs)\n return p == 0\n\ndef extension(file):\n return file.split(\".\")[-1]\n \n\ndef process_file(fullname):\n with open(work_dir + \"main.cpp\", \"w\") as f:\n f.write(\"#include <\" + fullname + \">\")\n f.write(\"\"\"\n \n int main() {}\n \"\"\")\n if not try_compile():\n print(\"Unable to compile\", fullname)\n quit()\n\n \n \ndef process_files(folders):\n for proj in folders:\n for root, dirs, files in os.walk(proj):\n for file in files:\n if extension(file) not in {\"h\", \"cpp\"}:\n continue\n fullname = root + \"/\" + file\n \n print(\"Starting\", file)\n \n process_file(fullname)\n \n print(file, \"Done\")\n print()\n \n\nprojects = {\"y\", \"yave\", \"editor\"}\n\nprocess_files(projects)","sub_path":"times.py","file_name":"times.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"534211986","text":"\"\"\"\n*****************************************************************\nLicensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2020. All Rights Reserved.\nUS Government Users Restricted Rights - Use, duplication or\ndisclosure restricted by GSA ADP Schedule Contract with IBM Corp.\n*****************************************************************\n\"\"\"\n\nimport os\nimport argparse\nimport sys\nimport subprocess\nfrom enum import Enum, unique\nfrom itertools import product\nimport pkg_resources\n\nDEFAULT_BUILD_TYPES = \"cpu,cuda\"\nDEFAULT_PYTHON_VERS = \"3.6\"\nDEFAULT_MPI_TYPES = \"openmpi\"\nDEFAULT_CONDA_BUILD_CONFIG = os.path.join(os.path.dirname(__file__),\n \"..\", \"conda_build_config.yaml\")\nDEFAULT_GIT_LOCATION = \"https://github.com/open-ce\"\nSUPPORTED_GIT_PROTOCOLS = [\"https:\", \"http:\", \"git@\"]\nDEFAULT_RECIPE_CONFIG_FILE = \"config/build-config.yaml\"\nDEFAULT_OUTPUT_FOLDER = \"condabuild\"\n\nclass OpenCEError(Exception):\n \"\"\"\n Exception class for errors that occur in an Open-CE tool.\n \"\"\"\n def __init__(self, msg):\n super().__init__(msg)\n self.msg = msg\n\nclass OpenCEFormatter(argparse.ArgumentDefaultsHelpFormatter):\n \"\"\"\n Default help text formatter class used within Open-CE.\n Allows the use of raw text argument descriptions by\n prepending 'R|' to the description text.\n \"\"\"\n def _split_lines(self, text, width):\n if text.startswith('R|'):\n return text[2:].splitlines()\n return super()._split_lines(text, width)\n\n@unique\nclass Argument(Enum):\n '''Enum for Arguments'''\n CONDA_BUILD_CONFIG = (lambda parser: parser.add_argument(\n '--conda_build_config',\n type=str,\n default=DEFAULT_CONDA_BUILD_CONFIG,\n help='Location of conda_build_config.yaml file.' ))\n\n OUTPUT_FOLDER = (lambda parser: parser.add_argument(\n '--output_folder',\n type=str,\n default=DEFAULT_OUTPUT_FOLDER,\n help='Path where built conda packages will be saved.'))\n\n CHANNELS = (lambda parser: parser.add_argument(\n '--channels',\n dest='channels_list',\n action='append',\n type=str,\n default=list(),\n help='Conda channels to be used.'))\n\n ENV_FILE = (lambda parser: parser.add_argument(\n 'env_config_file',\n nargs='+',\n type=str,\n help=\"Environment config file. This should be a YAML file \"\n \"describing the package environment you wish to build. A collection \"\n \"of files exist under the envs directory.\"))\n\n REPOSITORY_FOLDER = (lambda parser: parser.add_argument(\n '--repository_folder',\n type=str,\n default=\"\",\n help=\"Directory that contains the repositories. If the \"\n \"repositories don't exist locally, they will be \"\n \"downloaded from OpenCE's git repository. If no value is provided, \"\n \"repositories will be downloaded to the current working directory.\"))\n\n PYTHON_VERSIONS = (lambda parser: parser.add_argument(\n '--python_versions',\n type=str,\n default=DEFAULT_PYTHON_VERS,\n help='Comma delimited list of python versions to build for '\n ', such as \"3.6\" or \"3.7\".'))\n\n BUILD_TYPES = (lambda parser: parser.add_argument(\n '--build_types',\n type=str,\n default=DEFAULT_BUILD_TYPES,\n help='Comma delimited list of build types, such as \"cpu\" or \"cuda\".'))\n\n MPI_TYPES = (lambda parser: parser.add_argument(\n '--mpi_types',\n type=str,\n default=DEFAULT_MPI_TYPES,\n help='Comma delimited list of mpi types, such as \"openmpi\" or \"system\".'))\n\n DOCKER_BUILD = (lambda parser: parser.add_argument(\n '--docker_build',\n action='store_true',\n help=\"Perform a build within a docker container. \"\n \"NOTE: When the --docker_build flag is used, all arguments with paths \"\n \"should be relative to the directory containing open-ce. Only files \"\n \"within the open-ce directory and local_files will be visible at \"\n \"build time.\"))\n\ndef make_parser(arguments, *args, formatter_class=OpenCEFormatter, **kwargs):\n '''\n Make a parser from a list of OPEN-CE Arguments.\n '''\n parser = argparse.ArgumentParser(*args, formatter_class=formatter_class, **kwargs)\n for argument in arguments:\n argument(parser)\n return parser\n\ndef parse_arg_list(arg_list):\n ''' Turn a comma delimited string into a python list'''\n if isinstance(arg_list, list):\n return arg_list\n return arg_list.split(\",\") if not arg_list is None else list()\n\ndef make_variants(python_versions=DEFAULT_PYTHON_VERS, build_types=DEFAULT_BUILD_TYPES, mpi_types=DEFAULT_MPI_TYPES):\n '''Create a cross product of possible variant combinations.'''\n variants = { 'python' : parse_arg_list(python_versions),\n 'build_type' : parse_arg_list(build_types),\n 'mpi_type' : parse_arg_list(mpi_types)}\n return [dict(zip(variants,y)) for y in product(*variants.values())]\n\ndef remove_version(package):\n '''Remove conda version from dependency.'''\n return package.split()[0].split(\"=\")[0]\n\ndef check_if_conda_build_exists():\n '''Checks if conda-build is installed and exits if it is not'''\n try:\n pkg_resources.get_distribution('conda-build')\n except pkg_resources.DistributionNotFound:\n print(\"Cannot find `conda_build`, please see https://github.com/open-ce/open-ce#requirements\"\n \" for a list of requirements.\")\n sys.exit(1)\n\ndef make_schema_type(data_type,required=False):\n '''Make a schema type tuple.'''\n return (data_type, required)\n\ndef validate_type(value, schema_type):\n '''Validate a single type instance against a schema type.'''\n if isinstance(schema_type, dict):\n validate_dict_schema(value, schema_type)\n else:\n if not isinstance(value, schema_type):\n raise OpenCEError(\"{} is not of expected type {}\".format(value, schema_type))\n\ndef validate_dict_schema(dictionary, schema):\n '''Recursively validate a dictionary's schema.'''\n for k, (schema_type, required) in schema.items():\n if k not in dictionary:\n if required:\n raise OpenCEError(\"Required key {} was not found in {}\".format(k, dictionary))\n continue\n if isinstance(schema_type, list):\n if dictionary[k] is not None: #Handle if the yaml file has an empty list for this key.\n validate_type(dictionary[k], list)\n for value in dictionary[k]:\n validate_type(value, schema_type[0])\n else:\n validate_type(dictionary[k], schema_type)\n for k in dictionary:\n if not k in schema:\n raise OpenCEError(\"Unexpected key {} was found in {}\".format(k, dictionary))\n\ndef run_and_log(command):\n '''Print a shell command and then execute it.'''\n print(\"--->{}\".format(command))\n return os.system(command)\n\ndef get_output(command):\n '''Print and execute a shell command and then return the output.'''\n print(\"--->{}\".format(command))\n return subprocess.check_output(command, shell=True).decode(\"utf-8\").strip()\n","sub_path":"open-ce/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"277543602","text":"import pandas as pd\nimport requests\nimport bs4\n\n\n# get Coonmarketcap slugs\ndf_cmc_load_coins = pd.read_csv('data/csv/cmc_load_coins.csv')\nlist_slugs = list(df_cmc_load_coins['website_slug'])\nlist_market_share = list()\n\n# get Coinmarketcap markets data\ni = 0\n\nfor item in list_slugs:\n try:\n url = 'https://coinmarketcap.com/currencies/' + item + '/#markets'\n res_markets = requests.get(url)\n soup = bs4.BeautifulSoup(res_markets.text, 'html.parser')\n name = soup.select('h1')[0].getText()\n name = name[:name.find('\\n',2)].strip()\n i += 1\n print(i, name)\n #crypto_share = fiat_share = btc_share = eth_share = usd_share = usdt_share = ckusd_share = eur_share = cny_share = jpy_share = krw_share = float()\n crypto_share = fiat_share = btc_share = eth_share = usd_share = usdt_share = ckusd_share = eur_share = cny_share = jpy_share = krw_share = 0\n largest_fiat_markets = str()\n i_fiat_markets = 0\n largest_crypto_markets = str()\n i_crypto_markets = 0\n try:\n for row in soup.findAll('table')[0].tbody.findAll('tr'):\n exchange = row.select('td')[1].getText().strip()\n pair = row.select('td')[2].getText().strip()\n volume = row.select('td')[3].getText().strip()\n if volume.startswith('*'):\n dollar_sign = volume.find('$')\n volume = volume[dollar_sign:]\n perc = row.select('td')[5].getText().strip()\n perc = float(perc[:-1])\n perc_string = str(perc)\n if '/BTC' in pair:\n if item == 'bitcoin':\n continue\n btc_share += perc\n crypto_share += perc\n if i_crypto_markets < 10:\n largest_crypto_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_crypto_markets += 1\n if '/ETH' in pair:\n if item == 'bitcoin':\n continue\n eth_share += perc\n crypto_share += perc\n if i_crypto_markets < 10:\n largest_crypto_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_crypto_markets += 1\n if '/USD' in pair and '/USDT' not in pair:\n usd_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/USDT' in pair:\n usdt_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/CKUSD' in pair:\n ckusd_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/EUR' in pair:\n eur_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/CNY' in pair:\n cny_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/JPY' in pair:\n jpy_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n if '/KRW' in pair:\n krw_share += perc\n fiat_share += perc\n if i_fiat_markets < 10:\n largest_fiat_markets += str(\n exchange + ' ' + pair + ' Vol: ' + volume + ' - ' + perc_string + '% || ')\n i_fiat_markets += 1\n except:\n pass\n print(largest_crypto_markets)\n print(largest_fiat_markets)\n list_market_share.append(\n [name, crypto_share, largest_crypto_markets, fiat_share, largest_fiat_markets, btc_share, eth_share,\n usd_share, usdt_share, ckusd_share, eur_share, cny_share, jpy_share, krw_share])\n except:\n pass\n df_market_shares = pd.DataFrame(list_market_share,\n columns=['name', 'BTC+ETH_pairs', 'Top_crypto_markets', 'Top_fiat_pairs',\n 'Top_fiat_markets', 'BTC_pairs', 'ETH_pairs', 'USD_pairs', 'USDT_pairs',\n 'CK.USDT_pairs', 'EUR_pairs', 'CNY_pairs', 'JPY_pairs', 'KRW_pairs'])\nprint(df_market_shares)\ndf_market_shares.to_csv('data/csv/cmc_load_markets.csv')","sub_path":"cmc_load_markets.py","file_name":"cmc_load_markets.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"129193200","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom __builtin__ import unicode\nfrom django.http import HttpResponseRedirect, Http404\nfrom django.shortcuts import HttpResponse, render_to_response, render\n\n# Create your views here.\nfrom django.template import RequestContext\n\nfrom api.blog_forms import BlogForm, TagForm\nfrom api.models import Author, Blog, Tag\n\n\ndef home_view(request):\n return render_to_response('blog_list.html')\n\n\ndef blog_filer_view(request, id=None):\n tags = Tag.objects.all()\n tag = Tag.objects.get(id=id)\n blogs = tag.blog_set.all()\n return render_to_response(\"blog_filter.html\",\n {\"blogs\": blogs, \"tag\": tag, \"tags\": tags})\n\n\ndef blog_add_view(request):\n if request.method == 'POST':\n form = BlogForm(request.POST)\n tag = TagForm(request.POST)\n if form.is_valid() and tag.is_valid():\n cd = form.cleaned_data\n cdtag = tag.cleaned_data\n tagname = cdtag['tag_name']\n for taglist in tagname.split():\n Tag.objects.get_or_create(tag_name=taglist.strip())\n title = cd['caption']\n author = Author.objects.get(id=1)\n content = cd['content']\n blog = Blog(caption=title, author=author, content=content)\n blog.save()\n for taglist in tagname.split():\n blog.tags.add(Tag.objects.get(tag_name=taglist.strip()))\n blog.save()\n id = Blog.objects.order_by('-publish_time')[0].id\n return HttpResponseRedirect('/blog/show/%s' % id)\n else:\n form = BlogForm()\n tag = TagForm(initial={'tag_name': 'notags'})\n return render_to_response('blog_add.html',\n {'form': form, 'tag': tag}, context_instance=RequestContext(request))\n\n\ndef blog_show_view(request, id):\n try:\n blog = Blog.objects.get(id=id)\n tags = Tag.objects.all()\n except Blog.DoesNotExist:\n raise Http404\n return render_to_response(\"blog_show.html\",\n {\"blog\": blog, \"tags\": tags},\n context_instance=RequestContext(request))\n\n\ndef blog_update_view(request, id):\n id = id\n if request.method == 'POST':\n form = BlogForm(request.POST)\n tag = TagForm(request.POST)\n if form.is_valid() and tag.is_valid():\n cd = form.cleaned_data\n cdtag = tag.cleaned_data\n tagname = cdtag['tag_name']\n tagnamelist = tagname.split()\n for taglist in tagnamelist:\n Tag.objects.get_or_create(tag_name=taglist.strip())\n title = cd['caption']\n content = cd['content']\n blog = Blog.objects.get(id=id)\n if blog:\n blog.caption = title\n blog.content = content\n blog.save()\n for taglist in tagnamelist:\n blog.tags.add(Tag.objects.get(tag_name=taglist.strip()))\n blog.save()\n tags = blog.tags.all()\n for tagname in tags:\n tagname = unicode(str(tagname), \"utf-8\")\n if tagname not in tagnamelist:\n notag = blog.tags.get(tag_name=tagname)\n blog.tags.remove(notag)\n else:\n blog = Blog(caption=blog.caption, content=blog.content)\n blog.save()\n return HttpResponseRedirect('/blog/show/%s' % id)\n else:\n try:\n blog = Blog.objects.get(id=id)\n except Exception:\n raise Http404\n form = BlogForm(initial={'caption': blog.caption, 'content': blog.content}, auto_id=False)\n tags = blog.tags.all()\n if tags:\n taginit = ''\n for x in tags:\n taginit += str(x) + ' '\n tag = TagForm(initial={'tag_name': taginit})\n else:\n tag = TagForm()\n return render_to_response('blog_add.html',\n {'blog': blog, 'form': form, 'id': id, 'tag': tag},\n context_instance=RequestContext(request))\n\n\ndef blog_list_view(request):\n blogs = Blog.objects.order_by('-id')\n tags = Tag.objects.all()\n return render_to_response(\"blog_list.html\",\n {\"blogs\": blogs, \"tags\": tags, },\n context_instance=RequestContext(request))\n","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"79709755","text":"def prime(x):\n if(x>2):\n for i in range(2,x+1):\n for j in range(2,x//2 +1):\n if(x%j==0):\n return('{} is not a prime number.'.format(x))\n break\n elif(j==x//2):\n return('{} is a prime number.'.format(x))\n\nif __name__==\"__main__\":\n x=int(input(\"Enter a number: \"))\n result=prime(x)\n print(result)\n","sub_path":"funprime.py","file_name":"funprime.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"367067445","text":"import random\n\nimport numpy as np\n\n# reverse a matrix \n\n\nclass Board():\n def __init__(self):\n #print('in init')\n self.commands = {'up':self.up, 'down':self.down,'left':self.left,'right':self.right}\n self.history = []\n self.new_game()\n\n def new_game(self):\n matrix = []\n for i in range(4):\n matrix.append([0]*4)\n self.matrix = matrix\n self.temp_matrix = matrix\n self.add_two()\n self.add_two()\n self.history.append(self.matrix)\n\n def add_two(self):\n if self.game_state() == 2:\n a = random.randint(0, 3)\n b = random.randint(0, 3)\n while self.matrix[a][b] != 0:\n a = random.randint(0, 3)\n b = random.randint(0, 3)\n self.matrix[a][b] = 2\n #self.history.append(self.matrix)\n\n def numZeros(self):\n num = 0\n for i in range(4):\n for j in range(4):\n if self.matrix[i][j] == 0:\n num += 1\n return num\n\n def numNum(self,num):\n count = 0\n for i in range(4):\n for j in range(4):\n if self.matrix[i][j] == num:\n count += 1\n return count\n def symCount(self):\n count = 0\n num_zeros = 0\n for i in range(4):\n for j in range(4):\n if self.matrix[i][j] == self.matrix[j][i]:\n if self.matrix[i][j] != 0:\n if i != j:\n # print('new match')\n # print('i is :')\n # print(i)\n # print('j is :')\n # print(j)\n count += 1\n else:\n num_zeros += 1\n if self.matrix[i][j] == self.matrix[3-j][3-i]:\n if self.matrix[i][j] != 0:\n # print('new match')\n # print('i is :')\n # print(i)\n # print('j is :')\n # print(j)\n if i != 3-j:\n count += 1\n else:\n num_zeros += 1\n return count/2\n\n def game_state(self):\n mat = self.matrix\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n if mat[i][j] == 2048:\n # win\n return 1\n # check for any zero entries\n for i in range(len(mat)):\n for j in range(len(mat[0])):\n if mat[i][j] == 0:\n # not over\n return 2\n # check for same cells that touch each other\n for i in range(len(mat)-1):\n # intentionally reduced to check the row on the right and below\n # more elegant to use exceptions but most likely this will be their solution\n for j in range(len(mat[0])-1):\n if mat[i][j] == mat[i+1][j] or mat[i][j+1] == mat[i][j]:\n #not over\n return 2\n for k in range(len(mat)-1): # to check the left/right entries on the last row\n if mat[len(mat)-1][k] == mat[len(mat)-1][k+1]:\n #not over\n return 2\n for j in range(len(mat)-1): # check up/down entries on last column\n if mat[j][len(mat)-1] == mat[j+1][len(mat)-1]:\n #not over\n return 2\n #over \n return 0\n def reverse(self):\n mat = self.matrix\n new = []\n for i in range(len(mat)):\n new.append([])\n for j in range(len(mat[0])):\n new[i].append(mat[i][len(mat[0])-j-1]) \n self.matrix = new\n\n def transpose(self):\n mat = self.matrix\n new = []\n for i in range(len(mat[0])):\n new.append([])\n for j in range(len(mat)):\n new[i].append(mat[j][i])\n self.matrix = new\n\n def cover_up(self):\n self.temp_matrix = []\n mat = self.matrix\n for j in range(4):\n partial_new = []\n for i in range(4):\n partial_new.append(0)\n self.temp_matrix.append(partial_new)\n done = False\n for i in range(4):\n count = 0\n for j in range(4):\n if mat[i][j] != 0:\n self.temp_matrix[i][count] = mat[i][j]\n if j != count:\n done = True\n count += 1\n self.matrix = self.temp_matrix\n return done\n\n def merge(self, done):\n mat = self.matrix\n for i in range(4):\n for j in range(3):\n if mat[i][j] == mat[i][j+1] and mat[i][j] != 0:\n mat[i][j] *= 2\n mat[i][j+1] = 0\n done = True\n self.matrix = mat\n return done\n\n\n def up(self):\n \n self.transpose()\n done = self.cover_up()\n done = self.merge(done)\n self.cover_up()\n self.transpose()\n if done:\n self.add_two()\n self.history.append(self.matrix)\n return done\n\n def down(self):\n \n self.transpose()\n self.reverse()\n done = self.cover_up()\n done = self.merge(done)\n self.cover_up()\n self.reverse()\n self.transpose()\n if done:\n self.add_two()\n self.history.append(self.matrix)\n return done\n\n def left(self):\n \n done = self.cover_up()\n done = self.merge(done)\n self.cover_up()\n if done:\n self.add_two()\n self.history.append(self.matrix)\n return done \n\n def right(self):\n \n self.reverse()\n done = self.cover_up()\n done = self.merge(done)\n self.cover_up()\n self.reverse()\n if done:\n self.add_two()\n self.history.append(self.matrix)\n\n return done\n\n def follow_instr(self,inst):\n for i in range(len(inst)):\n print('in instructions')\n print(inst[i])\n self.commands[inst[i]]()\n\n\n\n def toString(self):\n list_as_array = np.array(self.matrix)\n print(list_as_array)\n\n def printHistory(self):\n \tfor i in range(len(self.history)):\n \t print(np.array(self.history[i]))\n\n\n\n","sub_path":"2048/board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":6474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"434788503","text":"'''\nSolution:\n1. The main idea is to add each node's value based on its parents' values and also based on its place value\n2. These can be done recursively or iteratively using a stack (DFS) or a queue (BFS)\n3. Return total sum if any of the nodes hits the leaf node.\n\n-- Passed all test cases on Leetcode successfully for all 3 Recursive, Iterative (Stack / Queue) approaches.\n\nTime Complexity: Recursive -- O(nodes), Iterative (Stack-DFS) -- O(nodes) and Iterative (Queue-BFS)-- O(nodes)\nSpace Complexity: Recursive -- O(height), Iterative (Stack-DFS) -- O(height) and Iterative (Queue-BFS)-- O(nodes)\n\n'''\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nfrom collections import deque\n\n\nclass SumRootToLeaf_Recursive(object):\n def __init__(self):\n self.totalSum = 0 # this needs to be updated and returned finally\n\n def __sumNumbers(self, root, value):\n # base cases\n if (root == None):\n return\n if (root.left == None and root.right == None):\n self.totalSum += (value * 10 + root.val)\n return\n\n # recursive calls by passing updated values using place value to the recursion calls.\n self.__sumNumbers(root.left, value * 10 + root.val)\n self.__sumNumbers(root.right, value * 10 + root.val)\n\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # call helper function\n self.__sumNumbers(root, 0)\n return self.totalSum\n\n\nclass SumRootToLeaf_Stack(object):\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # edge case check\n totalSum = 0\n if (root == None):\n return totalSum\n\n # initialize stack\n # each element in stack contains a node, count (0, 1 or 2 based on no. of children visited), current value\n stack = [[root, 0, 0]]\n\n while (len(stack) > 0):\n\n topNode = stack[-1][0]\n topValue = stack[-1][1]\n topCount = stack[-1][2]\n\n if (topCount == 0): # if none of the children is visted => count is 0\n stack[-1][2] += 1\n if (topNode.left != None):\n stack.append([topNode.left, topValue * 10 + topNode.val, 0]) # add left element to stack\n continue\n\n elif (topCount == 1): # if one of the children is visted => count is 1\n stack[-1][2] += 1\n if (topNode.right != None):\n stack.append([topNode.right, topValue * 10 + topNode.val, 0]) # add right element to stack\n continue\n\n elif (topCount == 2): # if both of the children is visted => count is 2\n if (topNode.left == None and topNode.right == None): # check for leaf node\n totalSum += (topValue * 10 + topNode.val)\n stack.pop()\n\n return totalSum\n\n\nclass SumRootToLeaf_Queue(object):\n def sumNumbers(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n # edge case check\n if (root == None):\n return 0\n\n totalSum = 0\n queue = deque([[root, 0]]) # initialize queue with node and current value till that node\n\n while (len(queue) > 0):\n\n front = queue.popleft()\n frontNode = front[0]\n frontValue = front[1]\n\n if frontNode.left == None and frontNode.right == None: # if leaf node, add it to the total sum\n totalSum += (frontValue * 10 + frontNode.val)\n\n if frontNode.left != None: # if left node not none, append it to the queue\n queue.append([frontNode.left, frontValue * 10 + frontNode.val])\n\n if frontNode.right != None: # if right node not none, append it to the queue\n queue.append([frontNode.right, frontValue * 10 + frontNode.val])\n\n return totalSum","sub_path":"SumRootToLeaf.py","file_name":"SumRootToLeaf.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"264500265","text":"#!/usr/bin/env python3\n#\n# Copyright 2016 Canonical 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\nimport json\nimport os\nimport sys\nimport uuid\nfrom subprocess import (\n check_call,\n)\n\nfrom charmhelpers.core.hookenv import (\n DEBUG,\n ERROR,\n Hooks,\n UnregisteredHookError,\n config,\n is_leader,\n leader_get,\n leader_set,\n local_unit,\n log,\n open_port,\n related_units,\n relation_get,\n relation_id,\n relation_ids,\n relation_set,\n status_set,\n unit_get,\n)\n\nfrom charmhelpers.core.host import (\n mkdir,\n service_reload,\n service_restart,\n)\n\nfrom charmhelpers.fetch import (\n apt_install,\n add_source,\n apt_update,\n filter_installed_packages,\n)\n\nfrom charmhelpers.contrib.openstack.utils import (\n configure_installation_source,\n openstack_upgrade_available,\n os_release,\n sync_db_with_multi_ipv6_addresses,\n is_unit_paused_set,\n pausable_restart_on_change as restart_on_change,\n CompareOpenStackReleases,\n series_upgrade_prepare,\n series_upgrade_complete,\n is_db_maintenance_mode,\n)\n\nfrom neutron_api_utils import (\n ADMIN_POLICY,\n CLUSTER_RES,\n NEUTRON_CONF,\n additional_install_locations,\n api_port,\n assess_status,\n check_local_db_actions_complete,\n determine_packages,\n determine_ports,\n do_openstack_upgrade,\n dvr_router_present,\n force_etcd_restart,\n is_api_ready,\n is_db_initialised,\n l3ha_router_present,\n manage_plugin,\n maybe_set_os_install_release,\n migrate_neutron_database,\n neutron_ready,\n pause_unit_helper,\n register_configs,\n remove_old_packages,\n restart_map,\n resume_unit_helper,\n services,\n setup_ipv6,\n)\nfrom neutron_api_context import (\n EtcdContext,\n IdentityServiceContext,\n NeutronApiSDNContext,\n NeutronCCContext,\n get_dns_domain,\n get_dvr,\n get_l2population,\n get_l3ha,\n get_overlay_network_type,\n is_fwaas_enabled,\n is_nfg_logging_enabled,\n is_nsg_logging_enabled,\n is_qos_requested_and_valid,\n is_port_forwarding_enabled,\n is_vlan_trunking_requested_and_valid,\n)\n\nfrom charmhelpers.contrib.hahelpers.cluster import (\n is_clustered,\n is_elected_leader,\n)\n\nfrom charmhelpers.contrib.openstack.ha.utils import (\n generate_ha_relation_data,\n)\n\nfrom charmhelpers.payload.execd import execd_preinstall\n\nfrom charmhelpers.contrib.openstack.ip import (\n canonical_url,\n PUBLIC, INTERNAL, ADMIN\n)\n\nfrom charmhelpers.contrib.openstack.neutron import (\n neutron_plugin_attribute,\n)\n\nfrom charmhelpers.contrib.network.ip import (\n get_relation_ip,\n)\n\nfrom charmhelpers.contrib.openstack.cert_utils import (\n get_certificate_request,\n process_certificates,\n)\n\nfrom charmhelpers.contrib.openstack.policyd import (\n maybe_do_policyd_overrides,\n maybe_do_policyd_overrides_on_config_changed,\n)\n\nfrom charmhelpers.contrib.openstack.context import ADDRESS_TYPES\n\nfrom charmhelpers.contrib.charmsupport import nrpe\nfrom charmhelpers.contrib.hardening.harden import harden\n\nhooks = Hooks()\nCONFIGS = register_configs()\n\n\ndef conditional_neutron_migration():\n \"\"\"Initialise neutron database if not already done so.\n\n Runs neutron-manage to initialize a new database or migrate existing and\n restarts services to ensure that the changes are picked up. The first\n (leader) unit to perform this action should have broadcast this information\n to its peers so first we check whether this has already occurred.\n \"\"\"\n if CompareOpenStackReleases(os_release('neutron-server')) <= 'icehouse':\n log('Not running neutron database migration as migrations are handled '\n 'by the neutron-server process.')\n return\n\n if not is_elected_leader(CLUSTER_RES):\n log('Not running neutron database migration, not leader')\n return\n\n allowed_units = relation_get('allowed_units')\n if not (allowed_units and local_unit() in allowed_units.split()):\n log('Not running neutron database migration, either no '\n 'allowed_units or this unit is not present')\n return\n\n migrate_neutron_database()\n\n\ndef configure_https():\n '''\n Enables SSL API Apache config if appropriate and kicks identity-service\n with any required api updates.\n '''\n # need to write all to ensure changes to the entire request pipeline\n # propagate (c-api, haprxy, apache)\n CONFIGS.write_all()\n if 'https' in CONFIGS.complete_contexts():\n cmd = ['a2ensite', 'openstack_https_frontend']\n check_call(cmd)\n else:\n cmd = ['a2dissite', 'openstack_https_frontend']\n check_call(cmd)\n\n # TODO: improve this by checking if local CN certs are available\n # first then checking reload status (see LP #1433114).\n if not is_unit_paused_set():\n service_reload('apache2', restart_on_failure=True)\n\n for rid in relation_ids('identity-service'):\n identity_joined(rid=rid)\n\n\n@hooks.hook('install')\n@harden()\ndef install():\n status_set('maintenance', 'Executing pre-install')\n execd_preinstall()\n openstack_origin = config('openstack-origin')\n configure_installation_source(openstack_origin)\n\n # Manage change of default configuration option values gated on\n # install-time OpenStack release\n maybe_set_os_install_release(openstack_origin)\n\n neutron_plugin = config('neutron-plugin')\n additional_install_locations(neutron_plugin, openstack_origin)\n\n add_source(config('extra-source'), config('extra-key'))\n status_set('maintenance', 'Installing apt packages')\n apt_update(fatal=True)\n # (ajkavanagh) LP: #1989538\n # Tactical fix to force openstack-release to match the configured\n # installation source; note that it comes after apt_update().\n apt_install(['openstack-release'], fatal=False, quiet=True)\n packages = determine_packages(openstack_origin)\n apt_install(packages, fatal=True)\n\n for port in determine_ports():\n open_port(port)\n\n if neutron_plugin == 'midonet':\n mkdir('/etc/neutron/plugins/midonet', owner='neutron', group='neutron',\n perms=0o755, force=False)\n # call the policy overrides handler which will install any policy overrides\n maybe_do_policyd_overrides(\n os_release('neutron-server'),\n 'neutron',\n restart_handler=lambda: service_restart('neutron-server'))\n\n\n@hooks.hook('vsd-rest-api-relation-joined')\n@restart_on_change(restart_map(), stopstart=True)\ndef relation_set_nuage_cms_name(rid=None):\n if CompareOpenStackReleases(os_release('neutron-server')) >= 'kilo':\n if config('vsd-cms-name') is None:\n e = \"Neutron Api hook failed as vsd-cms-name\" \\\n \" is not specified\"\n status_set('blocked', e)\n else:\n relation_data = {\n 'vsd-cms-name': '{}'.format(config('vsd-cms-name'))\n }\n relation_set(relation_id=rid, **relation_data)\n\n\n@hooks.hook('vsd-rest-api-relation-changed')\n@restart_on_change(restart_map(), stopstart=True)\ndef vsd_changed(relation_id=None, remote_unit=None):\n if config('neutron-plugin') == 'vsp':\n vsd_ip_address = relation_get('vsd-ip-address')\n if not vsd_ip_address:\n return\n vsd_address = '{}:8443'.format(vsd_ip_address)\n if CompareOpenStackReleases(os_release('neutron-server')) >= 'kilo':\n vsd_cms_id = relation_get('nuage-cms-id')\n log(\"nuage-vsd-api-relation-changed : cms_id:{}\"\n .format(vsd_cms_id))\n nuage_config_file = neutron_plugin_attribute(config('neutron-plugin'),\n 'config', 'neutron')\n log('vsd-rest-api-relation-changed: ip address:{}'.format(vsd_address))\n log('vsd-rest-api-relation-changed:{}'.format(nuage_config_file))\n\n CONFIGS.write(nuage_config_file)\n\n\n@hooks.hook('upgrade-charm')\n@restart_on_change(restart_map(), stopstart=True)\n@harden()\ndef upgrade_charm():\n common_upgrade_charm_and_config_changed()\n # call the policy overrides handler which will install any policy overrides\n maybe_do_policyd_overrides(\n os_release('neutron-server'),\n 'neutron',\n restart_handler=lambda: service_restart('neutron-server'))\n\n\n@hooks.hook('config-changed')\n@restart_on_change(restart_map(), stopstart=True)\n@harden()\ndef config_changed():\n common_upgrade_charm_and_config_changed()\n # call the policy overrides handler which will install any policy overrides\n maybe_do_policyd_overrides_on_config_changed(\n os_release('neutron-server'),\n 'neutron',\n restart_handler=lambda: service_restart('neutron-server'))\n\n\ndef common_upgrade_charm_and_config_changed():\n \"\"\"Common code between upgrade-charm and config-changed hooks\"\"\"\n # if we are paused, delay doing any config changed hooks.\n # It is forced on the resume.\n if is_unit_paused_set():\n log(\"Unit is pause or upgrading. Skipping config_changed\", \"WARN\")\n return\n\n # If neutron is ready to be queried then check for incompatability between\n # existing neutron objects and charm settings\n if neutron_ready():\n if l3ha_router_present() and not get_l3ha():\n e = ('Cannot disable Router HA while ha enabled routers exist.'\n ' Please remove any ha routers')\n status_set('blocked', e)\n raise Exception(e)\n if dvr_router_present() and not get_dvr():\n e = ('Cannot disable dvr while dvr enabled routers exist. Please'\n ' remove any distributed routers')\n log(e, level=ERROR)\n status_set('blocked', e)\n raise Exception(e)\n if config('prefer-ipv6'):\n status_set('maintenance', 'configuring ipv6')\n setup_ipv6()\n sync_db_with_multi_ipv6_addresses(config('database'),\n config('database-user'))\n\n global CONFIGS\n if not config('action-managed-upgrade'):\n if openstack_upgrade_available('neutron-common'):\n status_set('maintenance', 'Running openstack upgrade')\n do_openstack_upgrade(CONFIGS)\n\n additional_install_locations(\n config('neutron-plugin'),\n config('openstack-origin')\n )\n status_set('maintenance', 'Installing apt packages')\n pkgs = determine_packages(openstack_release=os_release('neutron-server'))\n apt_install(filter_installed_packages(pkgs), fatal=True)\n packages_removed = remove_old_packages()\n configure_https()\n update_nrpe_config()\n infoblox_changed()\n # This part can be removed for U.\n if os.path.exists(ADMIN_POLICY):\n # Clean 00-admin.json added for bug/1830536. At has been\n # noticed that it creates regression.\n os.remove(ADMIN_POLICY)\n CONFIGS.write_all()\n if packages_removed and not is_unit_paused_set():\n log(\"Package purge detected, restarting services\", \"INFO\")\n for s in services():\n service_restart(s)\n for r_id in relation_ids('neutron-api'):\n neutron_api_relation_joined(rid=r_id)\n for r_id in relation_ids('neutron-plugin-api'):\n neutron_plugin_api_relation_joined(rid=r_id)\n for r_id in relation_ids('amqp'):\n amqp_joined(relation_id=r_id)\n for r_id in relation_ids('identity-service'):\n identity_joined(rid=r_id)\n for r_id in relation_ids('ha'):\n ha_joined(relation_id=r_id)\n for r_id in relation_ids('neutron-plugin-api-subordinate'):\n neutron_plugin_api_subordinate_relation_joined(relid=r_id)\n for rid in relation_ids('cluster'):\n cluster_joined(rid)\n\n\n@hooks.hook('amqp-relation-joined')\ndef amqp_joined(relation_id=None):\n relation_set(relation_id=relation_id,\n username=config('rabbit-user'), vhost=config('rabbit-vhost'))\n\n\n@hooks.hook('amqp-relation-changed')\n@hooks.hook('amqp-relation-departed')\n@restart_on_change(restart_map())\ndef amqp_changed():\n if 'amqp' not in CONFIGS.complete_contexts():\n log('amqp relation incomplete. Peer not ready?')\n return\n CONFIGS.write(NEUTRON_CONF)\n\n for r_id in relation_ids('neutron-plugin-api-subordinate'):\n neutron_plugin_api_subordinate_relation_joined(relid=r_id)\n\n\n@hooks.hook('shared-db-relation-joined')\ndef db_joined():\n if config('prefer-ipv6'):\n sync_db_with_multi_ipv6_addresses(config('database'),\n config('database-user'))\n else:\n # Avoid churn check for access-network early\n access_network = None\n for unit in related_units():\n access_network = relation_get(unit=unit,\n attribute='access-network')\n if access_network:\n break\n host = get_relation_ip('shared-db', cidr_network=access_network)\n\n relation_set(database=config('database'),\n username=config('database-user'),\n hostname=host)\n\n\n@hooks.hook('shared-db-relation-changed')\n@restart_on_change(restart_map())\ndef db_changed():\n if is_db_maintenance_mode():\n log('Database maintenance mode, aborting hook.', level=DEBUG)\n return\n if 'shared-db' not in CONFIGS.complete_contexts():\n log('shared-db relation incomplete. Peer not ready?')\n return\n CONFIGS.write_all()\n conditional_neutron_migration()\n infoblox_changed()\n for r_id in relation_ids('neutron-plugin-api-subordinate'):\n neutron_plugin_api_subordinate_relation_joined(relid=r_id)\n\n\n@hooks.hook('amqp-relation-broken',\n 'identity-service-relation-broken',\n 'shared-db-relation-broken')\ndef relation_broken():\n CONFIGS.write_all()\n\n\n@hooks.hook('identity-service-relation-joined')\ndef identity_joined(rid=None, relation_trigger=False):\n if config('vip') and not is_clustered():\n log('Defering registration until clustered', level=DEBUG)\n return\n\n public_url = '{}:{}'.format(canonical_url(CONFIGS, PUBLIC),\n api_port('neutron-server'))\n admin_url = '{}:{}'.format(canonical_url(CONFIGS, ADMIN),\n api_port('neutron-server'))\n internal_url = '{}:{}'.format(canonical_url(CONFIGS, INTERNAL),\n api_port('neutron-server')\n )\n rel_settings = {\n 'neutron_service': 'neutron',\n 'neutron_region': config('region'),\n 'neutron_public_url': public_url,\n 'neutron_admin_url': admin_url,\n 'neutron_internal_url': internal_url,\n 'quantum_service': None,\n 'quantum_region': None,\n 'quantum_public_url': None,\n 'quantum_admin_url': None,\n 'quantum_internal_url': None,\n }\n if relation_trigger:\n rel_settings['relation_trigger'] = str(uuid.uuid4())\n relation_set(relation_id=rid, relation_settings=rel_settings)\n\n\n@hooks.hook('identity-service-relation-changed')\n@restart_on_change(restart_map())\ndef identity_changed():\n if 'identity-service' not in CONFIGS.complete_contexts():\n log('identity-service relation incomplete. Peer not ready?')\n return\n CONFIGS.write(NEUTRON_CONF)\n for r_id in relation_ids('neutron-api'):\n neutron_api_relation_joined(rid=r_id)\n for r_id in relation_ids('neutron-plugin-api'):\n neutron_plugin_api_relation_joined(rid=r_id)\n for r_id in relation_ids('neutron-plugin-api-subordinate'):\n neutron_plugin_api_subordinate_relation_joined(relid=r_id)\n configure_https()\n infoblox_changed()\n\n\n@hooks.hook('neutron-api-relation-joined')\ndef neutron_api_relation_joined(rid=None):\n base_url = canonical_url(CONFIGS, INTERNAL)\n neutron_url = '%s:%s' % (base_url, api_port('neutron-server'))\n relation_data = {\n 'enable-sriov': config('enable-sriov'),\n 'enable-hardware-offload': config('enable-hardware-offload'),\n 'neutron-url': neutron_url,\n 'neutron-plugin': config('neutron-plugin'),\n }\n if config('neutron-security-groups'):\n relation_data['neutron-security-groups'] = \"yes\"\n else:\n relation_data['neutron-security-groups'] = \"no\"\n\n if is_api_ready(CONFIGS):\n relation_data['neutron-api-ready'] = \"yes\"\n else:\n relation_data['neutron-api-ready'] = \"no\"\n\n # LP Bug#1805645\n dns_domain = get_dns_domain()\n if dns_domain:\n relation_data['dns-domain'] = dns_domain\n\n relation_set(relation_id=rid, **relation_data)\n # Nova-cc may have grabbed the neutron endpoint so kick identity-service\n # relation to register that its here\n for r_id in relation_ids('identity-service'):\n identity_joined(rid=r_id, relation_trigger=True)\n\n\n@hooks.hook('neutron-api-relation-changed')\n@restart_on_change(restart_map())\ndef neutron_api_relation_changed():\n CONFIGS.write(NEUTRON_CONF)\n\n\n@hooks.hook('neutron-load-balancer-relation-joined')\ndef neutron_load_balancer_relation_joined(rid=None):\n relation_data = {}\n relation_data['neutron-api-ready'] = is_api_ready(CONFIGS)\n relation_set(relation_id=rid, **relation_data)\n\n\n@hooks.hook('neutron-load-balancer-relation-changed')\n@restart_on_change(restart_map())\ndef neutron_load_balancer_relation_changed(rid=None):\n neutron_load_balancer_relation_joined(rid)\n CONFIGS.write(NEUTRON_CONF)\n\n\n@hooks.hook('neutron-plugin-api-relation-joined')\ndef neutron_plugin_api_relation_joined(rid=None):\n if config('neutron-plugin') == 'nsx':\n relation_data = {\n 'nsx-username': config('nsx-username'),\n 'nsx-password': config('nsx-password'),\n 'nsx-cluster-name': config('nsx-cluster-name'),\n 'nsx-tz-uuid': config('nsx-tz-uuid'),\n 'nsx-l3-uuid': config('nsx-l3-uuid'),\n 'nsx-controllers': config('nsx-controllers'),\n }\n else:\n relation_data = {\n 'neutron-security-groups': config('neutron-security-groups'),\n 'l2-population': get_l2population(),\n 'enable-dvr': get_dvr(),\n 'enable-l3ha': get_l3ha(),\n 'enable-qos': is_qos_requested_and_valid(),\n 'enable-vlan-trunking': is_vlan_trunking_requested_and_valid(),\n 'enable-nsg-logging': is_nsg_logging_enabled(),\n 'enable-nfg-logging': is_nfg_logging_enabled(),\n 'enable-port-forwarding': is_port_forwarding_enabled(),\n 'enable-fwaas': is_fwaas_enabled(),\n 'overlay-network-type': get_overlay_network_type(),\n 'addr': unit_get('private-address'),\n 'polling-interval': config('polling-interval'),\n 'rpc-response-timeout': config('rpc-response-timeout'),\n 'report-interval': config('report-interval'),\n 'global-physnet-mtu': config('global-physnet-mtu'),\n 'physical-network-mtus': config('physical-network-mtus'),\n }\n\n # Provide this value to relations since it needs to be set in multiple\n # places e.g. neutron.conf, nova.conf\n net_dev_mtu = config('network-device-mtu')\n if net_dev_mtu:\n relation_data['network-device-mtu'] = net_dev_mtu\n\n identity_ctxt = IdentityServiceContext()()\n if not identity_ctxt:\n identity_ctxt = {}\n\n relation_data.update({\n 'auth_host': identity_ctxt.get('auth_host'),\n 'auth_port': identity_ctxt.get('auth_port'),\n 'auth_protocol': identity_ctxt.get('auth_protocol'),\n 'service_protocol': identity_ctxt.get('service_protocol'),\n 'service_host': identity_ctxt.get('service_host'),\n 'service_port': identity_ctxt.get('service_port'),\n 'service_tenant': identity_ctxt.get('admin_tenant_name'),\n 'service_username': identity_ctxt.get('admin_user'),\n 'service_password': identity_ctxt.get('admin_password'),\n 'internal_host': identity_ctxt.get('internal_host'),\n 'internal_port': identity_ctxt.get('internal_port'),\n 'internal_protocol': identity_ctxt.get('internal_protocol'),\n 'region': config('region'),\n })\n\n dns_domain = get_dns_domain()\n if dns_domain:\n relation_data['dns-domain'] = dns_domain\n\n if is_api_ready(CONFIGS):\n relation_data['neutron-api-ready'] = \"yes\"\n else:\n relation_data['neutron-api-ready'] = \"no\"\n\n relation_set(relation_id=rid, **relation_data)\n\n\n@hooks.hook('cluster-relation-joined')\ndef cluster_joined(relation_id=None):\n settings = {}\n\n for addr_type in ADDRESS_TYPES:\n address = get_relation_ip(\n addr_type,\n cidr_network=config('os-{}-network'.format(addr_type)))\n if address:\n settings['{}-address'.format(addr_type)] = address\n\n settings['private-address'] = get_relation_ip('cluster')\n\n relation_set(relation_id=relation_id, relation_settings=settings)\n\n if not relation_id:\n check_local_db_actions_complete()\n\n\n@hooks.hook('cluster-relation-changed',\n 'cluster-relation-departed')\n@restart_on_change(restart_map(), stopstart=True)\ndef cluster_changed():\n CONFIGS.write_all()\n check_local_db_actions_complete()\n\n\n@hooks.hook('ha-relation-joined')\ndef ha_joined(relation_id=None):\n extra_settings = {\n 'delete_resources': ['cl_nova_haproxy']\n }\n settings = generate_ha_relation_data(\n 'neutron',\n extra_settings=extra_settings)\n relation_set(relation_id=relation_id, **settings)\n\n\n@hooks.hook('ha-relation-changed')\ndef ha_changed():\n clustered = relation_get('clustered')\n if not clustered or clustered in [None, 'None', '']:\n log('ha_changed: hacluster subordinate'\n ' not fully clustered: %s' % clustered)\n return\n log('Cluster configured, notifying other services and updating '\n 'keystone endpoint configuration')\n for rid in relation_ids('identity-service'):\n identity_joined(rid=rid)\n for rid in relation_ids('neutron-api'):\n neutron_api_relation_joined(rid=rid)\n\n\n@hooks.hook('neutron-plugin-api-subordinate-relation-joined',\n 'neutron-plugin-api-subordinate-relation-changed')\n@restart_on_change(restart_map(), stopstart=True)\ndef neutron_plugin_api_subordinate_relation_joined(relid=None):\n relation_data = {}\n if is_db_initialised():\n db_migration_key = 'migrate-database-nonce'\n if not relid:\n relid = relation_id()\n leader_key = '{}-{}'.format(db_migration_key, relid)\n for unit in related_units(relid):\n nonce = relation_get(db_migration_key, rid=relid, unit=unit)\n if nonce:\n if is_leader() and leader_get(leader_key) != nonce:\n migrate_neutron_database(upgrade=True)\n # track nonce in leader storage to avoid superfluous\n # migrations\n leader_set({leader_key: nonce})\n # set nonce back on relation to signal completion to other end\n # we do this regardless of leadership status so that\n # subordinates connected to non-leader units can proceed.\n relation_data[db_migration_key] = nonce\n\n relation_data['neutron-api-ready'] = 'no'\n if is_api_ready(CONFIGS):\n relation_data['neutron-api-ready'] = 'yes'\n if not manage_plugin():\n neutron_cc_ctxt = NeutronCCContext()()\n plugin_instance = NeutronApiSDNContext()\n neutron_config_data = {\n k: v for k, v in neutron_cc_ctxt.items()\n if plugin_instance.is_allowed(k)}\n if neutron_config_data:\n relation_data['neutron_config_data'] = json.dumps(\n neutron_config_data)\n relation_set(relation_id=relid, **relation_data)\n\n # there is no race condition with the neutron service restart\n # as juju propagates the changes done in relation_set only after\n # the hook exists\n CONFIGS.write_all()\n\n\n@hooks.hook('nrpe-external-master-relation-joined',\n 'nrpe-external-master-relation-changed')\ndef update_nrpe_config():\n # python-dbus is used by check_upstart_job\n apt_install('python-dbus')\n hostname = nrpe.get_nagios_hostname()\n current_unit = nrpe.get_nagios_unit_name()\n nrpe_setup = nrpe.NRPE(hostname=hostname)\n nrpe.copy_nrpe_checks()\n nrpe.add_init_service_checks(nrpe_setup, services(), current_unit)\n\n nrpe.add_haproxy_checks(nrpe_setup, current_unit)\n nrpe_setup.write()\n\n\n@hooks.hook('etcd-proxy-relation-joined')\n@hooks.hook('etcd-proxy-relation-changed')\ndef etcd_proxy_force_restart(relation_id=None):\n # note(cory.benfield): Mostly etcd does not require active management,\n # but occasionally it does require a full config nuking. This does not\n # play well with the standard neutron-api config management, so we\n # treat etcd like the special snowflake it insists on being.\n CONFIGS.register('/etc/init/etcd.conf', [EtcdContext()])\n CONFIGS.write('/etc/init/etcd.conf')\n CONFIGS.register('/etc/default/etcd', [EtcdContext()])\n CONFIGS.write('/etc/default/etcd')\n\n if 'etcd-proxy' in CONFIGS.complete_contexts():\n force_etcd_restart()\n\n\n@hooks.hook('midonet-relation-joined')\n@hooks.hook('midonet-relation-changed')\n@hooks.hook('midonet-relation-departed')\n@restart_on_change(restart_map())\ndef midonet_changed():\n CONFIGS.write_all()\n\n\n@hooks.hook('external-dns-relation-joined',\n 'external-dns-relation-changed',\n 'external-dns-relation-departed',\n 'external-dns-relation-broken')\n@restart_on_change(restart_map())\ndef designate_changed():\n CONFIGS.write_all()\n\n\n@hooks.hook('infoblox-neutron-relation-changed')\n@restart_on_change(restart_map)\ndef infoblox_changed():\n # The neutron DB upgrade will add new tables to\n # neutron db related to infoblox service.\n # Please take a look to charm-infoblox docs.\n if 'infoblox-neutron' not in CONFIGS.complete_contexts():\n log('infoblox-neutron relation incomplete. Peer not ready?')\n return\n\n CONFIGS.write(NEUTRON_CONF)\n\n if is_leader():\n ready = False\n if is_db_initialised() and neutron_ready():\n migrate_neutron_database(upgrade=True)\n ready = True\n for rid in relation_ids('infoblox-neutron'):\n relation_set(relation_id=rid, neutron_api_ready=ready)\n\n\n@hooks.hook('infoblox-neutron-relation-departed',\n 'infoblox-neutron-relation-broken')\n@restart_on_change(restart_map)\ndef infoblox_departed():\n CONFIGS.write_all()\n\n\n@hooks.hook('update-status')\n@harden()\n@harden()\ndef update_status():\n log('Updating status.')\n\n\n@hooks.hook('certificates-relation-joined')\ndef certs_joined(relation_id=None):\n relation_set(\n relation_id=relation_id,\n relation_settings=get_certificate_request())\n\n\n@hooks.hook('certificates-relation-changed')\n@restart_on_change(restart_map(), stopstart=True)\ndef certs_changed(relation_id=None, unit=None):\n process_certificates('neutron', relation_id, unit)\n configure_https()\n # If endpoint has switched to https, need to tell\n # nova-cc\n for r_id in relation_ids('neutron-api'):\n neutron_api_relation_joined(rid=r_id)\n\n\n@hooks.hook('pre-series-upgrade')\ndef pre_series_upgrade():\n log(\"Running prepare series upgrade hook\", \"INFO\")\n series_upgrade_prepare(\n pause_unit_helper, CONFIGS)\n\n\n@hooks.hook('post-series-upgrade')\ndef post_series_upgrade():\n log(\"Running complete series upgrade hook\", \"INFO\")\n series_upgrade_complete(\n resume_unit_helper, CONFIGS)\n\n\ndef main():\n try:\n hooks.execute(sys.argv)\n except UnregisteredHookError as e:\n log('Unknown hook {} - skipping.'.format(e))\n assess_status(CONFIGS)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hooks/neutron_api_hooks.py","file_name":"neutron_api_hooks.py","file_ext":"py","file_size_in_byte":28218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"90294983","text":"# coding: utf-8\n# Universidade Federal de Campina Grande - UFCG\n# Programação I - UFCG\n# Aluno: Walisson Nascimento de Farias\n# Matrícula: 117210716\n# Unidade: 9\tQuestão: É Quadrado Mágico?\n\ndef eh_quadrado_magico(quadrado):\n\tlista = []\n\tfor i in quadrado:\n\t\tfor j in i:\n\t\t\tif j not in lista:\n\t\t\t\tlista.append(j)\n\t\n\taux = []\n\tfor i in quadrado:\n\t\tfor j in i:\n\t\t\taux.append(j)\n\t\n\tif lista == aux and len(quadrado) != 0:\n\t\t# Somando Linhas:\n\t\tsoma_linha = 0\n\t\tlista_linhas = []\n\t\tlinha = 0\n\t\twhile linha <= len(quadrado)-1:\n\t\t\tfor i in range(len(quadrado[linha])):\n\t\t\t\tsoma_linha += quadrado[linha][i]\n\t\t\tlista_linhas.append(soma_linha)\n\t\t\tsoma_linha = 0\n\t\t\tlinha += 1\n\t\t\n\t\t# Somando Colunas:\n\t\tsoma_coluna = 0\n\t\tlista_colunas = []\n\t\tcoluna = 0\n\t\twhile coluna <= len(quadrado)-1:\n\t\t\tfor j in range(len(quadrado)):\n\t\t\t\tsoma_coluna += quadrado[j][coluna]\n\t\t\tlista_colunas.append(soma_coluna)\n\t\t\tsoma_coluna = 0\n\t\t\tcoluna += 1\n\t\t\n\t\tlista_final = lista_linhas + lista_colunas\n\t\t\n\t\t# Somando Diagonal:\n\t\tsoma_diagonal = 0\n\t\tfor d in range(len(quadrado)):\n\t\t\tsoma_diagonal += quadrado[d][d]\n\t\tlista_final.append(soma_diagonal)\n\t\t\n\t\t# Somando Diagonal Secundária:\n\t\tsoma_diagonal_sec = 0\n\t\tfor ds in range(len(quadrado)):\n\t\t\tsoma_diagonal_sec += quadrado[ds][(len(quadrado)-1) - ds]\n\t\tlista_final.append(soma_diagonal_sec)\n\t\t\n\t\tteste = lista_final[0]\n\t\tfor i in lista_final:\n\t\t\tif i != teste:\n\t\t\t\treturn False\n\t\treturn True\n\telse:\n\t\treturn False\n\nquadrado1 = [[2,7,6],[9,5,1],[4,3,8]]\nquadrado2 = [[1,2,3],[4,5,6]]\nquadrado3 = []\nassert eh_quadrado_magico(quadrado1)\nassert not eh_quadrado_magico(quadrado2)\nassert not eh_quadrado_magico(quadrado3)\n","sub_path":"Unidade_9/quadrado_magico/quadrado.py","file_name":"quadrado.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"119501552","text":"# MyPy for Static Typing\nfrom typing import List, Set, Dict, Tuple, Optional, Any, Iterable, Union\n\n# Custom Modules\nfrom helpers.config import config\nfrom helpers.logger import logger\n\n# PyPi Modules\nimport json\nimport mysql.connector.pooling as pooling\nfrom pandas.core.frame import DataFrame\nimport pandas as pd\nfrom mysql.connector.errors import PoolError\nimport threading\n\nclass Initialise:\n def __init__(self) -> None:\n self.poolConnections: Dict[Any, Any] = {}\n self.poolCursors: Dict[Any, Any] = {} \n mariaDet: dict = config['database']\n try:\n logger.info(f'Initialisng Maria pool: {mariaDet}')\n self.pool = pooling.MySQLConnectionPool(\n pool_size=mariaDet.get('poolSize'),\n pool_reset_session=False,\n host=mariaDet.get('host'),\n database=mariaDet.get('database'),\n port=mariaDet.get('port'),\n user=mariaDet.get('user'),\n password=mariaDet.get('password'),\n autocommit=True \n )\n except Exception as error:\n logger.error(f'Unable to connect to maria database, with error: {error}')\n raise \n\n def acquire(self, autocommit: bool = True) -> None:\n threadName: str = threading.current_thread().name\n try:\n self.poolConnections[threadName] = self.pool.get_connection() \n self.poolCursors[threadName] = self.poolConnections[threadName].cursor()\n except Exception as error:\n if type(error) is PoolError and error.args[1] == 'Failed getting connection; pool exhausted':\n self.pool.add_connection()\n self.addConnection = True\n self.poolConnections[threadName] = self.pool.get_connection() \n self.poolCursors[threadName] = self.poolConnections[threadName] \n else:\n raise \n\n def release(self) -> None:\n threadName: str = threading.current_thread().name\n self.poolConnections[threadName].close() \n\n def getData(self, sql, bindings=None, dataframe=None):\n threadName: str = threading.current_thread().name\n cursor = self.poolCursors[threadName]\n try:\n if bindings:\n cursor.execute(sql, bindings)\n else:\n cursor.execute(sql)\n except Exception as error:\n raise MariaError(f\"Unable to retrieve data with error: {error}\")\n\n columns = [field[0] for field in cursor.description]\n data = cursor.fetchall() \n result = []\n for x in data:\n result.append(list(x))\n \n for i, x in enumerate(result):\n for j, y in enumerate(x): \n try: \n x[j] = json.loads(y)\n except:\n x[j] = y\n data[i] = x \n \n if dataframe: \n if len(result) > 0:\n return pd.DataFrame(data = result, columns = columns)\n else:\n return pd.DataFrame(data = [], columns = columns)\n else:\n return [dict(zip(columns, x)) for x in result] \n\n def execute(self, sql, params=None):\n threadName: str = threading.current_thread().name\n cursor = self.poolCursors[threadName] \n try:\n if params:\n cursor.execute(sql, params)\n else:\n cursor.execute(sql)\n except Exception as error:\n raise MariaError(\"Unable to execute statement, with error: {}\".format(error)) \n\n def executeMany(self, sql, batchData, batchLimit):\n threadName: str = threading.current_thread().name\n cursor = self.poolCursors[threadName] \n try:\n for i in range(0, len(batchData)+batchLimit, batchLimit):\n cursor.executemany(\n sql,\n batchData[i:i+batchLimit]\n )\n except Exception as error:\n raise MariaError(\"Unable to executemany statement, with error: {}\".format(error))\n\n def insert(self, sql, params=None):\n threadName: str = threading.current_thread().name\n cursor = self.poolCursors[threadName] \n try:\n cursor.execute(sql, params)\n except Exception as error:\n raise MariaError(\"Unable to execute statement, with error: {}\".format(error)) \n\nclass MariaError(Exception):\n pass\n\nPool: Initialise = Initialise()","sub_path":"src/lib/models/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4665,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"455856034","text":"import torch\nimport torch.nn as nn\nimport torch.nn.utils.rnn as rnn_utils\nimport torch.nn.functional as F\n\nclass REVIEWDI(nn.Module):\n def __init__(self, vocab_obj, args, device):\n super().__init__()\n\n self.m_device=device\n\n self.m_embedding_size = args.embedding_size\n self.m_user_embedding_size = args.latent_size\n\n self.m_hidden_size = args.hidden_size\n self.m_word_dropout_rate = args.word_dropout \n self.m_embedding_dropout = args.embedding_dropout\n self.m_latent_size = args.latent_size\n\n self.m_max_sequence_len = args.max_seq_length\n self.m_num_layers = args.num_layers\n self.m_bidirectional = args.bidirectional\n # self.m_rnn_type = args.rnn_type\n\n self.m_sos_idx = vocab_obj.sos_idx\n self.m_eos_idx = vocab_obj.eos_idx\n self.m_pad_idx = vocab_obj.pad_idx\n self.m_unk_idx = vocab_obj.unk_idx\n\n self.m_vocab_size = vocab_obj.vocab_size\n self.m_user_size = vocab_obj.user_size\n self.m_item_size = vocab_obj.item_size\n\n self.m_embedding = nn.Embedding(self.m_vocab_size, self.m_embedding_size)\n self.m_embedding_dropout = nn.Dropout(p=self.m_embedding_dropout)\n\n self.m_user_embedding = nn.Embedding(self.m_user_size, self.m_latent_size)\n self.m_item_embedding = nn.Embedding(self.m_item_size, self.m_latent_size)\n \n # print(self.m_user_embedding.size())\n\n print(\"user size\", self.m_user_size)\n print(\"item size\", self.m_item_size)\n \n self.m_encoder_rnn = nn.GRU(self.m_embedding_size, self.m_hidden_size, num_layers=self.m_num_layers, bidirectional=True, batch_first=True)\n self.m_decoder_rnn = nn.GRU(self.m_embedding_size, self.m_hidden_size, num_layers=self.m_num_layers, bidirectional=False, batch_first=True)\n\n self.m_hidden2mean_z = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n self.m_hidden2logv_z = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n\n self.m_hidden2mean_s = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n self.m_hidden2logv_s = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n\n self.m_hidden2mean_l = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n self.m_hidden2logv_l = nn.Linear(self.m_hidden_size*2, self.m_latent_size)\n\n # self.m_latent2hidden = nn.Linear(self.m_latent_size, self.m_embedding_size)\n self.m_latent2hidden = nn.Linear(self.m_latent_size, self.m_hidden_size)\n self.m_output2vocab = nn.Linear(self.m_hidden_size, self.m_vocab_size)\n\n self.m_decoder_gate = nn.Sequential(nn.Linear(self.m_hidden_size, 1), nn.Sigmoid())\n\n self.m_attn = nn.Sequential(nn.Linear(self.m_hidden_size+self.m_latent_size, self.m_hidden_size), nn.Tanh(), nn.Linear(self.m_hidden_size, 1)) \n\n self = self.to(self.m_device)\n\n def forward(self, input_sequence, input_length, input_de_sequence, input_de_length, user_ids, item_ids, random_flag):\n batch_size = input_sequence.size(0)\n\n input_embedding = self.m_embedding(input_sequence)\n\n input_embedding = self.m_embedding_dropout(input_embedding)\n encoder_outputs, _ = self.m_encoder_rnn(input_embedding)\n\n first_dim_index = torch.arange(batch_size).to(self.m_device)\n second_dim_index = (input_length-1).long()\n \n last_en_hidden = encoder_outputs[first_dim_index, second_dim_index, :].contiguous()\n\n variational_hidden = None\n z_mean = None\n z_logv = None\n z = None\n\n s_mean = None\n s_logv = None\n s = None\n\n l_mean = None\n l_logv = None\n l = None\n\n z_prior = None\n s_prior = None\n\n if random_flag == 0:\n z_mean = self.m_hidden2mean_z(last_en_hidden)\n z_logv = self.m_hidden2logv_z(last_en_hidden)\n z_std = torch.exp(0.5*z_logv)\n z = torch.randn_like(z_std)*z_std + z_mean\n\n z_prior = self.m_user_embedding(user_ids)\n\n s_mean = self.m_hidden2mean_s(last_en_hidden)\n s_logv = self.m_hidden2logv_s(last_en_hidden)\n s_std = torch.exp(0.5*s_logv)\n s = torch.randn_like(s_std)*s_std + s_mean\n\n s_prior = self.m_item_embedding(item_ids)\n\n l_mean = self.m_hidden2mean_l(last_en_hidden)\n l_logv = self.m_hidden2logv_l(last_en_hidden)\n l_std = torch.exp(0.5*l_logv)\n l = torch.randn_like(l_std)*l_std + l_mean\n\n # variational_hidden = z+s\n variational_hidden = z+s+l\n # variational_hidden = torch.cat([z, s, l], dim=1)\n elif random_flag== 1: \n z_mean = self.m_hidden2mean_z(last_en_hidden)\n z_logv = self.m_hidden2logv_z(last_en_hidden)\n z_std = torch.exp(0.5*z_logv)\n z = torch.randn_like(z_std)*z_std + z_mean\n\n z_prior = self.m_user_embedding(user_ids)\n\n s_mean = self.m_hidden2mean_s(last_en_hidden)\n s_logv = self.m_hidden2logv_s(last_en_hidden)\n s_std = torch.exp(0.5*s_logv)\n s = torch.randn_like(s_std)*s_std + s_mean\n\n s_prior = self.m_item_embedding(item_ids)\n\n variational_hidden = z+s\n # variational_hidden = torch.cat([z, s], dim=1)\n \n elif random_flag == 2:\n s_mean = self.m_hidden2mean_s(last_en_hidden)\n s_logv = self.m_hidden2logv_s(last_en_hidden)\n s_std = torch.exp(0.5*s_logv)\n s = torch.randn_like(s_std)*s_std + s_mean\n\n s_prior = self.m_item_embedding(item_ids)\n\n l_mean = self.m_hidden2mean_l(last_en_hidden)\n l_logv = self.m_hidden2logv_l(last_en_hidden)\n l_std = torch.exp(0.5*l_logv)\n l = torch.randn_like(l_std)*l_std + l_mean\n\n # variational_hidden = torch.cat([s, l], dim=1)\n variational_hidden = s+l\n\n elif random_flag == 3:\n z_mean = self.m_hidden2mean_z(last_en_hidden)\n z_logv = self.m_hidden2logv_z(last_en_hidden)\n z_std = torch.exp(0.5*z_logv)\n z = torch.randn_like(z_std)*z_std + z_mean\n\n z_prior = self.m_user_embedding(user_ids)\n\n l_mean = self.m_hidden2mean_l(last_en_hidden)\n l_logv = self.m_hidden2logv_l(last_en_hidden)\n l_std = torch.exp(0.5*l_logv)\n l = torch.randn_like(l_std)*l_std + l_mean\n\n variational_hidden = z+l\n # variational_hidden = torch.cat([z, l], dim=1)\n else:\n raise NotImplementedError(\"0, 1, 2, 3, variational not defined!\")\n\n # init_de_hidden = self.m_latent2hidden(variational_hidden)\n\n input_de_embedding = self.m_embedding(input_de_sequence)\n # repeat_init_de_hidden = init_de_hidden.unsqueeze(1)\n # repeat_init_de_hidden = repeat_init_de_hidden.expand(init_de_hidden.size(0), input_de_embedding.size(1), init_de_hidden.size(-1))\n\n # input_de_embedding = input_de_embedding+repeat_init_de_hidden\n\n hidden = None\n\n de_batch_size = input_de_sequence.size(0)\n de_len = input_de_sequence.size(1)\n # print(\"decoding length\", de_len)\n\n output = []\n var_de = self.m_latent2hidden(variational_hidden)\n\n decode_strategy = \"attn\"\n\n if decode_strategy == \"avg\":\n \"\"\"\n avg mechanism\n \"\"\"\n\n for de_step_i in range(de_len):\n input_de_step_i = input_de_embedding[:, de_step_i, :]\n input_de_step_i = input_de_step_i.unsqueeze(1)\n output_step_i, hidden = self.m_decoder_rnn(input_de_step_i, hidden)\n output.append(output_step_i)\n\n # var_de_flag = self.m_decoder_gate(output_step_i.squeeze(1))\n # # print(\"var_de_flag\", var_de_flag.size())\n # var_de = self.m_latent2hidden((1-var_de_flag)*z+var_de_flag*s+l)\n output = torch.cat(output, dim=1)\n\n elif decode_strategy == \"gating\":\n \"\"\"\n gating mechanism\n \"\"\"\n\n for de_step_i in range(de_len):\n input_de_step_i = input_de_embedding[:, de_step_i, :]+var_de\n input_de_step_i = input_de_step_i.unsqueeze(1)\n output_step_i, hidden = self.m_decoder_rnn(input_de_step_i, hidden)\n # output.append(output_step_i)\n\n var_de_flag = self.m_decoder_gate(output_step_i.squeeze(1))\n # print(\"var_de_flag\", var_de_flag.size())\n var_de = self.m_latent2hidden((1-var_de_flag)*z+var_de_flag*s+l)\n\n output_step_i = output_step_i+var_de\n\n output = torch.cat(output, dim=1)\n\n elif decode_strategy == \"attn\":\n \"\"\"\n attention mechanism output\n \"\"\"\n\n for de_step_i in range(de_len):\n input_de_step_i = input_de_embedding[:, de_step_i, :]\n input_de_step_i = input_de_step_i.unsqueeze(1)\n output_step_i, hidden = self.m_decoder_rnn(input_de_step_i, hidden)\n \n output_step_i = output_step_i.squeeze(1)\n z_attn = torch.cat([output_step_i, z], dim=-1)\n s_attn = torch.cat([output_step_i, s], dim=-1)\n l_attn = torch.cat([output_step_i, l], dim=-1)\n\n z_attn_score = self.m_attn(z_attn)\n s_attn_score = self.m_attn(s_attn)\n l_attn_score = self.m_attn(l_attn)\n\n attn_score = F.softmax(torch.cat([z_attn_score, s_attn_score, l_attn_score], dim=-1), dim=-1)\n\n var_de = attn_score[:, 0].unsqueeze(1)*z\n var_de = var_de+attn_score[:, 1].unsqueeze(1)*s\n var_de = var_de+attn_score[:, 2].unsqueeze(1)*l\n # var_de = attn_score[:, 0]*z+attn_score[:, 1]*s+attn_score[:, 2]*l\n var_de = self.m_latent2hidden(var_de)\n\n output_step_i = output_step_i + var_de\n output.append(output_step_i.unsqueeze(1))\n\n output = torch.cat(output, dim=1)\n\n # print(\"output size\", output.size())\n # if self.m_word_dropout_rate > 0:\n # prob = torch.rand(input_sequence.size()).to(self.m_device)\n\n # prob[(input_sequence.data-self.m_sos_idx)*(input_sequence.data-self.m_pad_idx) ==0] = 1\n\n # decoder_input_sequence = decoder_input_sequence.clone()\n # decoder_input_sequence = input_sequence.clone()\n\n # decoder_input_sequence[prob < self.m_word_dropout_rate] = self.m_unk_idx\n # input_embedding = self.m_embedding(decoder_input_sequence)\n # print(\"output.size\", output.size())\n output = output.contiguous()\n logits = self.m_output2vocab(output.view(-1, output.size(2)))\n \n return logits, z_prior, z_mean, z_logv, z, s_prior, s_mean, s_logv, s, l_mean, l_logv, l, variational_hidden \n","sub_path":"iReview_v2/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":10959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"427107064","text":"#!/usr/bin/python\nimport sys\nimport os\n\nPATH = '~/Acute-Angle-Chain/build/programs/claac/'\n\n\nif len(sys.argv) == 1:\n PATH = PATH + 'claac wallet create'\n waltname = 'default'\nif len(sys.argv) == 2:\n PATH = PATH + 'claac wallet create -n '+ sys.argv[1]\n waltname = sys.argv[1]\nfor s in os.popen(PATH).readlines():\n line = s\nline1 = line[1:-2]\nwaltpin = waltname + ',' + line1 +'\\n' \nf = open('walt_pin', 'a')\nf.writelines(waltpin)\nf.close()\n\n","sub_path":"tests/transfer_tests/wallet.py","file_name":"wallet.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"263096186","text":"\r\nimport time\r\nimport math\r\nimport numpy as np\r\nimport random\r\nimport sys\r\nimport os\r\nimport traceback\r\nimport threading\r\nimport socket\r\ntry:\r\n from drawer import drawIP\r\n from drawer import drawer\r\nexcept:\r\n import drawIP\r\n import drawer\r\nimport struct\r\ntry:\r\n import unicornhat as uh\r\n uh.set_layout(uh.PHAT)\r\n uh.brightness(0.2)\r\nexcept:\r\n pass\r\ns = []\r\nx = 0\r\ny = 0\r\nrunning = True\r\ndraw = []\r\n\r\n\r\n\r\ndrawerIPSelected = drawIP.drawerIP\r\n\r\ndef selectMachine(machine = 1):\r\n global drawerIPSelected\r\n if machine == 1:\r\n drawerIPSelected = drawIP.drawerIP\r\n elif machine == 2:\r\n drawerIPSelected = drawIP.drawerIP2\r\n \r\ndef sendCommand(code,x = 0,y = 0):\r\n dataRec =[]\r\n socketClient = socket.socket()\r\n socketClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n connect = 0\r\n \r\n\r\n\r\n\r\n while connect == 0:\r\n try:\r\n socketClient.connect((drawerIPSelected, drawIP.drawerPort))\r\n connect = 1\r\n except:\r\n connect = 0\r\n data = struct.pack('ddi',x,y,code)\r\n socketClient.sendall(data)\r\n\r\n socketClient.shutdown(socket.SHUT_RDWR)\r\n socketClient.close()\r\n return dataRec\r\n\r\n\r\ndef sendLines(x,y):\r\n dataRec =[]\r\n socketClient = socket.socket()\r\n socketClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n connect = 0\r\n \r\n\r\n\r\n\r\n while connect == 0:\r\n try:\r\n socketClient.connect((drawerIPSelected, drawIP.drawerPort))\r\n connect = 1\r\n except:\r\n connect = 0\r\n data = struct.pack('ddi',x[0],y[0],drawIP.drawerCode['lineBegin'])\r\n socketClient.sendall(data)\r\n\r\n for k in range(1,len(x)):\r\n data = struct.pack('ddi',x[k],y[k],drawIP.drawerCode['toPosition'])\r\n socketClient.sendall(data)\r\n data = struct.pack('ddi',x[0],y[0],drawIP.drawerCode['lineEnd'])\r\n socketClient.sendall(data)\r\n\r\n\r\n socketClient.shutdown(socket.SHUT_RDWR)\r\n socketClient.close()\r\n return dataRec\r\n\r\ndef pen(position):\r\n dataRec =[]\r\n socketClient = socket.socket()\r\n socketClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n connect = 0\r\n \r\n while connect == 0:\r\n try:\r\n socketClient.connect((drawerIPSelected, drawIP.drawerPort))\r\n connect = 1\r\n except:\r\n connect = 0\r\n if position == \"down\":\r\n code = drawIP.drawerCode['penDown']\r\n else:\r\n code = drawIP.drawerCode['penUp']\r\n\r\n data = struct.pack('ddi',0,0,code)\r\n socketClient.sendall(data)\r\n \r\n socketClient.shutdown(socket.SHUT_RDWR)\r\n socketClient.close()\r\n return dataRec\r\n\r\ndef sendPosition(x,y):\r\n dataRec =[]\r\n socketClient = socket.socket()\r\n socketClient.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n connect = 0\r\n \r\n\r\n\r\n\r\n while connect == 0:\r\n try:\r\n socketClient.connect((drawerIPSelected, drawIP.drawerPort))\r\n connect = 1\r\n except:\r\n connect = 0\r\n \r\n data = struct.pack('ddi',x,y,drawIP.drawerCode['toPosition'])\r\n socketClient.sendall(data)\r\n\r\n socketClient.shutdown(socket.SHUT_RDWR)\r\n socketClient.close()\r\n return dataRec\r\n\r\ndef giveStatus(ip):\r\n global running\r\n backlog = 1 # how many connections to accept\r\n maxsize = 28\r\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n binded = False\r\n while not binded:\r\n try:\r\n server.bind((ip,statusPort))\r\n binded = True\r\n except:\r\n print('- Give Status -- binding failed')\r\n binded = False\r\n time.sleep(20)\r\n server.listen(1)\r\n while running:\r\n print('--- waiting for a connection')\r\n try:\r\n connection, client_address = server.accept()\r\n print('------ Connection coming from ' + str(client_address))\r\n\r\n\r\n\r\n code = struct.unpack('i',connection.recv(4))[0]\r\n print('------ code : '+ str(code))\r\n if code == requestStatusCode:\r\n data = struct.pack('i', sendStatusCode)\r\n try:\r\n connection.sendall(data)\r\n except:\r\n print('sending did not work :/ but better not break everything')\r\n except:\r\n pass\r\n\r\n\r\ndef receiveDirection(IP,PORT):\r\n uh.set_pixel(2, 1, 255, 0, 0)\r\n uh.show()\r\n global running\r\n backlog = 1 # how many connections to accept\r\n maxsize = 28\r\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r\n binded = False\r\n print('---- Stimuli Updater')\r\n while not binded:\r\n uh.set_pixel(2, 2, 255, 128, 0)\r\n uh.show()\r\n try:\r\n server.bind((IP,PORT))\r\n binded = True\r\n except:\r\n print(IP)\r\n print('- Wait for Stimuli Update -- binding failed')\r\n binded = False\r\n uh.set_pixel(2, 1, 255, 0, 255)\r\n uh.show()\r\n server.listen(1)\r\n print('---- Stimuli Updater is binded on : '+ IP +' with port : '+ str(PORT))\r\n while running:\r\n uh.set_pixel(2, 3, 255, 255, 0)\r\n uh.show()\r\n print('--- waiting for a connection')\r\n #try:\r\n connection, client_address = server.accept()\r\n print('------ Connection coming from ' + str(client_address))\r\n\r\n\r\n\r\n message = struct.unpack('ddi',connection.recv(20))\r\n code = message[2]\r\n x = message[0]\r\n y = message[1]\r\n print('------ code : '+ str(code))\r\n if code == drawIP.drawerCode['penUp']:\r\n uh.set_pixel(3, 3, 255, 0, 0)\r\n uh.show()\r\n draw.penUp()\r\n if code == drawIP.drawerCode['penDown']:\r\n uh.set_pixel(3, 3, 0, 255, 0)\r\n uh.show()\r\n draw.penDown()\r\n if code == drawIP.drawerCode['toPosition']:\r\n uh.set_pixel(3, 3, 0, 0, 255)\r\n uh.show()\r\n draw.toPosition(x,y)\r\n if code == drawIP.drawerCode['lineBegin']:\r\n uh.set_pixel(3, 3, 0, 255, 255)\r\n uh.show()\r\n draw.toPosition(x,y)\r\n draw.penDown()\r\n line = True\r\n while line:\r\n message = struct.unpack('ddi',connection.recv(20))\r\n code = message[2]\r\n uh.set_pixel(3, 3, 0, 255, 255)\r\n uh.show()\r\n if code == drawIP.drawerCode['lineEnd']:\r\n draw.penUp()\r\n line = False\r\n uh.set_pixel(3, 4, 0, 0, 0)\r\n uh.show()\r\n else:\r\n x = message[0]\r\n y = message[1]\r\n draw.toPosition(x,y)\r\n uh.set_pixel(3, 4, 0, 0, 0) \r\n uh.show()\r\n uh.set_pixel(3, 4, 0, 255, 255)\r\n uh.show()\r\n\r\n\r\n #except:\r\n # pass\r\n\r\ndef main():\r\n uh.set_pixel(0, 0, 255, 0, 0)\r\n uh.show()\r\n\r\n global running\r\n global draw\r\n draw = drawer.Drawer()\r\n print(sys.argv)\r\n try:\r\n print(int(sys.argv[2]))\r\n print(int(sys.argv[2]) == 1)\r\n if int(sys.argv[2]) == 1:\r\n draw.penInvert(True)\r\n except:\r\n pass\r\n try:\r\n print(int(sys.argv[1]))\r\n selectMachine(int(sys.argv[1]))\r\n print(drawerIPSelected)\r\n except:\r\n pass\r\n draw.penUp()\r\n receiveThread = threading.Thread(target=receiveDirection, args=(drawerIPSelected, drawIP.drawerPort))\r\n receiveThread.daemon = True\r\n receiveThread.start()\r\n uh.set_pixel(2, 0, 0, 255, 0)\r\n uh.show()\r\n\r\n\r\n statusThread = threading.Thread(target = giveStatus, args=(drawerIPSelected,))\r\n statusThread.daemon = True\r\n statusThread.start()\r\n uh.set_pixel(1, 0, 255, 0, 255)\r\n uh.show()\r\n\r\n t0 = time.time()\r\n\r\n while running:\r\n t = time.time()-t0\r\n time.sleep(3600)\r\n print(\">>>>>>>>>>>> the drawer is in service since \" + str(int(t/3600)) +\" hours\")\r\n\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n \r\n","sub_path":"src/drawer/drawNet.py","file_name":"drawNet.py","file_ext":"py","file_size_in_byte":8370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"318343719","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport lime\nimport lime.lime_tabular\nimport keras\nfrom datetime import datetime as dt\nfrom dateutil.parser import parse\nfrom scipy.stats import zscore\nfrom sklearn import preprocessing\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import tree\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.metrics import roc_auc_score, roc_curve, auc, average_precision_score, confusion_matrix, classification_report\nfrom sklearn.model_selection import GridSearchCV, train_test_split\nfrom sklearn import metrics\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import cross_validate\nfrom xgboost import XGBClassifier\nfrom __future__ import print_function\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\n# Load data and parse date columns\ndate_columns = ['subscription_start_date', 'subscription_stop_date', 'today']\ndup = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_DUP_TESTDATA.csv',\n sep='\\t', encoding='utf8', parse_dates=date_columns)\nunique = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_UNIQUE_TESTDATA.csv',\n sep='\\t', encoding='utf8', parse_dates=date_columns)\n# Sort by uuid\ndup = dup.sort_values('uuid')\nunique = unique.sort_values('uuid')\n\n# Inspect shape\nprint(dup.shape, unique.shape)\n# Inspect date\nprint(dup.subscription_start_date.describe(), unique.subscription_start_date.describe())\n\n# Derive tenure in days, subs with no stop date (active) will return NaN\ndup['tenure_in_days'] = (dup.subscription_stop_date - dup.subscription_start_date).dt.days\nunique['tenure_in_days'] = (unique.subscription_stop_date - unique.subscription_start_date).dt.days\n# Drop rows with negative tenure days\ndup.drop(dup.index[np.where(dup.tenure_in_days < 0)], inplace=True)\n# Derive previous average tenure days\ndup = dup.join(dup.groupby('uuid')['tenure_in_days'].mean(), on='uuid', rsuffix='_pre_avg')\n\n# Create a new stop date column with NaN imputed with \"today\"\ndup['subscription_stop_date_new'] = dup.subscription_stop_date.fillna(dup.today)\n# Derive the maximum history days by subtracting the earliest start date from latest stop date\n# This will be the sub's entire history\nmax_hist = (dup.groupby('uuid')['subscription_stop_date_new'].max() -\n dup.groupby('uuid')['subscription_start_date'].min()).dt.days\ndup = dup.join(pd.DataFrame(max_hist), on='uuid')\ndup.rename(columns={0: 'max_hist'}, inplace=True)\n\n# Derive the total tenure days including active tenure (all days a sub has/had a subscription)\ndup['tenure_in_days_new'] = (dup.subscription_stop_date_new - dup.subscription_start_date).dt.days\ndup = dup.join(dup.groupby('uuid')['tenure_in_days_new'].sum(), on='uuid', rsuffix='_sum')\n\n# Derive total gap days by subtracting the every tenure days from the entire history\ndup['total_gap'] = dup.max_hist - dup.tenure_in_days_new_sum\n\n# Remove negative gap days\n# It means the entire history is smaller than tenure days, the sub has started a new sub during a subscription\n# Take them out of the sample\ndup = dup[dup.total_gap >= 0]\n\n# Derive how many times a person canceled and derive the average gap days\ndup['cancel_num'] = dup.groupby('uuid')['uuid'].transform('count') - 1\ndup['avg_gap_days'] = dup.total_gap / dup.cancel_num\n\n# Eliminate all rows that canceled before churn window and get unique\ndup = dup[(dup.subscription_stop_date > '2018-08-31') | (dup.subscription_stop_date.isnull())]\ndup = dup[dup.groupby('uuid')['uuid'].transform('count') == 1]\n# Assign churn label\ndup['churn'] = np.where(dup.subscription_stop_date.isnull(), 0, 1)\n\n# Check for dups\nprint(len(dup.uuid.unique()), dup.shape)\n\n# For unique: Eliminate all rows that canceled before churn window\nunique.drop(unique.index[np.where(unique.subscription_stop_date <= '2018-08-31')], inplace=True)\n# Create a new stop date column with NaN imputed with \"today\"\nunique['subscription_stop_date_new'] = unique.subscription_stop_date.fillna(unique.today)\n# Derive the maximum history days and other relative columns\nunique['max_hist'] = (unique.subscription_stop_date_new - unique.subscription_start_date).dt.days\nl = ['total_gap', 'tenure_in_days_pre_avg', 'cancel_num', 'avg_gap_days']\nfor col in l:\n unique[col] = 0\nunique['churn'] = np.where(unique.subscription_stop_date.isnull(), 0, 1)\n\nprint(dup.churn.value_counts(), unique.churn.value_counts())\n\n# Drop rows with null average gap days\ndup.drop(dup.index[np.where(dup.avg_gap_days.isnull())], inplace=True)\ndup.drop(dup.index[np.where(dup.tenure_in_days_pre_avg.isnull())], inplace=True)\n\n# Import usage data\ncolnames = ['uuid', 'month', 'page_views']\ncolnames_app = ['uuid', 'month', 'all_visits']\n\nusage_raw = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_Usage_TESTDATA.csv',\n sep='\\t', encoding='latin-1', usecols=colnames)\nusage_mobile_raw = pd.read_csv(\n 'C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_Usage_Mobile_TESTDATA.csv', sep='\\t', encoding='latin-1', usecols=colnames)\nusage_app_raw = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/090618_CDP_Usage_App_TESTDATA.csv',\n sep='\\t', encoding='latin-1', usecols=colnames_app)\n\nusage_app_raw.rename(columns={'all_visits': 'page_views'}, inplace=True)\n\nusage = usage_raw.dropna()\nusage_mobile = usage_mobile_raw.dropna()\nusage_app = usage_app_raw.dropna()\n\nprint(usage.shape, usage_mobile.shape, usage_app.shape)\n\n# Check all unique uuids that have usage at least in 1 month\nprint(len(usage.uuid.unique()), len(usage_mobile.uuid.unique()), len(usage_app.uuid.unique()))\n# Check how many uuids with no usage for all 6 months\nprint(len(set((unique.uuid + dup.uuid)) - set((usage.uuid + usage_mobile.uuid + usage_app.uuid))))\n\ncolnames = ['Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'uuid']\ncol_ord = ['uuid', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug']\n\n\ndef usage_flat(x):\n x = x.pivot(index='uuid', columns='month', values='page_views')\n x['uuid'] = x.index\n x = x.reset_index(drop=True)\n x.columns = colnames\n x = x[col_ord]\n x = x.fillna(0)\n return x\n\n\nusage = usage_flat(usage)\nusage_mobile = usage_flat(usage_mobile)\nusage_app = usage_flat(usage_app)\n\n\n# Compute the delta of 4-month exponential moving average\ndef ewm_delta_function(x):\n x1 = x[['Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug']]\n s = x1.apply(lambda s: s.ewm(span=4, adjust=False).mean(), axis=1) # 4-month rolling window\n s['delta'] = s.Aug-s.Jul\n s['last_month'] = s.Aug\n x = pd.concat([x, s], axis=1)\n x = x[['uuid', 'delta', 'last_month']]\n return x\n\n\nusage = ewm_delta_function(usage)\nusage_mobile = ewm_delta_function(usage_mobile)\nusage_app = ewm_delta_function(usage_app)\n\nusage_mobile.rename(columns={'delta': 'delta_mobile',\n 'last_month': 'last_month_mobile'}, inplace=True)\nusage_app.rename(columns={'delta': 'delta_app', 'last_month': 'last_month_app'}, inplace=True)\n\n\ndef merge_function(x):\n x = pd.merge(x, usage, on='uuid', how='left')\n x = pd.merge(x, usage_mobile, on='uuid', how='left')\n x = pd.merge(x, usage_app, on='uuid', how='left')\n return x\n\n\ndup = merge_function(dup)\nunique = merge_function(unique)\n\n# Save cleaned data to csv for quicker access\n# dup.to_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/CDP_DUP_CLEAN_TESTDATA.csv')\n# unique.to_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/CDP_UNIQUE_CLEAN_TESTDATA.csv')\n# Load cleaned data\n#dup = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/CDP_DUP_CLEAN_TESTDATA.csv', encoding='utf8')\n#unique = pd.read_csv('C:/Users/hsiaol/Desktop/CDP_script_sample/CDP_UNIQUE_CLEAN_TESTDATA.csv', encoding='utf8')\n\n# Drop rows with all NaN usage, assign 0 to no usage and no delta\ncols = ['delta', 'delta_mobile', 'delta_app', 'last_month', 'last_month_mobile', 'last_month_app']\n\ndup.dropna(subset=cols, how='all', inplace=True)\nunique.dropna(subset=cols, how='all', inplace=True)\n\ndup[cols] = dup[cols].fillna(0)\nunique[cols] = unique[cols].fillna(0)\n\n# Get 'committed_subscription_amount' and 'subscription_frequency'\n\n\ndef clean_function(x):\n x = x[x.committed_subscription_amount.notnull()]\n x = x[x.committed_subscription_amount != 0]\n x = x[x.subscription_frequency != 'OTHER']\n return x\n\n\ndup = clean_function(dup)\nunique = clean_function(unique)\n\nprint(dup.shape)\nprint(unique.shape)\n\n# Modeling process\ncol_select = ['tenure_in_days_pre_avg', 'max_hist', 'total_gap', 'cancel_num', 'avg_gap_days',\n 'delta', 'delta_mobile', 'delta_app',\n 'committed_subscription_amount', 'churn', 'subscription_frequency']\ndf_dup = dup[col_select]\ndf_unique = unique[col_select]\n\ndf_final = df_dup.append(df_unique)\nprint(df_final.churn.value_counts())\n\n# Dummy-code categorical variables\ndf_final = pd.get_dummies(df_final, drop_first=True)\n\ndf_final = df_final.reset_index(drop=True)\ndf_final = df_final.values\n\n# Labeling\nlabels = df_final[:, 9]\nle = preprocessing.LabelEncoder()\nle.fit(labels)\nlabels = le.transform(labels)\nclass_names = le.classes_\ndf_final = np.delete(df_final, 9, axis=1)\n\ndf_final = df_final.astype(float)\n\n# load the model\nloaded_model = joblib.load('C:/Users/hsiaol/Desktop/CDP_script_sample/finalized_model.sav')\n\n# Confusion Matrix\npd.crosstab(labels, loaded_model.predict(df_final), rownames=[\n 'True'], colnames=['Predicted'], margins=True)\n\ny_scores = loaded_model.predict_proba(df_final)[:, 1]\n\n\npd.crosstab(labels, loaded_model.predict(df_final), rownames=[\n 'True'], colnames=['Predicted'], margins=True)\n\nprint(classification_report(labels, loaded_model.predict(df_final)))\n\n\ndef adjusted_classes(y_scores, t):\n return [1 if y >= t else 0 for y in y_scores]\n\n\n# Adjust decision threshold\ny_pred_adj = np.array(adjusted_classes(y_scores, 0.3))\n\n# Confusion Matrix\npd.crosstab(labels, y_pred_adj, rownames=['True'], colnames=['Predicted'], margins=True)\n\n# Classification Report\nprint(classification_report(labels, y_pred_adj))\n","sub_path":"090618_CDP_Test_Script.py","file_name":"090618_CDP_Test_Script.py","file_ext":"py","file_size_in_byte":10077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"73376443","text":"import sys\nimport os\nimport keras\nimport time\nimport numpy as np\nfrom keras.models import model_from_json\nfrom keras.preprocessing import image\nfrom keras.models import Model, load_model\nfrom keras.layers import Dense, Dropout, Activation, Flatten, GlobalAveragePooling2D\nfrom keras.optimizers import Adam, SGD\nfrom keras.callbacks import ModelCheckpoint, TensorBoard, ReduceLROnPlateau # Reference: https://keras.io/callbacks/\nimport h5py\n\nbatch_size = 32 # batch size\nepoch_count = 400 # Number of epochs to train\nimage_shape = (32, 32)\n\n# Load and augment training data\ntr_datagen = image.ImageDataGenerator(\n featurewise_center=True, # Boolean. Set input mean to 0 over the dataset, feature-wise\n samplewise_center=False, # Boolean. Set each sample mean to 0\n featurewise_std_normalization=True, # Boolean. Divide inputs by std of the dataset, feature-wise\n samplewise_std_normalization=False, # Boolean. Divide each input by its std\n zca_whitening=False, # Boolean. Apply ZCA whitening\n rotation_range=15, # Int. Degree range for random rotations\n width_shift_range=0.12, # Float. Range for random horizontal shifts\n height_shift_range=0.12, # Float. Range for random vertical shifts\n shear_range=0.2, # Float. Shear Intensity\n zoom_range=0.2, # Float. Range for random zoom\n fill_mode='nearest', # Points outside the boundaries of the input are filled according to the default nearest state\n horizontal_flip=True, # Boolean. Randomly flip inputs horizontally\n vertical_flip=False) # Boolean. Randomly flip inputs vertically\n\ntr_generator = tr_datagen.flow_from_directory(\n './Heiro_train/', # this is where the training data is\n target_size=image_shape, # all images should be resized to 32x32\n batch_size=batch_size,\n color_mode='grayscale',\n class_mode='categorical')\n\n# validation data generation and preprocessing\nval_datagen = image.ImageDataGenerator(featurewise_center=True, featurewise_std_normalization=True, rescale=None,\n rotation_range=15,\n width_shift_range=0.12,\n height_shift_range=0.12,\n shear_range=0.2,\n zoom_range=0.2,\n fill_mode='nearest',\n horizontal_flip=True)\n# this is a similar generator, for validation data\nval_generator = val_datagen.flow_from_directory(\n './Heiro_val/',\n target_size=image_shape,\n batch_size=batch_size,\n class_mode='categorical',\n color_mode='grayscale')\n\n# Load architecture\nf = open('augmented_model_architecture.json', 'r')\nmodel = model_from_json(f.read())\nf.close()\n\n# Load weights\nmodel = load_model('theweights_extra.hdf5')\nmodel.summary()\n\n# Stochastic Gradient Descent optimizer.\nsgd = SGD(lr=0.00001, momentum=0.7, decay=0.0001, nesterov=True)\n\nmodel.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])\n\n# reading current time to differentiate files in logs and submissions.\ncurrent = time.strftime(\"%c\")\n\ncheckpointer = ModelCheckpoint(filepath=\"theweights_extra_part2.hdf5\", verbose=1, save_best_only=True, monitor='val_loss')\ntb = TensorBoard(log_dir='./logsKanji/' + current, histogram_freq=0, write_graph=True, write_images=False)\n\n# Using reduce Learning rate on plateau to try to prevent saturation and overfitting by reducing the learning rate.\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=4, min_lr=1e-6)\n\n# Train model\nmodel.fit_generator(\n tr_generator,\n samples_per_epoch=1240, # amount of data we want to train on\n nb_epoch=epoch_count,\n validation_data=val_generator,\n nb_val_samples=200, # amount of data we want to validate on\n callbacks=[tb, checkpointer])\n\n\n\n","sub_path":"kanji_extra.py","file_name":"kanji_extra.py","file_ext":"py","file_size_in_byte":3865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"483873581","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# # Set Up\n\n# In[5]:\n\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport pickle as pk\nfrom collections import OrderedDict\nimport matplotlib\nfrom matplotlib import pyplot as plt\nimport matplotlib.animation as animation\nfrom timeit import default_timer as timer\nfrom IPython.display import display, clear_output, HTML\nfrom scipy import signal\n\n\n# In[6]:\n\n\n# Jupyter notebook configuration\n# Set backend of matplotlib to notebook\n# %matplotlib inline\n# get_ipython().run_line_magic('config', 'IPCompleter.greedy=False # aggresive auto-completion')\n# from IPython.core.display import display, HTML\n# display(HTML(\"\")) # Widen page of notebook\n\n\n# In[7]:\n\n\n# Paths\ndata_dir = os.path.dirname(os.path.realpath(\"__file__\"))\nholo_data_dir = os.path.join(data_dir, 'holo_ngsim_with_lane_info_v3')\noutput_dir = os.path.join(holo_data_dir, 'analysis')\nprocessed_data_dir = os.path.join(holo_data_dir, 'processed_data')\nif not os.path.exists(output_dir):\n os.mkdir(output_dir)\nif not os.path.exists(processed_data_dir):\n os.mkdir(processed_data_dir)\nfile_list = os.listdir(holo_data_dir)\ndate = '2018-12-04-10-47-15'\nmain_data_path = os.path.join(holo_data_dir, '{}.csv'.format(date))\nlane_data_path_list = [os.path.join(holo_data_dir, f) for f in file_list if date + '_lane' in f]\nlane_data_path_list.sort()\nprint(\"Data dir: {}\".format(holo_data_dir))\nprint(\"Holo data dir: {}\".format(holo_data_dir))\nprint(\"Main data path: {}\".format(main_data_path))\nprint(\"Lane Data paths:\")\nfor f in lane_data_path_list:\n print('\\t' + f)\nprint(\"Analysis results dir: {}\".format(output_dir))\nprint(\"Processed data dir: {}\".format(processed_data_dir))\n\n\n# # Load Data\n\n# In[8]:\n\n\n# Main data\nmd = pd.read_csv(main_data_path)\nmd.set_index(pd.to_datetime(md['Global_Time'], unit='ms'), inplace=True)\nmd.index.name = 'Date_Time'\n\n\n# In[9]:\n\n\nmd[:5]\n\n\n# In[10]:\n\n\n# Lane data\nld_list = [pd.read_csv(f) for f in lane_data_path_list]\nprint('Loaded data for {} lanes'.format(len(ld_list)))\n\n\n# # Data Preprocessing\n\n# ## Lane data preprocessing\n\n# In[11]:\n\n\ndef index_by_timestamp(data, timestamp_header = 'Global_Time'):\n for idx, ld in enumerate(data):\n if ld.index.name != timestamp_header:\n ld.set_index(pd.to_datetime(ld['Global_Time'], unit='ms'), inplace=True)\n# ld.index.tz_localize('Etc/GMT+8')\n ld.index.name = 'Date_Time'\n\ndef rename_headers(data):\n headers = list(data[0]) # Assumed that all lane data in data share same headers\n headers = [h for h in headers if 'Local' in h or 'Global' in h and 'Time' not in h]\n for idx, ld in enumerate(data):\n headers_renamed = [h + '_{}'.format(idx) for h in headers]\n rename_map = dict(zip(headers, headers_renamed))\n ld.rename(index=str, columns=rename_map, inplace=True)\n renamed.append(ld)\n \ndef string_to_array(s):\n if type(s) == np.ndarray:\n return s\n if '], [' in s:\n delim = '], ['\n elif '), (' in s:\n delim = '), ('\n elif '] [' in s:\n delim = '] ['\n else:\n print('Unable to determine the delimiter for parsing input string')\n s = s[2:-2] # rip two outer bracket at start and end of input: [[], [], ..., []]\n s = s.split(delim)\n s = [p.split(', ') for p in s]\n \n return np.asarray(s).astype(np.float)\n \ndef parse(data):\n print('Parsing string representations of arrays into np.array...')\n for id, ld in enumerate(data):\n headers = [h for h in list(ld) if 'Global' in h or 'Local' in h]\n headers = [h for h in headers if not 'Time' in h]\n for h in headers:\n ld[h] = ld[h].map(lambda row: string_to_array(row), na_action='ignore')\n\ndef filter_common_timestamp(data):\n print('Filtering lane data with information on all lanes...')\n stamps_list = []\n # Get a list of timestamps for each lane\n for id, ld in enumerate(data):\n stamps_list.append(set(ld.index.values))\n common_timestamps = sorted(list(set.intersection(*stamps_list)))\n for id, ld in enumerate(data):\n len_before = len(ld)\n data[id] = ld.loc[common_timestamps] # in-place modification of input data, self-assigning to ld does not modify data\n len_after = len(data[id])\n ratio = len_after / len_before\n print('Lane {}: Extracted {} / {} ({:.1%}) entries'.format(id, len_after, len_before, ratio))\n\ndef filter_out_identical_samples(data):\n print('Removing identical samples...')\n output = []\n stamps_remove = pd.DatetimeIndex([])\n for id, ld in enumerate(data):\n for pos in ['left', 'right']:\n for coord in ['global', 'local']:\n h = get_header(pos, coord)\n remove = ld[h].map(lambda row: has_identical_elements(row))\n stamps_remove = stamps_remove.union(ld.index[remove])\n for id, ld in enumerate(data):\n len_before = len(ld)\n stamps_before = ld.index\n stamps_keep = stamps_before.difference(stamps_remove)\n data[id] = ld.loc[stamps_keep]\n len_after = len(data[id])\n ratio = len_after / len_before\n print('Lane {}: Extracted {} / {} ({:.1%}) entries'.format(id, len_after, len_before, ratio))\n\ndef filter_by_x(a, xmin=None, xmax=None):\n if xmin is not None or xmax is not None:\n filter = np.ones((len(a),), dtype=bool)\n if xmin is not None:\n filter = filter & (xmin < a[:,0])\n if xmax is not None:\n filter = filter & (a[:,0] < xmax)\n idx = np.where(filter)[0]\n return a[idx]\n else:\n return a\n\ndef has_identical_elements(a):\n return np.all(a == a[0])\n\ndef concat_along_stamps(data):\n return pd.concat(data, ignore_index=False, sort=True)\n\ndef get_header(pos, coord):\n output = ''\n if pos.lower() == 'left':\n output += 'Lane_Boundary_Left_'\n elif pos == 'right':\n output += 'Lane_Boundary_Right_'\n elif pos == 'center':\n output += 'Center_Line_'\n else:\n print('Unsupported pos: {}'.format(pos))\n return ''\n if coord.lower() == 'global':\n output += 'Global'\n elif coord == 'local':\n output += 'Local'\n else:\n print('Unsupported coord: {}'.format(coord))\n return ''\n\n return output\n\ndef find_lane_shift(data, window=1, threshold=1.5):\n center_start = data['Center_Line_Global'].map(lambda a: a[0]).values\n steps = center_start[window:] - center_start[:-window]\n index = np.where(np.linalg.norm(np.vstack(steps), axis=1) > threshold)[0]\n index = index.tolist()\n index_list = index\n x_list = [center_start[i][0] for i in index]\n print('Lane {}: No. of frame of lane shift: {}'.format(idx, len(index)))\n \n return index_list, x_list\n\ndef find_lane_shift_interval(data, window=1, threshold=1.5):\n print('Detecting lane shift...')\n center_start = data['Center_Line_Global'].map(lambda a: a[0]).values\n steps = center_start[window:] - center_start[:-window]\n frame = np.where(np.linalg.norm(np.vstack(steps), axis=1) > threshold)[0]\n # Merge indices within window\n index_diff = frame[1:] - frame[:-1]\n index_frame_pre_break = np.where(index_diff >= window)[0]\n frame_pre_break = frame[index_frame_pre_break]\n frame_post_break = frame[index_frame_pre_break + 1]\n if frame_post_break[0] != frame[0]:\n frame_post_break = np.concatenate(([frame[0]], frame_post_break))\n if frame_pre_break[-1] != frame[-1]:\n frame_pre_break = np.concatenate((frame_pre_break, [frame[-1]]))\n index_list = list(zip(frame_post_break, frame_pre_break))\n x_list = [(center_start[i1][0], center_start[i2][0]) for i1, i2 in index_list]\n print('No. of interval of frame shift: {}'.format(len(index_list)))\n# print('Frame pre break:')\n# print(frame)\n# print('Index of frame pre break:')\n# print(index_frame_pre_break)\n# print('Frame pre break:')\n# print(frame_pre_break)\n# print('Index of frame post break:')\n# print(index_frame_pre_break+1)\n# print('Frame post break:')\n# print(frame_post_break)\n# print('Break frame interval:')\n# print(index_interval)\n \n return index_list, x_list\n\ndef count_valid(data):\n n_valid = len(np.where(data['Valid'] == True)[0])\n print('{} / {} ({:.1%}) entries are valid'.format(n_valid, len(data), n_valid / len(data)))\n return n_valid\n\n\n# In[12]:\n\n\nindex_by_timestamp(ld_list)\nfilter_common_timestamp(ld_list)\nparse(ld_list)\nfilter_out_identical_samples(ld_list)\n# Mark rows of data with large shift in the first lane and invalid\nfor idx, ld in enumerate(ld_list):\n print('Lane {}:'.format(idx))\n ld['Valid'] = np.ones((len(ld), )).astype(bool) # Valid by default\n lane_shift_index_list, _ = find_lane_shift_interval(ld, threshold=3, window=5)\n for start, end in lane_shift_index_list:\n# ld['Valid'].iloc[start:end] = False # this prompts pandas warning due to its internal mechanism\n ld.loc[ld.index[start:end], 'Valid'] = False\n count_valid(ld);\n\n\n# In[259]:\n\n\n# print('Saving post-processed lanes...')\n# for idx, ld in enumerate(ld_list):\n# path = lane_data_path_list[idx]\n# file_name = path.split('/')[-1]\n# output_path = os.path.join(processed_data_dir, file_name)\n# print('Saving Lane {} to {}...'.format(idx, output_path))\n# ld.to_csv(output_path, index=False, na_rep='NA', float_format='%.3f')\n\n\n# ## Main data preprocessing\n\n# In[61]:\n\n\n# # Mark rows with stamps at which lanes are valid as valid\n# print('Invalidate main data at timestamps where at least one lane is invalid...')\n# print('Before:')\n# count_valid(md);\n# index_invalid_lane = np.where(ld_list[0]['Valid'] == False)[0]\n# stamps_invalid_lane = ld_list[0].index[index_invalid_lane]\n# md.loc[stamps_invalid_lane, 'Valid'] = False\n# print('After:')\n# count_valid(md);\n\n\n# In[260]:\n\n\n# print('Saving post-processed lanes...')\n# main_data_file_name = main_data_path.split('/')[-1]\n# processed_main_data_path = os.path.join(processed_data_dir, main_data_file_name)\n# print('Saving main data to {}...'.format(processed_main_data_path))\n# md.to_csv(processed_main_data_path, index=False, na_rep='NA', float_format='%.3f')\n\n\n# # Data Analysis\n\n# ## Main data analysis\n\n# ### Invalid Odometry\n\n# In[240]:\n\n\ncount_valid(md);\n\n\n# ### Blinking vehicle (lost and then detected within short period of time)\n\n# In[13]:\n\n\ndef find_blinking_vehicle(data, window=5):\n if window < 3:\n return\n vehicles_by_stamps = data.groupby(['Date_Time'])['Vehicle_ID'].apply(list).apply(np.sort)\n vehicles_sets = np.array(([set(vs) for vs in vehicles_by_stamps]))\n lost = np.diff(vehicles_sets[::-1])[::-1] # vehicles in previous frame but not in later ones\n new = np.diff(vehicles_sets) # vehicles in later frames but not in previous ones\n vlen = np.vectorize(len) # vectorized len() function\n n_lost = vlen(lost)\n n_new = vlen(new)\n # index of transition between frames\n index_lost = np.where(n_lost != 0)[0]\n index_new = np.where(n_new != 0)[0]\n # Set sliding window over n frames or n - 1 frame transitions, where n is input window size\n trans = window - 1\n windows = [(i, i + trans) for i in range(len(vehicles_by_stamps) - trans)]\n blink_interval = []\n blink_vehicle_id = []\n for idx, w in enumerate(windows):\n index_lost_in_window = index_lost[np.where(np.logical_and(w[0] <= index_lost, index_lost < w[1]))[0]]\n index_new_in_window = index_new[np.where(np.logical_and(w[0] <= index_new, index_new < w[1]))[0]]\n if len(index_lost_in_window) != 0 and len(index_new_in_window) != 0:\n for i in index_lost_in_window:\n for j in index_new_in_window:\n if i < j:\n # A blinking vehicle lost track in previous frame and is detected again in later frames\n ids = list(set.intersection(lost[i], new[j]))\n if len(ids) > 0 and (i, j) not in blink_interval:\n # avoid duplicated frame intervals detected over different sliding window positions\n blink_interval.append((i, j))\n blink_vehicle_id.append(ids)\n blink_interval = sorted(list(set(blink_interval)))\n n_blink = len(blink_interval)\n n_trans = len(vehicles_by_stamps) - 1\n n_blinking_vehicles = np.sum([len(s) for s in blink_vehicle_id])\n n_blink_per_trans = len(blink_interval) / (len(vehicles_by_stamps) - 1)\n print('Detected {} blinking vehicles in {} / {} ({:.1%}) frame transitions'.format(n_blinking_vehicles, n_blink, n_trans, n_blink_per_trans))\n \n return blink_interval, blink_vehicle_id\n\n\n# In[242]:\n\n\nblink_interval, blink_vehicle_id = find_blinking_vehicle(md)\n\n#\n# # ### Deprecated code\n# used_id = set()\n# used_id = md['Vehicle_ID'].unique()\n# used_id.sort()\n# max_l = OrderedDict()\n# max_w = OrderedDict()\n#\n# for id in used_id:\n# rows = md[md['Vehicle_ID'] == id]\n# max_w[id] = max(rows['v_Width'])\n# max_l[id] = max(rows['v_length'])\n# fig, ax = plt.subplots(nrows=1, ncols=2)\n# ax[0].hist([max_w[k] for k in max_w])\n# ax[0].set_xlabel('width')\n# ax[1].hist([max_l[k] for k in max_l])\n# ax[1].set_xlabel('length')\n# plt.tight_layout()md['behavior'] = np.zeros(len(md)).astype(np.int)\n# dT = 0.1\n# x = list()\n# y = list()\n# vehicles = dict()\n# show_up = set()\n# vel_sum = 0\n#\n# id_map = dict()\n# discard_id = set()\n# id_cnt = 1\n# r_id_map = dict()\n#\n# for i in range(len(md)):\n# r = md.iloc[i]\n# v_id = r.Vehicle_ID\n#\n# md.at[i,'v_Width'] = max_w[v_id]\n# md.at[i,'v_length'] = max_l[v_id]\n#\n# if v_id in id_map:\n# v_id = id_map[v_id]\n# elif v_id in discard_id:\n# while id_cnt in used_id or id_cnt in discard_id:\n# id_cnt += 1\n# id_map[v_id] = id_cnt\n# r_id_map[id_cnt] = v_id\n# v_id = id_map[v_id]\n#\n# md.at[i,'Global_Time'] = md.at[i,'Frame_ID'] * 100\n# md.at[i,'Local_X'] = md.at[i,'Global_X'] - md.at[0, 'Global_X']\n# md.at[i,'Local_Y'] = md.at[i,'Global_Y'] - md.at[0, 'Global_Y']\n#\n# if v_id not in vehicles.keys():\n# vehicles[v_id] = i\n# md.at[i,'v_Acc'] = 0\n# else:\n# md.at[i,'v_Acc'] = md.at[i,'v_Vel'] - md.at[vehicles[v_id], 'v_Vel']\n#\n# show_up.add(v_id)\n#\n# if i == len(md)-1 or r.Global_Time != md.iloc[i+1].Global_Time:\n# for v_id in vehicles.keys():\n# if v_id not in show_up:\n# vehicles.remove(v_id)\n# discard_id.add(v_id)\n# id_map.remove(r_id_map(v_id))\n# print(v_id)len(discard_id)md[['Local_X', 'Local_Y', 'Global_X', 'Global_Y', 'v_Vel', 'v_Acc','v_length', 'v_Width', 'Space_Headway' ]] *= 3.28columnsTitles=[\"Local_X\",\"Local_Y\"]\n# md[[\"Local_X\",\"Local_Y\"]]=main_data.reindex(columns=columnsTitles)\n# md['Local_X'] = -main_data['Local_X']\n# ## Lane data analysis\n\n# ### Statistics\n\n# In[14]:\n\n\ndef print_statistics(data, coord, xmin=None, xmax=None, step_dist_threshold=None):\n for id, ld in enumerate(data):\n left = ld[get_header('left', coord)]\n right = ld[get_header('right', coord)]\n # Stack\n left = np.vstack(left)\n right = np.vstack(right)\n # Get samples at (c0, x0)\n left0 = np.vstack([samples[0] for samples in left])\n right0 = np.vstack([samples[0] for samples in right])\n # Filter by x\n left = filter_by_x(left, xmin=xmin, xmax=xmax)\n right = filter_by_x(right, xmin=xmin, xmax=xmax)\n left0 = filter_by_x(left0, xmin=xmin, xmax=xmax)\n right0 = filter_by_x(right0, xmin=xmin, xmax=xmax)\n # Filter out abrupt changes in step dist\n if step_dist_threshold is not None:\n left = filter_out_abrupt_change(left, step_dist_threshold)\n right = filter_out_abrupt_change(right, step_dist_threshold)\n # Statistics\n left_x_min = left[:, 0].min()\n left_x_max = left[:, 0].max()\n left_y_min = left[:, 1].min()\n left_y_max = left[:, 1].max()\n right_x_min = right[:, 0].min()\n right_x_max = right[:, 0].max()\n right_y_min = right[:, 1].min()\n right_y_max = right[:, 1].max()\n left_diff = np.diff(left0, axis=0)\n right_diff = np.diff(right0, axis=0)\n left_dist = np.sum(np.linalg.norm(left_diff, axis=1))\n right_dist = np.sum(np.linalg.norm(right_diff, axis=1))\n print('Lane {}:'.format(id))\n print(\"Left Boundary No. of samples: {}\".format(len(left)))\n print(\"Right Boundary No. of samples: {}\".format(len(right)))\n print(\"Left Boundary dist: {:.3f} km\".format(left_dist * 1e-3))\n print(\"Right Boundary dist: {:.3f} km\".format(right_dist * 1e-3))\n print('Left Boundary Global X range: [{:.0f}, {:.0f}]'.format(left_x_min, left_x_max))\n print('Left Boundary Global Y range: [{:.0f}, {:.0f}]'.format(left_y_min, left_y_max))\n print('Right Boundary Global X range: [{:.0f}, {:.0f}]'.format(right_x_min, right_x_max))\n print('Right Boundary Global Y range: [{:.0f}, {:.0f}]'.format(right_y_min, right_y_max))\n\n\n# In[288]:\n\n\n# print_statistics(ld_list, coord='global')\n\n\n# ### Frame loss\n\n# In[15]:\n\n\ndef find_frame_loss(data, threshold=50):\n frame_loss_index_list = []\n frame_loss_x_list = []\n for idx, ld in enumerate(ld_list):\n stamps = ld.index\n steps = stamps[1:] - stamps[:-1]\n index = np.where(np.array(steps > pd.Timedelta(threshold, unit='ms')))[0].tolist()\n frame_loss_index_list.append(index)\n pos = list(ld['Center_Line_Global'].iloc[index])\n frame_loss_x_list.append(pos)\n print('Lane {}: No. of frame loss: {}'.format(idx, len(index)))\n return frame_loss_index_list, frame_loss_x_list\n\n\n# In[16]:\n\n\nfind_frame_loss(ld_list);\n\n\n# ### Lane shift\n\n# In[17]:\n\n\nfind_lane_shift(ld_list[0], threshold=3, window=5);\nfind_lane_shift_interval(ld_list[0], threshold=3, window=5);\n\n\n# ### Invalid samples at initialization\n\n# In[18]:\n\n\ndef hist_samples(data, coord, xmin=None, xmax=None, step_dist_threshold=None):\n fig, axes = plt.subplots(nrows=len(ld_list), ncols=2, figsize=(10,10))\n for id, ld in enumerate(data):\n left = ld[get_header('left', coord)]\n right = ld[get_header('right', coord)]\n # Stack\n left = np.vstack(left)\n right = np.vstack(right)\n # Get samples at (c0, x0)\n left0 = np.vstack([samples[0] for samples in left])\n right0 = np.vstack([samples[0] for samples in right])\n # Filter by x\n left = filter_by_x(left, xmin=xmin, xmax=xmax)\n right = filter_by_x(right, xmin=xmin, xmax=xmax)\n left0 = filter_by_x(left0, xmin=xmin, xmax=xmax)\n right0 = filter_by_x(right0, xmin=xmin, xmax=xmax)\n # Filter out abrupt changes in step dist\n if step_dist_threshold is not None:\n left = filter_out_abrupt_change(left, step_dist_threshold)\n right = filter_out_abrupt_change(right, step_dist_threshold)\n # Statistics\n left_min = left[:, 0].min()\n left_max = left[:, 0].max()\n right_min = right[:, 0].min()\n right_max = right[:, 0].max()\n left_diff = np.diff(left0, axis=0)\n right_diff = np.diff(right0, axis=0)\n left_dist = np.sum(np.linalg.norm(left_diff, axis=1))\n right_dist = np.sum(np.linalg.norm(right_diff, axis=1))\n print('Lane {}:'.format(id))\n print(\"\\tLeft Boundary No. of samples: {}\".format(len(left)))\n print(\"\\tRight Boundary No. of samples: {}\".format(len(right)))\n print(\"\\tLeft Boundary dist: {:.3f} km\".format(left_dist * 1e-3))\n print(\"\\tRight Boundary dist: {:.3f} km\".format(right_dist * 1e-3))\n print('\\tLeft Boundary Global X range: [{}, {}]'.format(left_min, left_max))\n print('\\tRight Boundary Global X range: [{}, {}]'.format(right_min, right_max))\n # Plot\n ax_left = axes[id, 0]\n ax_right = axes[id, 1]\n ax_left.hist(left[:, 0])\n ax_right.hist(right[:, 0])\n ax_left.set_xlabel('Global_X')\n ax_left.set_title('Lane {} Left Boundary'.format(id))\n ax_right.set_xlabel('Global_X')\n ax_right.set_title('Lane {} Right Boundary'.format(id))\n plt.tight_layout()\n\n\n# In[217]:\n\n\nhist_samples(ld_list, 'global')\n\n\n# #### Interrution of lane detection\n\n# In[284]:\n\n\n# hist_samples(ld_list, 'global', xmin=4e4)\n\n\n# #### Filter out invalid samples at initialization and samples during interruption of lane detection\n\n# In[285]:\n\n\n# hist_samples(ld_list, coord='global', xmin=4e4, step_dist_threshold=100)\n\n\n# #### Abrupt changes in step distance between (x0, c0) of sampled lanes between consecutive frames\n\n# In[173]:\n\n\n# plot_step_dist(ld_list, 'global', xmin=4e4, step_dist_threshold=100)\n\n\n# ### Lane in given range of Global_X\n\n# ### Static Lane Plots\n\n# In[36]:\n\n\ndef plot_lane(data, id, coord, xmin=0, xmax=100, t=None, marker_size=5, save_dir=output_dir, downsample=None, smooth=False):\n if coord != 'global' and coord != 'local':\n print('Unsupported coord: {}'.format(coord))\n return\n fig = plt.figure(figsize=(20, 10))\n if t is not None:\n left = data[id][get_header('left', coord)].iloc[t]\n right = data[id][get_header('right', coord)].iloc[t]\n else:\n left = data[id][get_header('left', coord)]\n right = data[id][get_header('right', coord)]\n if downsample is not None:\n left = [a[::downsample] for a in left]\n right = [a[::downsample] for a in right]\n left = np.vstack(left)\n right = np.vstack(right)\n left = filter_by_x(left, xmin, xmax)\n right = filter_by_x(right, xmin, xmax)\n # Smoothing\n if smooth:\n left = signal.savgol_filter(left, window_length=401, polyorder=3, deriv=0, axis=0)\n right = signal.savgol_filter(right, window_length=401, polyorder=3, deriv=0, axis=0)\n plt.scatter(left[:, 0], left[:, 1], s=marker_size)\n plt.scatter(right[:, 0], right[:, 1], s=marker_size)\n plt.title('Lane {}'.format(id + 1))\n plt.xlabel('{}_X'.format(coord))\n plt.ylabel('{}_Y'.format(coord))\n plt.tight_layout()\n suffix = ''\n if downsample is not None:\n suffix = '_downsample_{}'.format(downsample)\n fig.savefig(os.path.join(save_dir, 'lane_{}_{}{}.png'.format(id, coord, suffix)))\n\ndef plot_lanes(data, coord, xmin=0, xmax=100, t=None, marker_size=5, save_dir=output_dir, downsample=None, sample=False, smooth=False):\n if coord != 'global' and coord != 'local':\n print('Unsupported coord: {}'.format(coord))\n return\n fig, axes = plt.subplots(nrows=1, ncols=len(ld_list), figsize=(20, 5))\n for id, ld in enumerate(data):\n clear_output(wait=True)\n display('Plotting data for lane {}/{}'.format(id, len(ld_list) - 1))\n if t is not None:\n left = data[id][get_header('left', coord)].iloc[t]\n right = data[id][get_header('right', coord)].iloc[t]\n else:\n left = data[id][get_header('left', coord)]\n right = data[id][get_header('right', coord)]\n if downsample is not None:\n left = [a[::downsample] for a in left]\n right = [a[::downsample] for a in right]\n left = np.vstack(left)\n right = np.vstack(right)\n # Smoothing\n if smooth:\n left = signal.savgol_filter(left, window_length=401, polyorder=3, deriv=0, axis=0)\n right = signal.savgol_filter(right, window_length=401, polyorder=3, deriv=0, axis=0)\n left = filter_by_x(left, xmin, xmax)\n right = filter_by_x(right, xmin, xmax)\n ax = axes[id]\n ax.scatter(left[:, 0], left[:, 1], s=marker_size)\n ax.scatter(right[:, 0], right[:, 1], s=marker_size)\n ax.set_title('Lane {}'.format(id + 1))\n ax.set_xlabel('{}_X'.format(coord))\n ax.set_ylabel('{}_Y'.format(coord))\n plt.tight_layout()\n suffix = ''\n if downsample is not None:\n suffix = '_downsample_{}'.format(downsample)\n fig.savefig(os.path.join(save_dir, 'lane_{}{}.png'.format(coord, suffix)))\n \ndef plot_road(data, coord, xmin=None, xmax=None, t=None, marker_size=5, save_dir=output_dir, downsample=None, smooth=False):\n fig = plt.figure(figsize=(20, 5))\n colors = ['orange', 'cornflowerblue', 'red', 'green', 'yellow', 'magenta', 'cyan', 'forestgreen', 'gold', 'hotpink']\n for id, ld in enumerate(ld_list):\n clear_output(wait=True)\n display('Plotting data for lane {}/{}'.format(id, len(ld_list) - 1))\n if t is not None:\n left = data[id][get_header('left', coord)].iloc[t]\n right = data[id][get_header('right', coord)].iloc[t]\n else:\n left = data[id][get_header('left', coord)]\n right = data[id][get_header('right', coord)]\n if downsample is not None:\n left = [a[::downsample] for a in left]\n right = [a[::downsample] for a in right]\n left = np.vstack(left)\n right = np.vstack(right)\n # Smoothing\n if smooth:\n left = signal.savgol_filter(left, window_length=401, polyorder=3, deriv=0, axis=0)\n right = signal.savgol_filter(right, window_length=401, polyorder=3, deriv=0, axis=0)\n left = filter_by_x(left, xmin, xmax)\n right = filter_by_x(right, xmin, xmax)\n # Plot samples acoording to the order in which they are sampled (i.e. w.r.t to x-distance from (x0, c0))\n# for i in range(4):\n# plt.scatter(left[i::10, 0], left[i::10, 1], s=marker_size, c=colors[i])\n# plt.scatter(right[i::10, 0], right[i::10, 1], s=marker_size, c=colors[i])\n plt.scatter(left[:, 0], left[:, 1], s=marker_size, c=colors[id])\n plt.scatter(right[:, 0], right[:, 1], s=marker_size, c=colors[id])\n plt.title('Overlayed {} Lanes'.format(len(ld_list)))\n plt.xlabel('{}_X'.format(coord))\n plt.ylabel('{}_Y'.format(coord))\n plt.tight_layout()\n suffix = ''\n if downsample is not None:\n suffix = '_downsample_{}'.format(downsample)\n plt.savefig(os.path.join(save_dir, 'road_{}{}.png'.format(coord, suffix)))\n \n return fig\n\ndef plot_vertical_span(intervals, alpha=1.0):\n for pre, post in intervals:\n if abs(post-pre) < 1:\n plt.axvline(x=pre, alpha=alpha)\n else:\n # This will only plot if abs(xmax-xmin) is greater than lowest precision for plotting\n plt.axvspan(xmin=pre, xmax=post, alpha=alpha)\n\n\n# #### Single lane\n\n# In[42]:\n\n\nplot_lane(data=ld_list, id=0, coord='global', xmin=464600, xmax=464700, marker_size=1)\nplt.show()\n\n\n# In[43]:\n\n\n# Smoothed lane\nplot_lane(data=ld_list, id=0, coord='global', xmin=464600, xmax=464700, marker_size=1, smooth=True)\nplt.show()\n\n\n# #### Separate lanes\n\n# In[44]:\n\n\nplot_lanes(data=ld_list, coord='global', xmin=464600, xmax=464700, marker_size=1)\nplt.show()\n\n\n# #### Lanes superimposed\n\n# In[45]:\n\n\n# Noticeable lane shift at x=[464300, 464500]\nplot_road(data=ld_list, coord='global', xmin=464300, xmax=464500, marker_size=5, smooth=True);\nplt.show()\n\n\n# In[46]:\n\n\nplot_road(data=ld_list, coord='global', marker_size=0.1, smooth=True);\nlane_shift_index_list, lane_shift_pos_interval = find_lane_shift_interval(ld_list[0], threshold=3, window=5) # threshold=3 and window=5 work well\nplot_vertical_span(lane_shift_pos_interval)\nplt.show()\n\n\n# #### Separate lanes at given time\n\n# In[24]:\n\n\nplot_lanes(data=ld_list, coord='local', t=10000, marker_size=50)\nplt.show()\n\n\n# #### Lanes superimposed at given time\n\n# In[25]:\n\n\nplot_road(data=ld_list, coord='local', t=10000, marker_size=50);\nplt.show()\n\n\n# In[26]:\n\n\nplot_road(data=ld_list, coord='global', t=10000, marker_size=50);\n\nplt.show()\n\n\n# ### Animated Lane Plots\n\n# In[27]:\n\n\ndef get_window(data, coord, idx, type='sliding'):\n samples_list = []\n for ld in data:\n if type == 'sliding':\n left = ld[get_header('left', coord)].iloc[idx]\n right = ld[get_header('right', coord)].iloc[idx]\n elif type == 'containing':\n left = ld[get_header('left', coord)].iloc[idx[0]:idx[1]] if idx[0] != idx[1] else ld[get_header('left', coord)].iloc[idx[0]]\n right = ld[get_header('right', coord)].iloc[idx[0]:idx[1]] if idx[0] != idx[1] else ld[get_header('right', coord)].iloc[idx[0]]\n left = np.vstack(left)\n right = np.vstack(right)\n else:\n print('Unsupported window type: {}'.format(type))\n samples_list.append(left)\n samples_list.append(right)\n samples_list = np.vstack(samples_list)\n min = np.min(samples_list, axis=0)\n max = np.max(samples_list, axis=0)\n xmin = min[0]\n xmax = max[0]\n ymin = min[1]\n ymax = max[1]\n \n return xmin, xmax, ymin, ymax\n\ndef swap_column(a):\n a.T[[1, 0]] = a.T[[0, 1]]\n \n return a\n\ndef animate_road(data, coord, frames=100, interval=50, downsample=None,\n window=None, window_type='sliding', hold=False, plot_type='line', marker_size=5,\n save_dir=output_dir, save_fps=20, return_video=False):\n \"\"\"\n @param frame: integer, list, tuple\n when frame is integer it will be treated as range(frames)\n when frame is tuple (a, b), it will be treated as list(range(a, b))\n when frame is tuple (a, b, c, ..., n), it will be treated as list(frames)\n @param interval: interval in ms between consecutive frames of HTML5 video, default is 50, corresponding to a frame rate of 20Hz\n @output anim: animation instance\n @output video(optional): if return_video=True, the function will return video as a HTML5 video tag\n \"\"\"\n colors = ['orange', 'cornflowerblue', 'red']\n fig = plt.figure(figsize=(10, 5))\n if coord == 'local':\n ax = plt.axes(xlim=(0, 50), ylim=(-10, 10))\n elif coord == 'global':\n ax = plt.gca()\n plt.xlabel('{}_X'.format(coord))\n plt.ylabel('{}_Y'.format(coord))\n title_base = 'Overlayed {} Lanes, frame '.format(len(data))\n title = plt.title(title_base + '0')\n# title = ax.text(0, 1.05, '', transform = ax.transAxes, va='center')\n plots = []\n for idx, ld in enumerate(data):\n if plot_type == 'line':\n plots.append(ax.plot([], [], c=colors[idx], marker='o')[0])\n plots.append(ax.plot([], [], c=colors[idx], marker='o')[0])\n elif plot_type == 'scatter':\n plots.append(ax.scatter([], [], s=marker_size, c=colors[idx]))\n plots.append(ax.scatter([], [], s=marker_size, c=colors[idx]))\n else:\n print('Unsupported plot type: {}'.format(plot_type))\n return\n \n def init():\n for plot in plots:\n if plot_type == 'line':\n plot.set_data([], [])\n elif plot_type == 'scatter':\n plot.set_offsets([])\n else:\n print('Unsupported plot type: {}'.format(plot_type))\n return\n title.set_text(title_base + '0')\n return plots\n\n # convert frames to list to unify pipeline below\n num_iter = 0\n if isinstance(frames, int):\n frames = list(range(frames))\n elif isinstance(frames, tuple):\n if len(frames) == 2:\n frames = list(range(frames[0], frames[-1]))\n else:\n frames = list(frames)\n else:\n print('Unsupported input type for frame: {}'.format(type(frames)))\n return\n num_iter = len(frames)\n \n def animate(t):\n # intialize\n if t == 0:\n animate.counter = 0\n start = timer()\n # update data\n for idx, ld in enumerate(data):\n if hold == False:\n left = data[idx][get_header('left', coord)].iloc[t]\n right = data[idx][get_header('right', coord)].iloc[t]\n else:\n left = data[idx][get_header('left', coord)].iloc[frames[0]:t] if frames[0] != t else data[idx][get_header('left', coord)].iloc[t]\n right = data[idx][get_header('right', coord)].iloc[frames[0]:t] if frames[0] != t else data[idx][get_header('right', coord)].iloc[t]\n if downsample is not None:\n left = [a[::downsample] for a in left]\n right = [a[::downsample] for a in right]\n left = np.vstack(left)\n right = np.vstack(right)\n if plot_type == 'line':\n plots[idx * 2].set_data(left[:, 0], left[:, 1])\n plots[idx * 2 + 1].set_data(right[:, 0], right[:, 1])\n elif plot_type == 'scatter':\n plots[idx * 2].set_offsets(left)\n plots[idx * 2 + 1].set_offsets(right)\n title.set_text(title_base + str(t))\n # Set axes limits for global lanes\n if coord == 'global':\n if window is None:\n if window_type == 'sliding':\n xmin, xmax, ymin, ymax = get_window(data, coord=coord, type=window_type, idx=t)\n elif window_type == 'containing':\n xmin, xmax, ymin, ymax = get_window(data, coord=coord, type=window_type, idx=(frames[0], t))\n else:\n print('Unsupported window type: {}'.format(window_type))\n else:\n xmin, xmax, ymin, ymax = window\n ax.set_xlim((xmin - 5, xmax + 5))\n ax.set_ylim((ymin - 5, ymax + 5))\n # Update counter\n animate.counter += 1\n clear_output(wait=True)\n num_left = 0\n eta = (num_iter - animate.counter) / animate.counter * (timer() - animate.start)\n display('Generating frame {} / {} frames, ETA: {:.1f}s'.format(animate.counter, num_iter, eta))\n return plots\n \n def init_animate():\n animate.counter = 0\n animate.start = timer()\n\n anim = animation.FuncAnimation(fig, animate, init_func=init, frames=frames, interval=interval, blit=True)\n plt.close()\n\n # Save video\n suffix = ''\n if len(frames) == 1:\n suffix = '{}_{}'.format(plot_type, str(frames))\n elif len(frames) > 1:\n suffix = '{}_{}_{}'.format(plot_type, frames[0], frames[-1])\n output_path = os.path.join(output_dir, 'road_{}_animation_{}.mp4'.format(coord, suffix))\n print('Saving animation to {}'.format(output_path))\n init_animate()\n anim.save(filename=output_path, fps=save_fps)\n \n # Output animation instance as HTML5 video tag\n if return_video:\n print('Generating HTML5 video')\n init_animate()\n video = HTML(anim.to_html5_video()) # this is equivalent to rc('animation', html='html5') and then call anim\n return anim, video\n else:\n anim\n\n\n# #### Local 50 frames (for debugging)\n\n# In[33]:\n\n\n# al1, vl1 = animate_road(data=ld_list, coord='local', frames=(500, 550), interval=50, return_video=True)\n\n\n# In[34]:\n\n\n# vl1\n\n\n# #### All frames\n\n# In[ ]:\n\n\n# almax, vlmax = animate_road(data=ld_list, coord='local', frames=len(ld_list[0]), interval=50) # Assumed that lane data in ld_list has same lengths\n\n\n# #### Global 50 frames (local window, for debugging)\n\n# In[35]:\n\n\n# ag1, vg1 = animate_road(data=ld_list, coord='global', frames=(500, 550), interval=50, return_video=True)\n\n\n# In[36]:\n\n\n# vg1\n\n\n# #### All frames\n\n# In[225]:\n\n\n# Might need to increase size limit on embedding video\n# plt.rcParams['animation.embed_limit'] = 25e6\n# agmax = animate_road(data=ld_list, coord='global', frames=len(ld_list[0]), interval=50) # Assumed that lane data in ld_list has same lengths\n\n\n# #### 50 frames (global window, for debugging)\n\n# In[97]:\n\n\n# ags1, vgs1 = animate_road(data=ld_list, coord='global', frames=(500, 550), interval=50,\n# window=(4.6112e5, 4.6115e5, 4.43214e6, 4.43217e6), hold=True, plot_type='scatter', marker_size=0.1,\n# return_video=True)\n\n\n# In[98]:\n\n\n# vgs1\n\n\n# #### 1500 frames (global window)\n\n# In[173]:\n\n\n# ags2 = animate_road(data=ld_list, coord='global', frames=(1500, 3000), interval=50,\n# window=(4.611e5, 4.616e5, 4.4321e6, 4.4322e6), hold=True, plot_type='scatter', marker_size=0.1,\n# return_video=False)\n\n\n# #### All frames (local window)\n\n# In[187]:\n\n\n# agsmax = animate_road(data=ld_list, coord='global', frames=len(ld_list[0]), interval=50,\n# hold=True, plot_type='scatter', marker_size=0.1,\n# return_video=False)\n\n# key_frames = list(np.linspace(0, len(ld_list[0]) - 1, 50).astype(int))\n# slices = list(zip(key_frames[:-1], key_frames[1:]))\n# for slice in slices:\n# agsmax = animate_road(data=ld_list, coord='global', frames=slice, interval=50,\n# hold=True, plot_type='scatter', marker_size=0.1, downsample=10,\n# return_video=False)","sub_path":"data/analyze_holo_data.py","file_name":"analyze_holo_data.py","file_ext":"py","file_size_in_byte":36729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"62760672","text":"import logging\nimport dotenv\nimport os\n\nfrom pathlib import Path\nfrom app import helpers\n\ndotenv_path = Path(__file__).parent.parent.parent / '.env'\ndotenv.load_dotenv(dotenv_path)\n\n\n# Config values\nAPP_NAME = os.environ.get('APP_NAME', default='bits')\nAPP_ENV = os.environ.get('APP_ENV', default='production')\nAPP_DEBUG = helpers.to_bool(os.environ.get('APP_DEBUG'))\nLOG_LVL = logging.getLevelName(os.environ['LOG_LVL'])\n\nREDIS_HOST = os.environ['REDIS_HOST']\nREDIS_PORT = os.environ['REDIS_PORT']\nREDIS_PASSWORD = os.environ['REDIS_PASSWORD']\n\n# non production environments\nif APP_ENV in ['development', 'test']:\n # in production, project id is inferred from credentials\n FIRESTORE_PROJECT_ID = os.environ.get('FIRESTORE_PROJECT_ID', default='bits')\n __emulator_host_env = 'FIRESTORE_EMULATOR_HOST'\n if __emulator_host_env not in os.environ:\n os.environ[__emulator_host_env] = 'localhost:8081'\n\n# Logging config\nlogging.basicConfig(level=LOG_LVL, \n format='%(asctime)s| %(levelname)-8s| %(name)s - %(message)s')\n","sub_path":"backend/app/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"550496546","text":"import os\nimport cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n# Set the working directory to be the current one\nos.chdir(os.path.dirname(os.path.abspath(__file__)))\n\n# Load gray images\nimg1 = cv2.imread('box.png', 0) # queryImage\nimg2 = cv2.imread('box_in_scene.png', 0) # trainImage\n\n# SIFT\nsift = cv2.xfeatures2d.SIFT_create()\nkeypoints1, descriptors1 = sift.detectAndCompute(img1, None)\nkeypoints2, descriptors2 = sift.detectAndCompute(img2, None)\n\n# Brute-Force matching\nbf = cv2.BFMatcher()\nmatches = bf.knnMatch(descriptors1, descriptors2, k=2)\n\n# Apply ratio test\ngood = []\nfor m,n in matches:\n if m.distance < 0.75*n.distance:\n good.append([m])\n\n# cv2.drawMatchesKnn expects list of lists as matches.\nimg3 = cv2.drawMatchesKnn(img1, keypoints1, img2, keypoints2, good, None, flags=2)\n\nplt.imshow(img3)\nplt.title('SIFT Features + Brute-Force Matching (knn)')\nplt.xticks([]), plt.yticks([])\nplt.show()","sub_path":"17_feature_matching/02_sift_brute_force_matching_knn.py","file_name":"02_sift_brute_force_matching_knn.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"405500663","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import timedelta\nfrom itertools import product\nimport nose\nimport re\nimport warnings\n\nfrom pandas import (date_range, MultiIndex, Index, CategoricalIndex,\n compat)\nfrom pandas.core.common import PerformanceWarning\nfrom pandas.indexes.base import InvalidIndexError\nfrom pandas.compat import range, lrange, u, PY3, long, lzip\n\nimport numpy as np\n\nfrom pandas.util.testing import (assert_almost_equal, assertRaisesRegexp,\n assert_copy)\n\nimport pandas.util.testing as tm\n\nimport pandas as pd\nfrom pandas.lib import Timestamp\n\nfrom .common import Base\n\n\nclass TestMultiIndex(Base, tm.TestCase):\n _holder = MultiIndex\n _multiprocess_can_split_ = True\n _compat_props = ['shape', 'ndim', 'size', 'itemsize']\n\n def setUp(self):\n major_axis = Index(['foo', 'bar', 'baz', 'qux'])\n minor_axis = Index(['one', 'two'])\n\n major_labels = np.array([0, 0, 1, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 1, 0, 1])\n self.index_names = ['first', 'second']\n self.indices = dict(index=MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels\n ], names=self.index_names,\n verify_integrity=False))\n self.setup_indices()\n\n def create_index(self):\n return self.index\n\n def test_boolean_context_compat2(self):\n\n # boolean context compat\n # GH7897\n i1 = MultiIndex.from_tuples([('A', 1), ('A', 2)])\n i2 = MultiIndex.from_tuples([('A', 1), ('A', 3)])\n common = i1.intersection(i2)\n\n def f():\n if common:\n pass\n\n tm.assertRaisesRegexp(ValueError, 'The truth value of a', f)\n\n def test_labels_dtypes(self):\n\n # GH 8456\n i = MultiIndex.from_tuples([('A', 1), ('A', 2)])\n self.assertTrue(i.labels[0].dtype == 'int8')\n self.assertTrue(i.labels[1].dtype == 'int8')\n\n i = MultiIndex.from_product([['a'], range(40)])\n self.assertTrue(i.labels[1].dtype == 'int8')\n i = MultiIndex.from_product([['a'], range(400)])\n self.assertTrue(i.labels[1].dtype == 'int16')\n i = MultiIndex.from_product([['a'], range(40000)])\n self.assertTrue(i.labels[1].dtype == 'int32')\n\n i = pd.MultiIndex.from_product([['a'], range(1000)])\n self.assertTrue((i.labels[0] >= 0).all())\n self.assertTrue((i.labels[1] >= 0).all())\n\n def test_set_name_methods(self):\n # so long as these are synonyms, we don't need to test set_names\n self.assertEqual(self.index.rename, self.index.set_names)\n new_names = [name + \"SUFFIX\" for name in self.index_names]\n ind = self.index.set_names(new_names)\n self.assertEqual(self.index.names, self.index_names)\n self.assertEqual(ind.names, new_names)\n with assertRaisesRegexp(ValueError, \"^Length\"):\n ind.set_names(new_names + new_names)\n new_names2 = [name + \"SUFFIX2\" for name in new_names]\n res = ind.set_names(new_names2, inplace=True)\n self.assertIsNone(res)\n self.assertEqual(ind.names, new_names2)\n\n # set names for specific level (# GH7792)\n ind = self.index.set_names(new_names[0], level=0)\n self.assertEqual(self.index.names, self.index_names)\n self.assertEqual(ind.names, [new_names[0], self.index_names[1]])\n\n res = ind.set_names(new_names2[0], level=0, inplace=True)\n self.assertIsNone(res)\n self.assertEqual(ind.names, [new_names2[0], self.index_names[1]])\n\n # set names for multiple levels\n ind = self.index.set_names(new_names, level=[0, 1])\n self.assertEqual(self.index.names, self.index_names)\n self.assertEqual(ind.names, new_names)\n\n res = ind.set_names(new_names2, level=[0, 1], inplace=True)\n self.assertIsNone(res)\n self.assertEqual(ind.names, new_names2)\n\n def test_set_levels(self):\n # side note - you probably wouldn't want to use levels and labels\n # directly like this - but it is possible.\n levels = self.index.levels\n new_levels = [[lev + 'a' for lev in level] for level in levels]\n\n def assert_matching(actual, expected):\n # avoid specifying internal representation\n # as much as possible\n self.assertEqual(len(actual), len(expected))\n for act, exp in zip(actual, expected):\n act = np.asarray(act)\n exp = np.asarray(exp)\n assert_almost_equal(act, exp)\n\n # level changing [w/o mutation]\n ind2 = self.index.set_levels(new_levels)\n assert_matching(ind2.levels, new_levels)\n assert_matching(self.index.levels, levels)\n\n # level changing [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_levels(new_levels, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.levels, new_levels)\n\n # level changing specific level [w/o mutation]\n ind2 = self.index.set_levels(new_levels[0], level=0)\n assert_matching(ind2.levels, [new_levels[0], levels[1]])\n assert_matching(self.index.levels, levels)\n\n ind2 = self.index.set_levels(new_levels[1], level=1)\n assert_matching(ind2.levels, [levels[0], new_levels[1]])\n assert_matching(self.index.levels, levels)\n\n # level changing multiple levels [w/o mutation]\n ind2 = self.index.set_levels(new_levels, level=[0, 1])\n assert_matching(ind2.levels, new_levels)\n assert_matching(self.index.levels, levels)\n\n # level changing specific level [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_levels(new_levels[0], level=0, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.levels, [new_levels[0], levels[1]])\n assert_matching(self.index.levels, levels)\n\n ind2 = self.index.copy()\n inplace_return = ind2.set_levels(new_levels[1], level=1, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.levels, [levels[0], new_levels[1]])\n assert_matching(self.index.levels, levels)\n\n # level changing multiple levels [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_levels(new_levels, level=[0, 1],\n inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.levels, new_levels)\n assert_matching(self.index.levels, levels)\n\n def test_set_labels(self):\n # side note - you probably wouldn't want to use levels and labels\n # directly like this - but it is possible.\n labels = self.index.labels\n major_labels, minor_labels = labels\n major_labels = [(x + 1) % 3 for x in major_labels]\n minor_labels = [(x + 1) % 1 for x in minor_labels]\n new_labels = [major_labels, minor_labels]\n\n def assert_matching(actual, expected):\n # avoid specifying internal representation\n # as much as possible\n self.assertEqual(len(actual), len(expected))\n for act, exp in zip(actual, expected):\n act = np.asarray(act)\n exp = np.asarray(exp)\n assert_almost_equal(act, exp)\n\n # label changing [w/o mutation]\n ind2 = self.index.set_labels(new_labels)\n assert_matching(ind2.labels, new_labels)\n assert_matching(self.index.labels, labels)\n\n # label changing [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_labels(new_labels, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.labels, new_labels)\n\n # label changing specific level [w/o mutation]\n ind2 = self.index.set_labels(new_labels[0], level=0)\n assert_matching(ind2.labels, [new_labels[0], labels[1]])\n assert_matching(self.index.labels, labels)\n\n ind2 = self.index.set_labels(new_labels[1], level=1)\n assert_matching(ind2.labels, [labels[0], new_labels[1]])\n assert_matching(self.index.labels, labels)\n\n # label changing multiple levels [w/o mutation]\n ind2 = self.index.set_labels(new_labels, level=[0, 1])\n assert_matching(ind2.labels, new_labels)\n assert_matching(self.index.labels, labels)\n\n # label changing specific level [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_labels(new_labels[0], level=0, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.labels, [new_labels[0], labels[1]])\n assert_matching(self.index.labels, labels)\n\n ind2 = self.index.copy()\n inplace_return = ind2.set_labels(new_labels[1], level=1, inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.labels, [labels[0], new_labels[1]])\n assert_matching(self.index.labels, labels)\n\n # label changing multiple levels [w/ mutation]\n ind2 = self.index.copy()\n inplace_return = ind2.set_labels(new_labels, level=[0, 1],\n inplace=True)\n self.assertIsNone(inplace_return)\n assert_matching(ind2.labels, new_labels)\n assert_matching(self.index.labels, labels)\n\n def test_set_levels_labels_names_bad_input(self):\n levels, labels = self.index.levels, self.index.labels\n names = self.index.names\n\n with tm.assertRaisesRegexp(ValueError, 'Length of levels'):\n self.index.set_levels([levels[0]])\n\n with tm.assertRaisesRegexp(ValueError, 'Length of labels'):\n self.index.set_labels([labels[0]])\n\n with tm.assertRaisesRegexp(ValueError, 'Length of names'):\n self.index.set_names([names[0]])\n\n # shouldn't scalar data error, instead should demand list-like\n with tm.assertRaisesRegexp(TypeError, 'list of lists-like'):\n self.index.set_levels(levels[0])\n\n # shouldn't scalar data error, instead should demand list-like\n with tm.assertRaisesRegexp(TypeError, 'list of lists-like'):\n self.index.set_labels(labels[0])\n\n # shouldn't scalar data error, instead should demand list-like\n with tm.assertRaisesRegexp(TypeError, 'list-like'):\n self.index.set_names(names[0])\n\n # should have equal lengths\n with tm.assertRaisesRegexp(TypeError, 'list of lists-like'):\n self.index.set_levels(levels[0], level=[0, 1])\n\n with tm.assertRaisesRegexp(TypeError, 'list-like'):\n self.index.set_levels(levels, level=0)\n\n # should have equal lengths\n with tm.assertRaisesRegexp(TypeError, 'list of lists-like'):\n self.index.set_labels(labels[0], level=[0, 1])\n\n with tm.assertRaisesRegexp(TypeError, 'list-like'):\n self.index.set_labels(labels, level=0)\n\n # should have equal lengths\n with tm.assertRaisesRegexp(ValueError, 'Length of names'):\n self.index.set_names(names[0], level=[0, 1])\n\n with tm.assertRaisesRegexp(TypeError, 'string'):\n self.index.set_names(names, level=0)\n\n def test_metadata_immutable(self):\n levels, labels = self.index.levels, self.index.labels\n # shouldn't be able to set at either the top level or base level\n mutable_regex = re.compile('does not support mutable operations')\n with assertRaisesRegexp(TypeError, mutable_regex):\n levels[0] = levels[0]\n with assertRaisesRegexp(TypeError, mutable_regex):\n levels[0][0] = levels[0][0]\n # ditto for labels\n with assertRaisesRegexp(TypeError, mutable_regex):\n labels[0] = labels[0]\n with assertRaisesRegexp(TypeError, mutable_regex):\n labels[0][0] = labels[0][0]\n # and for names\n names = self.index.names\n with assertRaisesRegexp(TypeError, mutable_regex):\n names[0] = names[0]\n\n def test_inplace_mutation_resets_values(self):\n levels = [['a', 'b', 'c'], [4]]\n levels2 = [[1, 2, 3], ['a']]\n labels = [[0, 1, 0, 2, 2, 0], [0, 0, 0, 0, 0, 0]]\n mi1 = MultiIndex(levels=levels, labels=labels)\n mi2 = MultiIndex(levels=levels2, labels=labels)\n vals = mi1.values.copy()\n vals2 = mi2.values.copy()\n self.assertIsNotNone(mi1._tuples)\n\n # make sure level setting works\n new_vals = mi1.set_levels(levels2).values\n assert_almost_equal(vals2, new_vals)\n # non-inplace doesn't kill _tuples [implementation detail]\n assert_almost_equal(mi1._tuples, vals)\n # and values is still same too\n assert_almost_equal(mi1.values, vals)\n\n # inplace should kill _tuples\n mi1.set_levels(levels2, inplace=True)\n assert_almost_equal(mi1.values, vals2)\n\n # make sure label setting works too\n labels2 = [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]\n exp_values = np.empty((6, ), dtype=object)\n exp_values[:] = [(long(1), 'a')] * 6\n # must be 1d array of tuples\n self.assertEqual(exp_values.shape, (6, ))\n new_values = mi2.set_labels(labels2).values\n # not inplace shouldn't change\n assert_almost_equal(mi2._tuples, vals2)\n # should have correct values\n assert_almost_equal(exp_values, new_values)\n\n # and again setting inplace should kill _tuples, etc\n mi2.set_labels(labels2, inplace=True)\n assert_almost_equal(mi2.values, new_values)\n\n def test_copy_in_constructor(self):\n levels = np.array([\"a\", \"b\", \"c\"])\n labels = np.array([1, 1, 2, 0, 0, 1, 1])\n val = labels[0]\n mi = MultiIndex(levels=[levels, levels], labels=[labels, labels],\n copy=True)\n self.assertEqual(mi.labels[0][0], val)\n labels[0] = 15\n self.assertEqual(mi.labels[0][0], val)\n val = levels[0]\n levels[0] = \"PANDA\"\n self.assertEqual(mi.levels[0][0], val)\n\n def test_set_value_keeps_names(self):\n # motivating example from #3742\n lev1 = ['hans', 'hans', 'hans', 'grethe', 'grethe', 'grethe']\n lev2 = ['1', '2', '3'] * 2\n idx = pd.MultiIndex.from_arrays([lev1, lev2], names=['Name', 'Number'])\n df = pd.DataFrame(\n np.random.randn(6, 4),\n columns=['one', 'two', 'three', 'four'],\n index=idx)\n df = df.sortlevel()\n self.assertIsNone(df.is_copy)\n self.assertEqual(df.index.names, ('Name', 'Number'))\n df = df.set_value(('grethe', '4'), 'one', 99.34)\n self.assertIsNone(df.is_copy)\n self.assertEqual(df.index.names, ('Name', 'Number'))\n\n def test_names(self):\n\n # names are assigned in __init__\n names = self.index_names\n level_names = [level.name for level in self.index.levels]\n self.assertEqual(names, level_names)\n\n # setting bad names on existing\n index = self.index\n assertRaisesRegexp(ValueError, \"^Length of names\", setattr, index,\n \"names\", list(index.names) + [\"third\"])\n assertRaisesRegexp(ValueError, \"^Length of names\", setattr, index,\n \"names\", [])\n\n # initializing with bad names (should always be equivalent)\n major_axis, minor_axis = self.index.levels\n major_labels, minor_labels = self.index.labels\n assertRaisesRegexp(ValueError, \"^Length of names\", MultiIndex,\n levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels],\n names=['first'])\n assertRaisesRegexp(ValueError, \"^Length of names\", MultiIndex,\n levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels],\n names=['first', 'second', 'third'])\n\n # names are assigned\n index.names = [\"a\", \"b\"]\n ind_names = list(index.names)\n level_names = [level.name for level in index.levels]\n self.assertEqual(ind_names, level_names)\n\n def test_reference_duplicate_name(self):\n idx = MultiIndex.from_tuples(\n [('a', 'b'), ('c', 'd')], names=['x', 'x'])\n self.assertTrue(idx._reference_duplicate_name('x'))\n\n idx = MultiIndex.from_tuples(\n [('a', 'b'), ('c', 'd')], names=['x', 'y'])\n self.assertFalse(idx._reference_duplicate_name('x'))\n\n def test_astype(self):\n expected = self.index.copy()\n actual = self.index.astype('O')\n assert_copy(actual.levels, expected.levels)\n assert_copy(actual.labels, expected.labels)\n self.check_level_names(actual, expected.names)\n\n with assertRaisesRegexp(TypeError, \"^Setting.*dtype.*object\"):\n self.index.astype(np.dtype(int))\n\n def test_constructor_single_level(self):\n single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']],\n labels=[[0, 1, 2, 3]], names=['first'])\n tm.assertIsInstance(single_level, Index)\n self.assertNotIsInstance(single_level, MultiIndex)\n self.assertEqual(single_level.name, 'first')\n\n single_level = MultiIndex(levels=[['foo', 'bar', 'baz', 'qux']],\n labels=[[0, 1, 2, 3]])\n self.assertIsNone(single_level.name)\n\n def test_constructor_no_levels(self):\n assertRaisesRegexp(ValueError, \"non-zero number of levels/labels\",\n MultiIndex, levels=[], labels=[])\n both_re = re.compile('Must pass both levels and labels')\n with tm.assertRaisesRegexp(TypeError, both_re):\n MultiIndex(levels=[])\n with tm.assertRaisesRegexp(TypeError, both_re):\n MultiIndex(labels=[])\n\n def test_constructor_mismatched_label_levels(self):\n labels = [np.array([1]), np.array([2]), np.array([3])]\n levels = [\"a\"]\n assertRaisesRegexp(ValueError, \"Length of levels and labels must be\"\n \" the same\", MultiIndex, levels=levels,\n labels=labels)\n length_error = re.compile('>= length of level')\n label_error = re.compile(r'Unequal label lengths: \\[4, 2\\]')\n\n # important to check that it's looking at the right thing.\n with tm.assertRaisesRegexp(ValueError, length_error):\n MultiIndex(levels=[['a'], ['b']],\n labels=[[0, 1, 2, 3], [0, 3, 4, 1]])\n\n with tm.assertRaisesRegexp(ValueError, label_error):\n MultiIndex(levels=[['a'], ['b']], labels=[[0, 0, 0, 0], [0, 0]])\n\n # external API\n with tm.assertRaisesRegexp(ValueError, length_error):\n self.index.copy().set_levels([['a'], ['b']])\n\n with tm.assertRaisesRegexp(ValueError, label_error):\n self.index.copy().set_labels([[0, 0, 0, 0], [0, 0]])\n\n # deprecated properties\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n\n with tm.assertRaisesRegexp(ValueError, length_error):\n self.index.copy().levels = [['a'], ['b']]\n\n with tm.assertRaisesRegexp(ValueError, label_error):\n self.index.copy().labels = [[0, 0, 0, 0], [0, 0]]\n\n def assert_multiindex_copied(self, copy, original):\n # levels shoudl be (at least, shallow copied)\n assert_copy(copy.levels, original.levels)\n\n assert_almost_equal(copy.labels, original.labels)\n\n # labels doesn't matter which way copied\n assert_almost_equal(copy.labels, original.labels)\n self.assertIsNot(copy.labels, original.labels)\n\n # names doesn't matter which way copied\n self.assertEqual(copy.names, original.names)\n self.assertIsNot(copy.names, original.names)\n\n # sort order should be copied\n self.assertEqual(copy.sortorder, original.sortorder)\n\n def test_copy(self):\n i_copy = self.index.copy()\n\n self.assert_multiindex_copied(i_copy, self.index)\n\n def test_shallow_copy(self):\n i_copy = self.index._shallow_copy()\n\n self.assert_multiindex_copied(i_copy, self.index)\n\n def test_view(self):\n i_view = self.index.view()\n\n self.assert_multiindex_copied(i_view, self.index)\n\n def check_level_names(self, index, names):\n self.assertEqual([level.name for level in index.levels], list(names))\n\n def test_changing_names(self):\n\n # names should be applied to levels\n level_names = [level.name for level in self.index.levels]\n self.check_level_names(self.index, self.index.names)\n\n view = self.index.view()\n copy = self.index.copy()\n shallow_copy = self.index._shallow_copy()\n\n # changing names should change level names on object\n new_names = [name + \"a\" for name in self.index.names]\n self.index.names = new_names\n self.check_level_names(self.index, new_names)\n\n # but not on copies\n self.check_level_names(view, level_names)\n self.check_level_names(copy, level_names)\n self.check_level_names(shallow_copy, level_names)\n\n # and copies shouldn't change original\n shallow_copy.names = [name + \"c\" for name in shallow_copy.names]\n self.check_level_names(self.index, new_names)\n\n def test_duplicate_names(self):\n self.index.names = ['foo', 'foo']\n assertRaisesRegexp(KeyError, 'Level foo not found',\n self.index._get_level_number, 'foo')\n\n def test_get_level_number_integer(self):\n self.index.names = [1, 0]\n self.assertEqual(self.index._get_level_number(1), 0)\n self.assertEqual(self.index._get_level_number(0), 1)\n self.assertRaises(IndexError, self.index._get_level_number, 2)\n assertRaisesRegexp(KeyError, 'Level fourth not found',\n self.index._get_level_number, 'fourth')\n\n def test_from_arrays(self):\n arrays = []\n for lev, lab in zip(self.index.levels, self.index.labels):\n arrays.append(np.asarray(lev).take(lab))\n\n result = MultiIndex.from_arrays(arrays)\n self.assertEqual(list(result), list(self.index))\n\n # infer correctly\n result = MultiIndex.from_arrays([[pd.NaT, Timestamp('20130101')],\n ['a', 'b']])\n self.assertTrue(result.levels[0].equals(Index([Timestamp('20130101')\n ])))\n self.assertTrue(result.levels[1].equals(Index(['a', 'b'])))\n\n def test_from_product(self):\n\n first = ['foo', 'bar', 'buz']\n second = ['a', 'b', 'c']\n names = ['first', 'second']\n result = MultiIndex.from_product([first, second], names=names)\n\n tuples = [('foo', 'a'), ('foo', 'b'), ('foo', 'c'), ('bar', 'a'),\n ('bar', 'b'), ('bar', 'c'), ('buz', 'a'), ('buz', 'b'),\n ('buz', 'c')]\n expected = MultiIndex.from_tuples(tuples, names=names)\n\n tm.assert_numpy_array_equal(result, expected)\n self.assertEqual(result.names, names)\n\n def test_from_product_datetimeindex(self):\n dt_index = date_range('2000-01-01', periods=2)\n mi = pd.MultiIndex.from_product([[1, 2], dt_index])\n etalon = pd.lib.list_to_object_array([(1, pd.Timestamp(\n '2000-01-01')), (1, pd.Timestamp('2000-01-02')), (2, pd.Timestamp(\n '2000-01-01')), (2, pd.Timestamp('2000-01-02'))])\n tm.assert_numpy_array_equal(mi.values, etalon)\n\n def test_values_boxed(self):\n tuples = [(1, pd.Timestamp('2000-01-01')), (2, pd.NaT),\n (3, pd.Timestamp('2000-01-03')),\n (1, pd.Timestamp('2000-01-04')),\n (2, pd.Timestamp('2000-01-02')),\n (3, pd.Timestamp('2000-01-03'))]\n mi = pd.MultiIndex.from_tuples(tuples)\n tm.assert_numpy_array_equal(mi.values,\n pd.lib.list_to_object_array(tuples))\n # Check that code branches for boxed values produce identical results\n tm.assert_numpy_array_equal(mi.values[:4], mi[:4].values)\n\n def test_append(self):\n result = self.index[:3].append(self.index[3:])\n self.assertTrue(result.equals(self.index))\n\n foos = [self.index[:1], self.index[1:3], self.index[3:]]\n result = foos[0].append(foos[1:])\n self.assertTrue(result.equals(self.index))\n\n # empty\n result = self.index.append([])\n self.assertTrue(result.equals(self.index))\n\n def test_get_level_values(self):\n result = self.index.get_level_values(0)\n expected = ['foo', 'foo', 'bar', 'baz', 'qux', 'qux']\n tm.assert_numpy_array_equal(result, expected)\n\n self.assertEqual(result.name, 'first')\n\n result = self.index.get_level_values('first')\n expected = self.index.get_level_values(0)\n tm.assert_numpy_array_equal(result, expected)\n\n # GH 10460\n index = MultiIndex(levels=[CategoricalIndex(\n ['A', 'B']), CategoricalIndex([1, 2, 3])], labels=[np.array(\n [0, 0, 0, 1, 1, 1]), np.array([0, 1, 2, 0, 1, 2])])\n exp = CategoricalIndex(['A', 'A', 'A', 'B', 'B', 'B'])\n self.assert_index_equal(index.get_level_values(0), exp)\n exp = CategoricalIndex([1, 2, 3, 1, 2, 3])\n self.assert_index_equal(index.get_level_values(1), exp)\n\n def test_get_level_values_na(self):\n arrays = [['a', 'b', 'b'], [1, np.nan, 2]]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(1)\n expected = [1, np.nan, 2]\n tm.assert_numpy_array_equal(values.values.astype(float), expected)\n\n arrays = [['a', 'b', 'b'], [np.nan, np.nan, 2]]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(1)\n expected = [np.nan, np.nan, 2]\n tm.assert_numpy_array_equal(values.values.astype(float), expected)\n\n arrays = [[np.nan, np.nan, np.nan], ['a', np.nan, 1]]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(0)\n expected = [np.nan, np.nan, np.nan]\n tm.assert_numpy_array_equal(values.values.astype(float), expected)\n values = index.get_level_values(1)\n expected = np.array(['a', np.nan, 1], dtype=object)\n tm.assert_numpy_array_equal(values.values, expected)\n\n arrays = [['a', 'b', 'b'], pd.DatetimeIndex([0, 1, pd.NaT])]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(1)\n expected = pd.DatetimeIndex([0, 1, pd.NaT])\n tm.assert_numpy_array_equal(values.values, expected.values)\n\n arrays = [[], []]\n index = pd.MultiIndex.from_arrays(arrays)\n values = index.get_level_values(0)\n self.assertEqual(values.shape, (0, ))\n\n def test_reorder_levels(self):\n # this blows up\n assertRaisesRegexp(IndexError, '^Too many levels',\n self.index.reorder_levels, [2, 1, 0])\n\n def test_nlevels(self):\n self.assertEqual(self.index.nlevels, 2)\n\n def test_iter(self):\n result = list(self.index)\n expected = [('foo', 'one'), ('foo', 'two'), ('bar', 'one'),\n ('baz', 'two'), ('qux', 'one'), ('qux', 'two')]\n self.assertEqual(result, expected)\n\n def test_legacy_pickle(self):\n if PY3:\n raise nose.SkipTest(\"testing for legacy pickles not \"\n \"support on py3\")\n\n path = tm.get_data_path('multiindex_v1.pickle')\n obj = pd.read_pickle(path)\n\n obj2 = MultiIndex.from_tuples(obj.values)\n self.assertTrue(obj.equals(obj2))\n\n res = obj.get_indexer(obj)\n exp = np.arange(len(obj))\n assert_almost_equal(res, exp)\n\n res = obj.get_indexer(obj2[::-1])\n exp = obj.get_indexer(obj[::-1])\n exp2 = obj2.get_indexer(obj2[::-1])\n assert_almost_equal(res, exp)\n assert_almost_equal(exp, exp2)\n\n def test_legacy_v2_unpickle(self):\n\n # 0.7.3 -> 0.8.0 format manage\n path = tm.get_data_path('mindex_073.pickle')\n obj = pd.read_pickle(path)\n\n obj2 = MultiIndex.from_tuples(obj.values)\n self.assertTrue(obj.equals(obj2))\n\n res = obj.get_indexer(obj)\n exp = np.arange(len(obj))\n assert_almost_equal(res, exp)\n\n res = obj.get_indexer(obj2[::-1])\n exp = obj.get_indexer(obj[::-1])\n exp2 = obj2.get_indexer(obj2[::-1])\n assert_almost_equal(res, exp)\n assert_almost_equal(exp, exp2)\n\n def test_roundtrip_pickle_with_tz(self):\n\n # GH 8367\n # round-trip of timezone\n index = MultiIndex.from_product(\n [[1, 2], ['a', 'b'], date_range('20130101', periods=3,\n tz='US/Eastern')\n ], names=['one', 'two', 'three'])\n unpickled = self.round_trip_pickle(index)\n self.assertTrue(index.equal_levels(unpickled))\n\n def test_from_tuples_index_values(self):\n result = MultiIndex.from_tuples(self.index)\n self.assertTrue((result.values == self.index.values).all())\n\n def test_contains(self):\n self.assertIn(('foo', 'two'), self.index)\n self.assertNotIn(('bar', 'two'), self.index)\n self.assertNotIn(None, self.index)\n\n def test_is_all_dates(self):\n self.assertFalse(self.index.is_all_dates)\n\n def test_is_numeric(self):\n # MultiIndex is never numeric\n self.assertFalse(self.index.is_numeric())\n\n def test_getitem(self):\n # scalar\n self.assertEqual(self.index[2], ('bar', 'one'))\n\n # slice\n result = self.index[2:5]\n expected = self.index[[2, 3, 4]]\n self.assertTrue(result.equals(expected))\n\n # boolean\n result = self.index[[True, False, True, False, True, True]]\n result2 = self.index[np.array([True, False, True, False, True, True])]\n expected = self.index[[0, 2, 4, 5]]\n self.assertTrue(result.equals(expected))\n self.assertTrue(result2.equals(expected))\n\n def test_getitem_group_select(self):\n sorted_idx, _ = self.index.sortlevel(0)\n self.assertEqual(sorted_idx.get_loc('baz'), slice(3, 4))\n self.assertEqual(sorted_idx.get_loc('foo'), slice(0, 2))\n\n def test_get_loc(self):\n self.assertEqual(self.index.get_loc(('foo', 'two')), 1)\n self.assertEqual(self.index.get_loc(('baz', 'two')), 3)\n self.assertRaises(KeyError, self.index.get_loc, ('bar', 'two'))\n self.assertRaises(KeyError, self.index.get_loc, 'quux')\n\n self.assertRaises(NotImplementedError, self.index.get_loc, 'foo',\n method='nearest')\n\n # 3 levels\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])])\n self.assertRaises(KeyError, index.get_loc, (1, 1))\n self.assertEqual(index.get_loc((2, 0)), slice(3, 5))\n\n def test_get_loc_duplicates(self):\n index = Index([2, 2, 2, 2])\n result = index.get_loc(2)\n expected = slice(0, 4)\n self.assertEqual(result, expected)\n # self.assertRaises(Exception, index.get_loc, 2)\n\n index = Index(['c', 'a', 'a', 'b', 'b'])\n rs = index.get_loc('c')\n xp = 0\n assert (rs == xp)\n\n def test_get_loc_level(self):\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])])\n\n loc, new_index = index.get_loc_level((0, 1))\n expected = slice(1, 2)\n exp_index = index[expected].droplevel(0).droplevel(0)\n self.assertEqual(loc, expected)\n self.assertTrue(new_index.equals(exp_index))\n\n loc, new_index = index.get_loc_level((0, 1, 0))\n expected = 1\n self.assertEqual(loc, expected)\n self.assertIsNone(new_index)\n\n self.assertRaises(KeyError, index.get_loc_level, (2, 2))\n\n index = MultiIndex(levels=[[2000], lrange(4)], labels=[np.array(\n [0, 0, 0, 0]), np.array([0, 1, 2, 3])])\n result, new_index = index.get_loc_level((2000, slice(None, None)))\n expected = slice(None, None)\n self.assertEqual(result, expected)\n self.assertTrue(new_index.equals(index.droplevel(0)))\n\n def test_slice_locs(self):\n df = tm.makeTimeDataFrame()\n stacked = df.stack()\n idx = stacked.index\n\n slob = slice(*idx.slice_locs(df.index[5], df.index[15]))\n sliced = stacked[slob]\n expected = df[5:16].stack()\n tm.assert_almost_equal(sliced.values, expected.values)\n\n slob = slice(*idx.slice_locs(df.index[5] + timedelta(seconds=30),\n df.index[15] - timedelta(seconds=30)))\n sliced = stacked[slob]\n expected = df[6:15].stack()\n tm.assert_almost_equal(sliced.values, expected.values)\n\n def test_slice_locs_with_type_mismatch(self):\n df = tm.makeTimeDataFrame()\n stacked = df.stack()\n idx = stacked.index\n assertRaisesRegexp(TypeError, '^Level type mismatch', idx.slice_locs,\n (1, 3))\n assertRaisesRegexp(TypeError, '^Level type mismatch', idx.slice_locs,\n df.index[5] + timedelta(seconds=30), (5, 2))\n df = tm.makeCustomDataframe(5, 5)\n stacked = df.stack()\n idx = stacked.index\n with assertRaisesRegexp(TypeError, '^Level type mismatch'):\n idx.slice_locs(timedelta(seconds=30))\n # TODO: Try creating a UnicodeDecodeError in exception message\n with assertRaisesRegexp(TypeError, '^Level type mismatch'):\n idx.slice_locs(df.index[1], (16, \"a\"))\n\n def test_slice_locs_not_sorted(self):\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])])\n\n assertRaisesRegexp(KeyError, \"[Kk]ey length.*greater than MultiIndex\"\n \" lexsort depth\", index.slice_locs, (1, 0, 1),\n (2, 1, 0))\n\n # works\n sorted_index, _ = index.sortlevel(0)\n # should there be a test case here???\n sorted_index.slice_locs((1, 0, 1), (2, 1, 0))\n\n def test_slice_locs_partial(self):\n sorted_idx, _ = self.index.sortlevel(0)\n\n result = sorted_idx.slice_locs(('foo', 'two'), ('qux', 'one'))\n self.assertEqual(result, (1, 5))\n\n result = sorted_idx.slice_locs(None, ('qux', 'one'))\n self.assertEqual(result, (0, 5))\n\n result = sorted_idx.slice_locs(('foo', 'two'), None)\n self.assertEqual(result, (1, len(sorted_idx)))\n\n result = sorted_idx.slice_locs('bar', 'baz')\n self.assertEqual(result, (2, 4))\n\n def test_slice_locs_not_contained(self):\n # some searchsorted action\n\n index = MultiIndex(levels=[[0, 2, 4, 6], [0, 2, 4]],\n labels=[[0, 0, 0, 1, 1, 2, 3, 3, 3],\n [0, 1, 2, 1, 2, 2, 0, 1, 2]], sortorder=0)\n\n result = index.slice_locs((1, 0), (5, 2))\n self.assertEqual(result, (3, 6))\n\n result = index.slice_locs(1, 5)\n self.assertEqual(result, (3, 6))\n\n result = index.slice_locs((2, 2), (5, 2))\n self.assertEqual(result, (3, 6))\n\n result = index.slice_locs(2, 5)\n self.assertEqual(result, (3, 6))\n\n result = index.slice_locs((1, 0), (6, 3))\n self.assertEqual(result, (3, 8))\n\n result = index.slice_locs(-1, 10)\n self.assertEqual(result, (0, len(index)))\n\n def test_consistency(self):\n # need to construct an overflow\n major_axis = lrange(70000)\n minor_axis = lrange(10)\n\n major_labels = np.arange(70000)\n minor_labels = np.repeat(lrange(10), 7000)\n\n # the fact that is works means it's consistent\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n\n # inconsistent\n major_labels = np.array([0, 0, 1, 1, 1, 2, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 1, 1, 0, 1, 0, 1])\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n\n self.assertFalse(index.is_unique)\n\n def test_truncate(self):\n major_axis = Index(lrange(4))\n minor_axis = Index(lrange(2))\n\n major_labels = np.array([0, 0, 1, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 1, 0, 1])\n\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n\n result = index.truncate(before=1)\n self.assertNotIn('foo', result.levels[0])\n self.assertIn(1, result.levels[0])\n\n result = index.truncate(after=1)\n self.assertNotIn(2, result.levels[0])\n self.assertIn(1, result.levels[0])\n\n result = index.truncate(before=1, after=2)\n self.assertEqual(len(result.levels[0]), 2)\n\n # after < before\n self.assertRaises(ValueError, index.truncate, 3, 1)\n\n def test_get_indexer(self):\n major_axis = Index(lrange(4))\n minor_axis = Index(lrange(2))\n\n major_labels = np.array([0, 0, 1, 2, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 0, 1, 0, 1])\n\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n idx1 = index[:5]\n idx2 = index[[1, 3, 5]]\n\n r1 = idx1.get_indexer(idx2)\n assert_almost_equal(r1, [1, 3, -1])\n\n r1 = idx2.get_indexer(idx1, method='pad')\n e1 = [-1, 0, 0, 1, 1]\n assert_almost_equal(r1, e1)\n\n r2 = idx2.get_indexer(idx1[::-1], method='pad')\n assert_almost_equal(r2, e1[::-1])\n\n rffill1 = idx2.get_indexer(idx1, method='ffill')\n assert_almost_equal(r1, rffill1)\n\n r1 = idx2.get_indexer(idx1, method='backfill')\n e1 = [0, 0, 1, 1, 2]\n assert_almost_equal(r1, e1)\n\n r2 = idx2.get_indexer(idx1[::-1], method='backfill')\n assert_almost_equal(r2, e1[::-1])\n\n rbfill1 = idx2.get_indexer(idx1, method='bfill')\n assert_almost_equal(r1, rbfill1)\n\n # pass non-MultiIndex\n r1 = idx1.get_indexer(idx2._tuple_index)\n rexp1 = idx1.get_indexer(idx2)\n assert_almost_equal(r1, rexp1)\n\n r1 = idx1.get_indexer([1, 2, 3])\n self.assertTrue((r1 == [-1, -1, -1]).all())\n\n # create index with duplicates\n idx1 = Index(lrange(10) + lrange(10))\n idx2 = Index(lrange(20))\n assertRaisesRegexp(InvalidIndexError, \"Reindexing only valid with\"\n \" uniquely valued Index objects\", idx1.get_indexer,\n idx2)\n\n def test_get_indexer_nearest(self):\n midx = MultiIndex.from_tuples([('a', 1), ('b', 2)])\n with tm.assertRaises(NotImplementedError):\n midx.get_indexer(['a'], method='nearest')\n with tm.assertRaises(NotImplementedError):\n midx.get_indexer(['a'], method='pad', tolerance=2)\n\n def test_format(self):\n self.index.format()\n self.index[:0].format()\n\n def test_format_integer_names(self):\n index = MultiIndex(levels=[[0, 1], [0, 1]],\n labels=[[0, 0, 1, 1], [0, 1, 0, 1]], names=[0, 1])\n index.format(names=True)\n\n def test_format_sparse_display(self):\n index = MultiIndex(levels=[[0, 1], [0, 1], [0, 1], [0]],\n labels=[[0, 0, 0, 1, 1, 1], [0, 0, 1, 0, 0, 1],\n [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0]])\n\n result = index.format()\n self.assertEqual(result[3], '1 0 0 0')\n\n def test_format_sparse_config(self):\n warn_filters = warnings.filters\n warnings.filterwarnings('ignore', category=FutureWarning,\n module=\".*format\")\n # GH1538\n pd.set_option('display.multi_sparse', False)\n\n result = self.index.format()\n self.assertEqual(result[1], 'foo two')\n\n self.reset_display_options()\n\n warnings.filters = warn_filters\n\n def test_to_hierarchical(self):\n index = MultiIndex.from_tuples([(1, 'one'), (1, 'two'), (2, 'one'), (\n 2, 'two')])\n result = index.to_hierarchical(3)\n expected = MultiIndex(levels=[[1, 2], ['one', 'two']],\n labels=[[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1],\n [0, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1]])\n tm.assert_index_equal(result, expected)\n self.assertEqual(result.names, index.names)\n\n # K > 1\n result = index.to_hierarchical(3, 2)\n expected = MultiIndex(levels=[[1, 2], ['one', 'two']],\n labels=[[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1],\n [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]])\n tm.assert_index_equal(result, expected)\n self.assertEqual(result.names, index.names)\n\n # non-sorted\n index = MultiIndex.from_tuples([(2, 'c'), (1, 'b'),\n (2, 'a'), (2, 'b')],\n names=['N1', 'N2'])\n\n result = index.to_hierarchical(2)\n expected = MultiIndex.from_tuples([(2, 'c'), (2, 'c'), (1, 'b'),\n (1, 'b'),\n (2, 'a'), (2, 'a'),\n (2, 'b'), (2, 'b')],\n names=['N1', 'N2'])\n tm.assert_index_equal(result, expected)\n self.assertEqual(result.names, index.names)\n\n def test_bounds(self):\n self.index._bounds\n\n def test_equals(self):\n self.assertTrue(self.index.equals(self.index))\n self.assertTrue(self.index.equal_levels(self.index))\n\n self.assertFalse(self.index.equals(self.index[:-1]))\n\n self.assertTrue(self.index.equals(self.index._tuple_index))\n\n # different number of levels\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])])\n\n index2 = MultiIndex(levels=index.levels[:-1], labels=index.labels[:-1])\n self.assertFalse(index.equals(index2))\n self.assertFalse(index.equal_levels(index2))\n\n # levels are different\n major_axis = Index(lrange(4))\n minor_axis = Index(lrange(2))\n\n major_labels = np.array([0, 0, 1, 2, 2, 3])\n minor_labels = np.array([0, 1, 0, 0, 1, 0])\n\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n self.assertFalse(self.index.equals(index))\n self.assertFalse(self.index.equal_levels(index))\n\n # some of the labels are different\n major_axis = Index(['foo', 'bar', 'baz', 'qux'])\n minor_axis = Index(['one', 'two'])\n\n major_labels = np.array([0, 0, 2, 2, 3, 3])\n minor_labels = np.array([0, 1, 0, 1, 0, 1])\n\n index = MultiIndex(levels=[major_axis, minor_axis],\n labels=[major_labels, minor_labels])\n self.assertFalse(self.index.equals(index))\n\n def test_identical(self):\n mi = self.index.copy()\n mi2 = self.index.copy()\n self.assertTrue(mi.identical(mi2))\n\n mi = mi.set_names(['new1', 'new2'])\n self.assertTrue(mi.equals(mi2))\n self.assertFalse(mi.identical(mi2))\n\n mi2 = mi2.set_names(['new1', 'new2'])\n self.assertTrue(mi.identical(mi2))\n\n mi3 = Index(mi.tolist(), names=mi.names)\n mi4 = Index(mi.tolist(), names=mi.names, tupleize_cols=False)\n self.assertTrue(mi.identical(mi3))\n self.assertFalse(mi.identical(mi4))\n self.assertTrue(mi.equals(mi4))\n\n def test_is_(self):\n mi = MultiIndex.from_tuples(lzip(range(10), range(10)))\n self.assertTrue(mi.is_(mi))\n self.assertTrue(mi.is_(mi.view()))\n self.assertTrue(mi.is_(mi.view().view().view().view()))\n mi2 = mi.view()\n # names are metadata, they don't change id\n mi2.names = [\"A\", \"B\"]\n self.assertTrue(mi2.is_(mi))\n self.assertTrue(mi.is_(mi2))\n\n self.assertTrue(mi.is_(mi.set_names([\"C\", \"D\"])))\n mi2 = mi.view()\n mi2.set_names([\"E\", \"F\"], inplace=True)\n self.assertTrue(mi.is_(mi2))\n # levels are inherent properties, they change identity\n mi3 = mi2.set_levels([lrange(10), lrange(10)])\n self.assertFalse(mi3.is_(mi2))\n # shouldn't change\n self.assertTrue(mi2.is_(mi))\n mi4 = mi3.view()\n mi4.set_levels([[1 for _ in range(10)], lrange(10)], inplace=True)\n self.assertFalse(mi4.is_(mi3))\n mi5 = mi.view()\n mi5.set_levels(mi5.levels, inplace=True)\n self.assertFalse(mi5.is_(mi))\n\n def test_union(self):\n piece1 = self.index[:5][::-1]\n piece2 = self.index[3:]\n\n the_union = piece1 | piece2\n\n tups = sorted(self.index._tuple_index)\n expected = MultiIndex.from_tuples(tups)\n\n self.assertTrue(the_union.equals(expected))\n\n # corner case, pass self or empty thing:\n the_union = self.index.union(self.index)\n self.assertIs(the_union, self.index)\n\n the_union = self.index.union(self.index[:0])\n self.assertIs(the_union, self.index)\n\n # won't work in python 3\n # tuples = self.index._tuple_index\n # result = self.index[:4] | tuples[4:]\n # self.assertTrue(result.equals(tuples))\n\n # not valid for python 3\n # def test_union_with_regular_index(self):\n # other = Index(['A', 'B', 'C'])\n\n # result = other.union(self.index)\n # self.assertIn(('foo', 'one'), result)\n # self.assertIn('B', result)\n\n # result2 = self.index.union(other)\n # self.assertTrue(result.equals(result2))\n\n def test_intersection(self):\n piece1 = self.index[:5][::-1]\n piece2 = self.index[3:]\n\n the_int = piece1 & piece2\n tups = sorted(self.index[3:5]._tuple_index)\n expected = MultiIndex.from_tuples(tups)\n self.assertTrue(the_int.equals(expected))\n\n # corner case, pass self\n the_int = self.index.intersection(self.index)\n self.assertIs(the_int, self.index)\n\n # empty intersection: disjoint\n empty = self.index[:2] & self.index[2:]\n expected = self.index[:0]\n self.assertTrue(empty.equals(expected))\n\n # can't do in python 3\n # tuples = self.index._tuple_index\n # result = self.index & tuples\n # self.assertTrue(result.equals(tuples))\n\n def test_difference(self):\n\n first = self.index\n result = first.difference(self.index[-3:])\n\n # - API change GH 8226\n with tm.assert_produces_warning():\n first - self.index[-3:]\n with tm.assert_produces_warning():\n self.index[-3:] - first\n with tm.assert_produces_warning():\n self.index[-3:] - first.tolist()\n\n self.assertRaises(TypeError, lambda: first.tolist() - self.index[-3:])\n\n expected = MultiIndex.from_tuples(sorted(self.index[:-3].values),\n sortorder=0,\n names=self.index.names)\n\n tm.assertIsInstance(result, MultiIndex)\n self.assertTrue(result.equals(expected))\n self.assertEqual(result.names, self.index.names)\n\n # empty difference: reflexive\n result = self.index.difference(self.index)\n expected = self.index[:0]\n self.assertTrue(result.equals(expected))\n self.assertEqual(result.names, self.index.names)\n\n # empty difference: superset\n result = self.index[-3:].difference(self.index)\n expected = self.index[:0]\n self.assertTrue(result.equals(expected))\n self.assertEqual(result.names, self.index.names)\n\n # empty difference: degenerate\n result = self.index[:0].difference(self.index)\n expected = self.index[:0]\n self.assertTrue(result.equals(expected))\n self.assertEqual(result.names, self.index.names)\n\n # names not the same\n chunklet = self.index[-3:]\n chunklet.names = ['foo', 'baz']\n result = first.difference(chunklet)\n self.assertEqual(result.names, (None, None))\n\n # empty, but non-equal\n result = self.index.difference(self.index.sortlevel(1)[0])\n self.assertEqual(len(result), 0)\n\n # raise Exception called with non-MultiIndex\n result = first.difference(first._tuple_index)\n self.assertTrue(result.equals(first[:0]))\n\n # name from empty array\n result = first.difference([])\n self.assertTrue(first.equals(result))\n self.assertEqual(first.names, result.names)\n\n # name from non-empty array\n result = first.difference([('foo', 'one')])\n expected = pd.MultiIndex.from_tuples([('bar', 'one'), ('baz', 'two'), (\n 'foo', 'two'), ('qux', 'one'), ('qux', 'two')])\n expected.names = first.names\n self.assertEqual(first.names, result.names)\n assertRaisesRegexp(TypeError, \"other must be a MultiIndex or a list\"\n \" of tuples\", first.difference, [1, 2, 3, 4, 5])\n\n def test_from_tuples(self):\n assertRaisesRegexp(TypeError, 'Cannot infer number of levels from'\n ' empty list', MultiIndex.from_tuples, [])\n\n idx = MultiIndex.from_tuples(((1, 2), (3, 4)), names=['a', 'b'])\n self.assertEqual(len(idx), 2)\n\n def test_argsort(self):\n result = self.index.argsort()\n expected = self.index._tuple_index.argsort()\n tm.assert_numpy_array_equal(result, expected)\n\n def test_sortlevel(self):\n import random\n\n tuples = list(self.index)\n random.shuffle(tuples)\n\n index = MultiIndex.from_tuples(tuples)\n\n sorted_idx, _ = index.sortlevel(0)\n expected = MultiIndex.from_tuples(sorted(tuples))\n self.assertTrue(sorted_idx.equals(expected))\n\n sorted_idx, _ = index.sortlevel(0, ascending=False)\n self.assertTrue(sorted_idx.equals(expected[::-1]))\n\n sorted_idx, _ = index.sortlevel(1)\n by1 = sorted(tuples, key=lambda x: (x[1], x[0]))\n expected = MultiIndex.from_tuples(by1)\n self.assertTrue(sorted_idx.equals(expected))\n\n sorted_idx, _ = index.sortlevel(1, ascending=False)\n self.assertTrue(sorted_idx.equals(expected[::-1]))\n\n def test_sortlevel_not_sort_remaining(self):\n mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC'))\n sorted_idx, _ = mi.sortlevel('A', sort_remaining=False)\n self.assertTrue(sorted_idx.equals(mi))\n\n def test_sortlevel_deterministic(self):\n tuples = [('bar', 'one'), ('foo', 'two'), ('qux', 'two'),\n ('foo', 'one'), ('baz', 'two'), ('qux', 'one')]\n\n index = MultiIndex.from_tuples(tuples)\n\n sorted_idx, _ = index.sortlevel(0)\n expected = MultiIndex.from_tuples(sorted(tuples))\n self.assertTrue(sorted_idx.equals(expected))\n\n sorted_idx, _ = index.sortlevel(0, ascending=False)\n self.assertTrue(sorted_idx.equals(expected[::-1]))\n\n sorted_idx, _ = index.sortlevel(1)\n by1 = sorted(tuples, key=lambda x: (x[1], x[0]))\n expected = MultiIndex.from_tuples(by1)\n self.assertTrue(sorted_idx.equals(expected))\n\n sorted_idx, _ = index.sortlevel(1, ascending=False)\n self.assertTrue(sorted_idx.equals(expected[::-1]))\n\n def test_dims(self):\n pass\n\n def test_drop(self):\n dropped = self.index.drop([('foo', 'two'), ('qux', 'one')])\n\n index = MultiIndex.from_tuples([('foo', 'two'), ('qux', 'one')])\n dropped2 = self.index.drop(index)\n\n expected = self.index[[0, 2, 3, 5]]\n self.assert_index_equal(dropped, expected)\n self.assert_index_equal(dropped2, expected)\n\n dropped = self.index.drop(['bar'])\n expected = self.index[[0, 1, 3, 4, 5]]\n self.assert_index_equal(dropped, expected)\n\n dropped = self.index.drop('foo')\n expected = self.index[[2, 3, 4, 5]]\n self.assert_index_equal(dropped, expected)\n\n index = MultiIndex.from_tuples([('bar', 'two')])\n self.assertRaises(KeyError, self.index.drop, [('bar', 'two')])\n self.assertRaises(KeyError, self.index.drop, index)\n self.assertRaises(KeyError, self.index.drop, ['foo', 'two'])\n\n # partially correct argument\n mixed_index = MultiIndex.from_tuples([('qux', 'one'), ('bar', 'two')])\n self.assertRaises(KeyError, self.index.drop, mixed_index)\n\n # error='ignore'\n dropped = self.index.drop(index, errors='ignore')\n expected = self.index[[0, 1, 2, 3, 4, 5]]\n self.assert_index_equal(dropped, expected)\n\n dropped = self.index.drop(mixed_index, errors='ignore')\n expected = self.index[[0, 1, 2, 3, 5]]\n self.assert_index_equal(dropped, expected)\n\n dropped = self.index.drop(['foo', 'two'], errors='ignore')\n expected = self.index[[2, 3, 4, 5]]\n self.assert_index_equal(dropped, expected)\n\n # mixed partial / full drop\n dropped = self.index.drop(['foo', ('qux', 'one')])\n expected = self.index[[2, 3, 5]]\n self.assert_index_equal(dropped, expected)\n\n # mixed partial / full drop / error='ignore'\n mixed_index = ['foo', ('qux', 'one'), 'two']\n self.assertRaises(KeyError, self.index.drop, mixed_index)\n dropped = self.index.drop(mixed_index, errors='ignore')\n expected = self.index[[2, 3, 5]]\n self.assert_index_equal(dropped, expected)\n\n def test_droplevel_with_names(self):\n index = self.index[self.index.get_loc('foo')]\n dropped = index.droplevel(0)\n self.assertEqual(dropped.name, 'second')\n\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])],\n names=['one', 'two', 'three'])\n dropped = index.droplevel(0)\n self.assertEqual(dropped.names, ('two', 'three'))\n\n dropped = index.droplevel('two')\n expected = index.droplevel(1)\n self.assertTrue(dropped.equals(expected))\n\n def test_droplevel_multiple(self):\n index = MultiIndex(levels=[Index(lrange(4)), Index(lrange(4)), Index(\n lrange(4))], labels=[np.array([0, 0, 1, 2, 2, 2, 3, 3]), np.array(\n [0, 1, 0, 0, 0, 1, 0, 1]), np.array([1, 0, 1, 1, 0, 0, 1, 0])],\n names=['one', 'two', 'three'])\n\n dropped = index[:2].droplevel(['three', 'one'])\n expected = index[:2].droplevel(2).droplevel(0)\n self.assertTrue(dropped.equals(expected))\n\n def test_drop_not_lexsorted(self):\n # GH 12078\n\n # define the lexsorted version of the multi-index\n tuples = [('a', ''), ('b1', 'c1'), ('b2', 'c2')]\n lexsorted_mi = MultiIndex.from_tuples(tuples, names=['b', 'c'])\n self.assertTrue(lexsorted_mi.is_lexsorted())\n\n # and the not-lexsorted version\n df = pd.DataFrame(columns=['a', 'b', 'c', 'd'],\n data=[[1, 'b1', 'c1', 3], [1, 'b2', 'c2', 4]])\n df = df.pivot_table(index='a', columns=['b', 'c'], values='d')\n df = df.reset_index()\n not_lexsorted_mi = df.columns\n self.assertFalse(not_lexsorted_mi.is_lexsorted())\n\n # compare the results\n self.assert_index_equal(lexsorted_mi, not_lexsorted_mi)\n with self.assert_produces_warning(PerformanceWarning):\n self.assert_index_equal(lexsorted_mi.drop('a'),\n not_lexsorted_mi.drop('a'))\n\n def test_insert(self):\n # key contained in all levels\n new_index = self.index.insert(0, ('bar', 'two'))\n self.assertTrue(new_index.equal_levels(self.index))\n self.assertEqual(new_index[0], ('bar', 'two'))\n\n # key not contained in all levels\n new_index = self.index.insert(0, ('abc', 'three'))\n tm.assert_numpy_array_equal(new_index.levels[0],\n list(self.index.levels[0]) + ['abc'])\n tm.assert_numpy_array_equal(new_index.levels[1],\n list(self.index.levels[1]) + ['three'])\n self.assertEqual(new_index[0], ('abc', 'three'))\n\n # key wrong length\n assertRaisesRegexp(ValueError, \"Item must have length equal to number\"\n \" of levels\", self.index.insert, 0, ('foo2', ))\n\n left = pd.DataFrame([['a', 'b', 0], ['b', 'd', 1]],\n columns=['1st', '2nd', '3rd'])\n left.set_index(['1st', '2nd'], inplace=True)\n ts = left['3rd'].copy(deep=True)\n\n left.loc[('b', 'x'), '3rd'] = 2\n left.loc[('b', 'a'), '3rd'] = -1\n left.loc[('b', 'b'), '3rd'] = 3\n left.loc[('a', 'x'), '3rd'] = 4\n left.loc[('a', 'w'), '3rd'] = 5\n left.loc[('a', 'a'), '3rd'] = 6\n\n ts.loc[('b', 'x')] = 2\n ts.loc['b', 'a'] = -1\n ts.loc[('b', 'b')] = 3\n ts.loc['a', 'x'] = 4\n ts.loc[('a', 'w')] = 5\n ts.loc['a', 'a'] = 6\n\n right = pd.DataFrame([['a', 'b', 0],\n ['b', 'd', 1],\n ['b', 'x', 2],\n ['b', 'a', -1],\n ['b', 'b', 3],\n ['a', 'x', 4],\n ['a', 'w', 5],\n ['a', 'a', 6]],\n columns=['1st', '2nd', '3rd'])\n right.set_index(['1st', '2nd'], inplace=True)\n # FIXME data types changes to float because\n # of intermediate nan insertion;\n tm.assert_frame_equal(left, right, check_dtype=False)\n tm.assert_series_equal(ts, right['3rd'])\n\n # GH9250\n idx = [('test1', i) for i in range(5)] + \\\n [('test2', i) for i in range(6)] + \\\n [('test', 17), ('test', 18)]\n\n left = pd.Series(np.linspace(0, 10, 11),\n pd.MultiIndex.from_tuples(idx[:-2]))\n\n left.loc[('test', 17)] = 11\n left.ix[('test', 18)] = 12\n\n right = pd.Series(np.linspace(0, 12, 13),\n pd.MultiIndex.from_tuples(idx))\n\n tm.assert_series_equal(left, right)\n\n def test_take_preserve_name(self):\n taken = self.index.take([3, 0, 1])\n self.assertEqual(taken.names, self.index.names)\n\n def test_join_level(self):\n def _check_how(other, how):\n join_index, lidx, ridx = other.join(self.index, how=how,\n level='second',\n return_indexers=True)\n\n exp_level = other.join(self.index.levels[1], how=how)\n self.assertTrue(join_index.levels[0].equals(self.index.levels[0]))\n self.assertTrue(join_index.levels[1].equals(exp_level))\n\n # pare down levels\n mask = np.array(\n [x[1] in exp_level for x in self.index], dtype=bool)\n exp_values = self.index.values[mask]\n tm.assert_numpy_array_equal(join_index.values, exp_values)\n\n if how in ('outer', 'inner'):\n join_index2, ridx2, lidx2 = \\\n self.index.join(other, how=how, level='second',\n return_indexers=True)\n\n self.assertTrue(join_index.equals(join_index2))\n tm.assert_numpy_array_equal(lidx, lidx2)\n tm.assert_numpy_array_equal(ridx, ridx2)\n tm.assert_numpy_array_equal(join_index2.values, exp_values)\n\n def _check_all(other):\n _check_how(other, 'outer')\n _check_how(other, 'inner')\n _check_how(other, 'left')\n _check_how(other, 'right')\n\n _check_all(Index(['three', 'one', 'two']))\n _check_all(Index(['one']))\n _check_all(Index(['one', 'three']))\n\n # some corner cases\n idx = Index(['three', 'one', 'two'])\n result = idx.join(self.index, level='second')\n tm.assertIsInstance(result, MultiIndex)\n\n assertRaisesRegexp(TypeError, \"Join.*MultiIndex.*ambiguous\",\n self.index.join, self.index, level=1)\n\n def test_join_self(self):\n kinds = 'outer', 'inner', 'left', 'right'\n for kind in kinds:\n res = self.index\n joined = res.join(res, how=kind)\n self.assertIs(res, joined)\n\n def test_join_multi(self):\n # GH 10665\n midx = pd.MultiIndex.from_product(\n [np.arange(4), np.arange(4)], names=['a', 'b'])\n idx = pd.Index([1, 2, 5], name='b')\n\n # inner\n jidx, lidx, ridx = midx.join(idx, how='inner', return_indexers=True)\n exp_idx = pd.MultiIndex.from_product(\n [np.arange(4), [1, 2]], names=['a', 'b'])\n exp_lidx = np.array([1, 2, 5, 6, 9, 10, 13, 14])\n exp_ridx = np.array([0, 1, 0, 1, 0, 1, 0, 1])\n self.assert_index_equal(jidx, exp_idx)\n self.assert_numpy_array_equal(lidx, exp_lidx)\n self.assert_numpy_array_equal(ridx, exp_ridx)\n # flip\n jidx, ridx, lidx = idx.join(midx, how='inner', return_indexers=True)\n self.assert_index_equal(jidx, exp_idx)\n self.assert_numpy_array_equal(lidx, exp_lidx)\n self.assert_numpy_array_equal(ridx, exp_ridx)\n\n # keep MultiIndex\n jidx, lidx, ridx = midx.join(idx, how='left', return_indexers=True)\n exp_ridx = np.array([-1, 0, 1, -1, -1, 0, 1, -1, -1, 0, 1, -1, -1, 0,\n 1, -1])\n self.assert_index_equal(jidx, midx)\n self.assertIsNone(lidx)\n self.assert_numpy_array_equal(ridx, exp_ridx)\n # flip\n jidx, ridx, lidx = idx.join(midx, how='right', return_indexers=True)\n self.assert_index_equal(jidx, midx)\n self.assertIsNone(lidx)\n self.assert_numpy_array_equal(ridx, exp_ridx)\n\n def test_reindex(self):\n result, indexer = self.index.reindex(list(self.index[:4]))\n tm.assertIsInstance(result, MultiIndex)\n self.check_level_names(result, self.index[:4].names)\n\n result, indexer = self.index.reindex(list(self.index))\n tm.assertIsInstance(result, MultiIndex)\n self.assertIsNone(indexer)\n self.check_level_names(result, self.index.names)\n\n def test_reindex_level(self):\n idx = Index(['one'])\n\n target, indexer = self.index.reindex(idx, level='second')\n target2, indexer2 = idx.reindex(self.index, level='second')\n\n exp_index = self.index.join(idx, level='second', how='right')\n exp_index2 = self.index.join(idx, level='second', how='left')\n\n self.assertTrue(target.equals(exp_index))\n exp_indexer = np.array([0, 2, 4])\n tm.assert_numpy_array_equal(indexer, exp_indexer)\n\n self.assertTrue(target2.equals(exp_index2))\n exp_indexer2 = np.array([0, -1, 0, -1, 0, -1])\n tm.assert_numpy_array_equal(indexer2, exp_indexer2)\n\n assertRaisesRegexp(TypeError, \"Fill method not supported\",\n self.index.reindex, self.index, method='pad',\n level='second')\n\n assertRaisesRegexp(TypeError, \"Fill method not supported\", idx.reindex,\n idx, method='bfill', level='first')\n\n def test_duplicates(self):\n self.assertFalse(self.index.has_duplicates)\n self.assertTrue(self.index.append(self.index).has_duplicates)\n\n index = MultiIndex(levels=[[0, 1], [0, 1, 2]], labels=[\n [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]])\n self.assertTrue(index.has_duplicates)\n\n # GH 9075\n t = [(u('x'), u('out'), u('z'), 5, u('y'), u('in'), u('z'), 169),\n (u('x'), u('out'), u('z'), 7, u('y'), u('in'), u('z'), 119),\n (u('x'), u('out'), u('z'), 9, u('y'), u('in'), u('z'), 135),\n (u('x'), u('out'), u('z'), 13, u('y'), u('in'), u('z'), 145),\n (u('x'), u('out'), u('z'), 14, u('y'), u('in'), u('z'), 158),\n (u('x'), u('out'), u('z'), 16, u('y'), u('in'), u('z'), 122),\n (u('x'), u('out'), u('z'), 17, u('y'), u('in'), u('z'), 160),\n (u('x'), u('out'), u('z'), 18, u('y'), u('in'), u('z'), 180),\n (u('x'), u('out'), u('z'), 20, u('y'), u('in'), u('z'), 143),\n (u('x'), u('out'), u('z'), 21, u('y'), u('in'), u('z'), 128),\n (u('x'), u('out'), u('z'), 22, u('y'), u('in'), u('z'), 129),\n (u('x'), u('out'), u('z'), 25, u('y'), u('in'), u('z'), 111),\n (u('x'), u('out'), u('z'), 28, u('y'), u('in'), u('z'), 114),\n (u('x'), u('out'), u('z'), 29, u('y'), u('in'), u('z'), 121),\n (u('x'), u('out'), u('z'), 31, u('y'), u('in'), u('z'), 126),\n (u('x'), u('out'), u('z'), 32, u('y'), u('in'), u('z'), 155),\n (u('x'), u('out'), u('z'), 33, u('y'), u('in'), u('z'), 123),\n (u('x'), u('out'), u('z'), 12, u('y'), u('in'), u('z'), 144)]\n\n index = pd.MultiIndex.from_tuples(t)\n self.assertFalse(index.has_duplicates)\n\n # handle int64 overflow if possible\n def check(nlevels, with_nulls):\n labels = np.tile(np.arange(500), 2)\n level = np.arange(500)\n\n if with_nulls: # inject some null values\n labels[500] = -1 # common nan value\n labels = list(labels.copy() for i in range(nlevels))\n for i in range(nlevels):\n labels[i][500 + i - nlevels // 2] = -1\n\n labels += [np.array([-1, 1]).repeat(500)]\n else:\n labels = [labels] * nlevels + [np.arange(2).repeat(500)]\n\n levels = [level] * nlevels + [[0, 1]]\n\n # no dups\n index = MultiIndex(levels=levels, labels=labels)\n self.assertFalse(index.has_duplicates)\n\n # with a dup\n if with_nulls:\n f = lambda a: np.insert(a, 1000, a[0])\n labels = list(map(f, labels))\n index = MultiIndex(levels=levels, labels=labels)\n else:\n values = index.values.tolist()\n index = MultiIndex.from_tuples(values + [values[0]])\n\n self.assertTrue(index.has_duplicates)\n\n # no overflow\n check(4, False)\n check(4, True)\n\n # overflow possible\n check(8, False)\n check(8, True)\n\n # GH 9125\n n, k = 200, 5000\n levels = [np.arange(n), tm.makeStringIndex(n), 1000 + np.arange(n)]\n labels = [np.random.choice(n, k * n) for lev in levels]\n mi = MultiIndex(levels=levels, labels=labels)\n\n for keep in ['first', 'last', False]:\n left = mi.duplicated(keep=keep)\n right = pd.lib.duplicated(mi.values, keep=keep)\n tm.assert_numpy_array_equal(left, right)\n\n # GH5873\n for a in [101, 102]:\n mi = MultiIndex.from_arrays([[101, a], [3.5, np.nan]])\n self.assertFalse(mi.has_duplicates)\n self.assertEqual(mi.get_duplicates(), [])\n tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(\n 2, dtype='bool'))\n\n for n in range(1, 6): # 1st level shape\n for m in range(1, 5): # 2nd level shape\n # all possible unique combinations, including nan\n lab = product(range(-1, n), range(-1, m))\n mi = MultiIndex(levels=[list('abcde')[:n], list('WXYZ')[:m]],\n labels=np.random.permutation(list(lab)).T)\n self.assertEqual(len(mi), (n + 1) * (m + 1))\n self.assertFalse(mi.has_duplicates)\n self.assertEqual(mi.get_duplicates(), [])\n tm.assert_numpy_array_equal(mi.duplicated(), np.zeros(\n len(mi), dtype='bool'))\n\n def test_duplicate_meta_data(self):\n # GH 10115\n index = MultiIndex(levels=[[0, 1], [0, 1, 2]], labels=[\n [0, 0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 0, 1, 2]])\n for idx in [index,\n index.set_names([None, None]),\n index.set_names([None, 'Num']),\n index.set_names(['Upper', 'Num']), ]:\n self.assertTrue(idx.has_duplicates)\n self.assertEqual(idx.drop_duplicates().names, idx.names)\n\n def test_tolist(self):\n result = self.index.tolist()\n exp = list(self.index.values)\n self.assertEqual(result, exp)\n\n def test_repr_with_unicode_data(self):\n with pd.core.config.option_context(\"display.encoding\", 'UTF-8'):\n d = {\"a\": [u(\"\\u05d0\"), 2, 3], \"b\": [4, 5, 6], \"c\": [7, 8, 9]}\n index = pd.DataFrame(d).set_index([\"a\", \"b\"]).index\n self.assertFalse(\"\\\\u\" in repr(index)\n ) # we don't want unicode-escaped\n\n def test_repr_roundtrip(self):\n\n mi = MultiIndex.from_product([list('ab'), range(3)],\n names=['first', 'second'])\n str(mi)\n\n if PY3:\n tm.assert_index_equal(eval(repr(mi)), mi, exact=True)\n else:\n result = eval(repr(mi))\n # string coerces to unicode\n tm.assert_index_equal(result, mi, exact=False)\n self.assertEqual(\n mi.get_level_values('first').inferred_type, 'string')\n self.assertEqual(\n result.get_level_values('first').inferred_type, 'unicode')\n\n mi_u = MultiIndex.from_product(\n [list(u'ab'), range(3)], names=['first', 'second'])\n result = eval(repr(mi_u))\n tm.assert_index_equal(result, mi_u, exact=True)\n\n # formatting\n if PY3:\n str(mi)\n else:\n compat.text_type(mi)\n\n # long format\n mi = MultiIndex.from_product([list('abcdefg'), range(10)],\n names=['first', 'second'])\n result = str(mi)\n\n if PY3:\n tm.assert_index_equal(eval(repr(mi)), mi, exact=True)\n else:\n result = eval(repr(mi))\n # string coerces to unicode\n tm.assert_index_equal(result, mi, exact=False)\n self.assertEqual(\n mi.get_level_values('first').inferred_type, 'string')\n self.assertEqual(\n result.get_level_values('first').inferred_type, 'unicode')\n\n mi = MultiIndex.from_product(\n [list(u'abcdefg'), range(10)], names=['first', 'second'])\n result = eval(repr(mi_u))\n tm.assert_index_equal(result, mi_u, exact=True)\n\n def test_str(self):\n # tested elsewhere\n pass\n\n def test_unicode_string_with_unicode(self):\n d = {\"a\": [u(\"\\u05d0\"), 2, 3], \"b\": [4, 5, 6], \"c\": [7, 8, 9]}\n idx = pd.DataFrame(d).set_index([\"a\", \"b\"]).index\n\n if PY3:\n str(idx)\n else:\n compat.text_type(idx)\n\n def test_bytestring_with_unicode(self):\n d = {\"a\": [u(\"\\u05d0\"), 2, 3], \"b\": [4, 5, 6], \"c\": [7, 8, 9]}\n idx = pd.DataFrame(d).set_index([\"a\", \"b\"]).index\n\n if PY3:\n bytes(idx)\n else:\n str(idx)\n\n def test_slice_keep_name(self):\n x = MultiIndex.from_tuples([('a', 'b'), (1, 2), ('c', 'd')],\n names=['x', 'y'])\n self.assertEqual(x[1:].names, x.names)\n\n def test_isnull_behavior(self):\n # should not segfault GH5123\n # NOTE: if MI representation changes, may make sense to allow\n # isnull(MI)\n with tm.assertRaises(NotImplementedError):\n pd.isnull(self.index)\n\n def test_level_setting_resets_attributes(self):\n ind = MultiIndex.from_arrays([\n ['A', 'A', 'B', 'B', 'B'], [1, 2, 1, 2, 3]\n ])\n assert ind.is_monotonic\n ind.set_levels([['A', 'B', 'A', 'A', 'B'], [2, 1, 3, -2, 5]],\n inplace=True)\n # if this fails, probably didn't reset the cache correctly.\n assert not ind.is_monotonic\n\n def test_isin(self):\n values = [('foo', 2), ('bar', 3), ('quux', 4)]\n\n idx = MultiIndex.from_arrays([['qux', 'baz', 'foo', 'bar'], np.arange(\n 4)])\n result = idx.isin(values)\n expected = np.array([False, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n # empty, return dtype bool\n idx = MultiIndex.from_arrays([[], []])\n result = idx.isin(values)\n self.assertEqual(len(result), 0)\n self.assertEqual(result.dtype, np.bool_)\n\n def test_isin_nan(self):\n idx = MultiIndex.from_arrays([['foo', 'bar'], [1.0, np.nan]])\n tm.assert_numpy_array_equal(idx.isin([('bar', np.nan)]),\n [False, False])\n tm.assert_numpy_array_equal(idx.isin([('bar', float('nan'))]),\n [False, False])\n\n def test_isin_level_kwarg(self):\n idx = MultiIndex.from_arrays([['qux', 'baz', 'foo', 'bar'], np.arange(\n 4)])\n\n vals_0 = ['foo', 'bar', 'quux']\n vals_1 = [2, 3, 10]\n\n expected = np.array([False, False, True, True])\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=0))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level=-2))\n\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=1))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level=-1))\n\n self.assertRaises(IndexError, idx.isin, vals_0, level=5)\n self.assertRaises(IndexError, idx.isin, vals_0, level=-5)\n\n self.assertRaises(KeyError, idx.isin, vals_0, level=1.0)\n self.assertRaises(KeyError, idx.isin, vals_1, level=-1.0)\n self.assertRaises(KeyError, idx.isin, vals_1, level='A')\n\n idx.names = ['A', 'B']\n tm.assert_numpy_array_equal(expected, idx.isin(vals_0, level='A'))\n tm.assert_numpy_array_equal(expected, idx.isin(vals_1, level='B'))\n\n self.assertRaises(KeyError, idx.isin, vals_1, level='C')\n\n def test_reindex_preserves_names_when_target_is_list_or_ndarray(self):\n # GH6552\n idx = self.index.copy()\n target = idx.copy()\n idx.names = target.names = [None, None]\n\n other_dtype = pd.MultiIndex.from_product([[1, 2], [3, 4]])\n\n # list & ndarray cases\n self.assertEqual(idx.reindex([])[0].names, [None, None])\n self.assertEqual(idx.reindex(np.array([]))[0].names, [None, None])\n self.assertEqual(idx.reindex(target.tolist())[0].names, [None, None])\n self.assertEqual(idx.reindex(target.values)[0].names, [None, None])\n self.assertEqual(\n idx.reindex(other_dtype.tolist())[0].names, [None, None])\n self.assertEqual(\n idx.reindex(other_dtype.values)[0].names, [None, None])\n\n idx.names = ['foo', 'bar']\n self.assertEqual(idx.reindex([])[0].names, ['foo', 'bar'])\n self.assertEqual(idx.reindex(np.array([]))[0].names, ['foo', 'bar'])\n self.assertEqual(idx.reindex(target.tolist())[0].names, ['foo', 'bar'])\n self.assertEqual(idx.reindex(target.values)[0].names, ['foo', 'bar'])\n self.assertEqual(\n idx.reindex(other_dtype.tolist())[0].names, ['foo', 'bar'])\n self.assertEqual(\n idx.reindex(other_dtype.values)[0].names, ['foo', 'bar'])\n\n def test_reindex_lvl_preserves_names_when_target_is_list_or_array(self):\n # GH7774\n idx = pd.MultiIndex.from_product([[0, 1], ['a', 'b']],\n names=['foo', 'bar'])\n self.assertEqual(idx.reindex([], level=0)[0].names, ['foo', 'bar'])\n self.assertEqual(idx.reindex([], level=1)[0].names, ['foo', 'bar'])\n\n def test_reindex_lvl_preserves_type_if_target_is_empty_list_or_array(self):\n # GH7774\n idx = pd.MultiIndex.from_product([[0, 1], ['a', 'b']])\n self.assertEqual(idx.reindex([], level=0)[0].levels[0].dtype.type,\n np.int64)\n self.assertEqual(idx.reindex([], level=1)[0].levels[1].dtype.type,\n np.object_)\n\n def test_groupby(self):\n groups = self.index.groupby(np.array([1, 1, 1, 2, 2, 2]))\n labels = self.index.get_values().tolist()\n exp = {1: labels[:3], 2: labels[3:]}\n tm.assert_dict_equal(groups, exp)\n\n # GH5620\n groups = self.index.groupby(self.index)\n exp = dict((key, [key]) for key in self.index)\n tm.assert_dict_equal(groups, exp)\n\n def test_index_name_retained(self):\n # GH9857\n result = pd.DataFrame({'x': [1, 2, 6],\n 'y': [2, 2, 8],\n 'z': [-5, 0, 5]})\n result = result.set_index('z')\n result.loc[10] = [9, 10]\n df_expected = pd.DataFrame({'x': [1, 2, 6, 9],\n 'y': [2, 2, 8, 10],\n 'z': [-5, 0, 5, 10]})\n df_expected = df_expected.set_index('z')\n tm.assert_frame_equal(result, df_expected)\n\n def test_equals_operator(self):\n # GH9785\n self.assertTrue((self.index == self.index).all())\n","sub_path":"pkgs/pandas-0.18.0-np110py27_0/lib/python2.7/site-packages/pandas/tests/indexes/test_multi.py","file_name":"test_multi.py","file_ext":"py","file_size_in_byte":78143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"213753280","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Author : YuLei Lan\n# @Software: PyCharm\n\nimport base64\nimport datetime\nfrom .state import *\nfrom app.system import models\nfrom utils.operating_redis import redis_object\n\n\nclass Agent:\n def __init__(self, agent_id='', info=None):\n self.id = agent_id\n self.last_heartbeat = datetime.datetime.now()\n self.info = info\n self.queue = []\n self.tasks = {}\n self.agents = {}\n\n def heartbeat(self, info):\n self.info = info\n self.last_heartbeat = datetime.datetime.now()\n\n def register(self, agent_id, info):\n agent = Agent(agent_id, info)\n agent.heartbeat(info)\n return agent\n\n def get_agent(self, agent_id):\n agent_obj = models.AgentListModels.objects.get(agent_id=agent_id)\n info = {\n \"hostname\": agent_obj.hostname,\n \"ip\": agent_obj.ipaddress,\n }\n return Agent(agent_id, info)\n\n def get_agent_task(self):\n task_id = redis_object.lpop(\"dispatch_task_id\")\n if task_id:\n task = redis_object.lpop(task_id)\n return task\n\n def send(self, task):\n payload = {'task_id': task.id,\n 'script': base64.b64encode(task.script.encode()).decode(),\n 'timeout': task.timeout}\n redis_object.rpush(\"dispatch_task_id\", task.id)\n redis_object.rpush(task.id, payload)\n \n def free(self, task_id):\n try:\n self.queue.remove(task_id)\n self.tasks.pop(task_id)\n except Exception as e:\n pass\n","sub_path":"dispatch/service/master/core/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"292532388","text":"from django.conf.urls import patterns, include, url\n\n\nfrom apps.location import views\n\nurlpatterns = patterns('',\n # Home Page:\n url(r'^$', views.home, name='home'),\n\n # Add New Trip\n url(r'^add-new-trip/$', views.add_new_trip, name='add_new_trip'),\n\n ## Load agent data\n url(r'^ajax_calls/load-agents/',views.get_load_agents,name='load_data_agents'),\n ## Load countrys dara\n url(r'^ajax_calls/load-countrys/',views.get_load_countrys,name='load_data_countrys'),\n\n\n url(r'^details/(?P[\\w-]+)/$',views.details_agent_data,name='details_agent_data'),\n\n\n\n\n\n # url(r'^blog-detail$', views.blog_detail, name='blog-detail'),\n\n\n\n )\n","sub_path":"apps/location/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"20058768","text":"import torch.nn as nn\nimport torch\nimport utils \nfrom layers import ConvBlock, UpResBloc, Conv2dEnum, BatchNorm2dEnum\nclass Encoder_z(nn.Module):\n \"\"\"\n Will take any insize as long as it is divisible by 8\n \"\"\"\n def __init__(self,\n x_size=80, z_size=100, y_size=3):\n super().__init__()\n self.y_size = y_size\n self.x_size = x_size\n self.z_size = z_size\n self.linear_size = int((self.x_size/8)**2)\n self.net = nn.Sequential(\n Conv2dEnum(1, 32, kernel_size=7, padding=3, bias=False),\n nn.ELU(),\n nn.AvgPool2d(2),\n ConvBlock(32, bias=False),\n Conv2dEnum(32,16,kernel_size=5, padding=2, bias=False),\n nn.ELU(),\n ConvBlock(16, bias=False),\n nn.AvgPool2d(2),\n Conv2dEnum(16, 1, kernel_size=5, padding=2, bias=False),\n nn.AvgPool2d(2),\n nn.ELU()\n )\n self.linear = nn.Linear(self.linear_size + self.y_size, self.linear_size)\n self.loc = nn.Linear(self.linear_size, self.z_size)\n self.scale = nn.Linear(self.linear_size, self.z_size)\n \n def forward(self, x, y):\n z = x - 0.222\n z = x / 0.156\n z = self.net(z)\n z = z.view(z.shape[0], -1)\n \n z = utils.cat((z, y), -1)\n\n z = self.linear(z)\n z_loc = self.loc(z)\n z_scale = torch.exp(self.scale(z))\n return z_loc, z_scale\n\nclass Encoder_y(nn.Module):\n def __init__(self, x_size=80, y_size=3):\n super().__init__()\n self.y_size = y_size\n self.x_size = x_size\n self.linear_size = int((x_size/8)**2)\n self.net = nn.Sequential(\n Conv2dEnum(1, 32, kernel_size=7, padding=3, bias=False),\n nn.Tanh(),\n nn.AvgPool2d(2),\n ConvBlock(32,5, bias=False),\n Conv2dEnum(32,16,kernel_size=5, padding=2, bias=False),\n nn.Tanh(),\n ConvBlock(16, bias=False),\n nn.AvgPool2d(2),\n Conv2dEnum(16, 1, kernel_size=5, padding=2, bias=False),\n nn.AvgPool2d(2),\n nn.Tanh()\n )\n self.linear = nn.Linear(self.linear_size, self.y_size)\n self.sigmoid = nn.Sigmoid()\n def forward(self, x):\n\n x = x - 0.222\n x = x / 0.156\n x = self.net(x)\n x = x.view(-1, self.linear_size)\n x = self.linear(x)\n x = self.sigmoid(x)\n return x\n \nclass Decoder(nn.Module):\n def __init__(self, z_size=100, x_size=80, y_size=3):\n super().__init__()\n self.y_size = y_size\n self.z_size = z_size\n self.x_size = x_size\n self.linear_size = int((x_size/8)**2)\n self.linear = nn.Linear(self.z_size + self.y_size, self.linear_size)\n self.net = nn.Sequential(\n nn.ELU(),\n UpResBloc(1, 32),\n nn.ELU(),\n BatchNorm2dEnum(32),\n ConvBlock(32, bias=False),\n UpResBloc(32, 32),\n nn.ELU(),\n ConvBlock(32, bias=False),\n ConvBlock(32, bias=False),\n UpResBloc(32, 1),\n nn.Sigmoid()\n )\n \n def forward(self, z, y):\n # TODO CHECK\n z = utils.cat((z, y), -1)\n z = self.linear(z)\n z = torch.reshape(z, (*z.shape[:-1],1, int(self.x_size/8), int(self.x_size/8)))\n \n loc_img = self.net(z)\n return loc_img\n\nif __name__ == \"__main__\":\n x = torch.zeros([10, 1, 80, 80])\n y = torch.zeros([2, 10, 3])\n encoder_z = Encoder_z(x_size=80)\n encoder_y = Encoder_y()\n decoder = Decoder(x_size=80)\n x = encoder_z(x, y)\n\n x = x[0]\n x = decoder(x, y)\n x = torch.zeros([10, 1, 80, 80])\n y = encoder_y(x)\n","sub_path":"ss_encoders_decoders_gz_enum.py","file_name":"ss_encoders_decoders_gz_enum.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"510881828","text":"import numpy as np\nimport pandas as pd\nimport math\nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import KFold\nfrom xgboost import XGBRegressor\n\ntrain_df= pd.read_csv('data/processed_train.csv')\ntest_df = pd.read_csv('data/processed_test.csv')\ntarget_col = \"target\"\n\ncols_to_use=['feature_1', 'feature_2', 'feature_3','year','month','num_hist_transactions','sum_hist_trans', 'mean_hist_trans',\n 'std_hist_trans', 'min_hist_trans', 'max_hist_trans','num_merch_transactions','sum_merch_trans', 'mean_merch_trans',\n 'std_merch_trans','min_merch_trans', 'max_merch_trans']\n\ntrain_X = train_df[cols_to_use]\ntest_X = test_df[cols_to_use]\ntrain_y = train_df[target_col].values\n\n'''\n#tune 1:\ndepth = [5]\nlearning = [0.05]\nestimators = [100]\ngamma = [0.1,0.3,0.5]\nmin_child_weight =[1,3,5]\n#best: Best: -14.493511 using {'n_estimators': 100, 'learning_rate': 0.05, 'max_depth': 5}\n#Best: -14.492914 using {'n_estimators': 100, 'learning_rate': 0.05, 'max_depth': 5, 'gamma': 0.3, 'min_child_weight': 5}\n\n#########\nmodel = XGBRegressor(random_state =0)\nparam_grid = dict(max_depth = depth,learning_rate=learning, n_estimators=estimators, gamma = gamma,min_child_weight=min_child_weight)\nkfold = KFold(n_splits=5, shuffle=True, random_state=7)\ngrid_search = GridSearchCV(model, param_grid, scoring=\"neg_mean_squared_error\", n_jobs=-1, cv=kfold,verbose=True)\ngrid_result = grid_search.fit(train_X, train_y)\n\n# summarize results\n\nprint(\"Best: %f using %s\" % (grid_result.best_score_,grid_result.best_params_))\nprint(\"RMSE: \" + math.sqrt(abs(grid_result.best_score_)))\nmeans = grid_result.cv_results_['mean_test_score']\nstds = grid_result.cv_results_['std_test_score']\nparams = grid_result.cv_results_['params']\nfor mean, stdev, param in zip(means, stds, params):\n print(\"%f (%f) with: %r\" % (mean, stdev, param))\n'''\nmodel_A= XGBRegressor(max_depth=5,\n n_estimators=100,\n learning_rate=0.05,\n gamma = 0.3,\n min_child_weight =5,\n random_state=0\n )\n\nmodel_A.fit(train_X, train_y)\na_preds = model_A.predict(test_X)\n\nsub_df = pd.DataFrame({\"card_id\":test_df[\"card_id\"].values})\nsub_df[\"target\"] = a_preds\nsub_df.to_csv(\"results/xgb.csv\", index=False)\n\n'''\nmodel.fit(X_train_A, y_train_A)\na_preds = model_A.predict_proba(X_test_A)\na_sub = make_country_sub(a_preds, X_test_A, 'A')\n'''\n#version 1\n\n# Initialize XGB and GridSearch\n'''\nxgb = XGBRegressor(nthread=-1) \n\ngrid = GridSearchCV(xgb, params, scoring=\"neg_mean_squared_error\")\ngrid.fit(train_X, train_y)\n\nprint(r2_score(Y_Val, grid.best_estimator_.predict(X_Val))) \n'''\n\n#version 2\n'''\ndef run_xgb(train_X, train_y, val_X, val_y, test_X):\n\tparams = {'min_child_weight':[4,5], 'gamma':[i/10.0 for i in range(3,6)], 'subsample':[i/10.0 for i in range(6,11)],\n'colsample_bytree':[i/10.0 for i in range(6,11)], 'max_depth': [2,3,4]}\n\tevals_result = {}\n\txgb = XGBRegressor(nthread=-1, silent=False)\n'''\n\n#version 3\n'''\npred_test = 0\nkf = model_selection.KFold(n_splits=5, random_state = 2018, shuffle=True)\nfor dev_index, val_index in kf.split(train_df):\n dev_X, val_X = train_X.loc[dev_index,:], train_X.loc[val_index,:]\n dev_y, val_y = train_y[dev_index], train_y[val_index]\n \n model.fit(dev_X, dev_y)\n model.predict\n pred_test_tmp, model, evals_result = run_lgb(dev_X, dev_y, val_X, val_y, test_X)\n pred_test += pred_test_tmp\n \npred_test/=5\n'''","sub_path":"models/baseline_xgb.py","file_name":"baseline_xgb.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"47177682","text":"#! /usr/local/bin/python2.7\n# Contributed by Mei-Ju May Chen (2015)\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\nimport sys\nimport re\nimport logging\n# try to import from project first\nfrom os.path import dirname\nif dirname(__file__) == '':\n lib_path = '../lib'\nelse:\n lib_path = dirname(__file__) + '/../lib'\nsys.path.insert(1, lib_path)\nfrom gff3_modified import Gff3\nimport function4gff\nimport single_feature\nimport inter_model\nimport intra_model\nimport ERROR # Details of the errors that can be detected.\n\n__version__ = '0.0.1'\n\nif __name__ == '__main__':\n logger_stderr = logging.getLogger(__name__+'stderr')\n logger_stderr.setLevel(logging.INFO)\n stderr_handler = logging.StreamHandler()\n stderr_handler.setFormatter(logging.Formatter('%(levelname)-8s %(message)s'))\n logger_stderr.addHandler(stderr_handler)\n logger_null = logging.getLogger(__name__+'null')\n null_handler = logging.NullHandler()\n logger_null.addHandler(null_handler)\n import argparse\n from textwrap import dedent\n parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=dedent(\"\"\"\\\n \n Testing environment:\n 1. Python 2.7\n\n Inputs:\n 1. GFF3: Specify the file name with the -g or --gff argument; Please note that this program requires gene/pseudogene and mRNA/pseudogenic_transcript to have an ID attribute in column 9.\n 2. fasta file: Specify the file name with the -f or --fasta argument\n\n Outputs:\n 1. Error report for the input GFF3 file\n\t* Line_num: Line numbers of the found problematic models in the input GFF3 file.\n\t* Error_code: Error codes for the found problematic models. Please refer to lib/ERROR/ERROR.py to see the full list of Error_code and the corresponding Error_tag.\n * Error_tag: Detail of the found errors for the problematic models. Please refer to lib/ERROR/ERROR.py to see the full list of Error_code and the corresponding Error_tag.\n\n Quick start:\n python2.7 bin/gff-QC.py -g example_file/example.gff3 -f example_file/reference.fa -o test\n or\n python2.7 bin/gff-QC.py --gff example_file/example.gff3 --fasta example_file/reference.fa --output test\n\n \"\"\"))\n parser.add_argument('-g', '--gff', type=str, help='Genome annotation file, gff3 format') \n parser.add_argument('-f', '--fasta', type=str, help='Genome sequences, fasta format')\n parser.add_argument('-o', '--output', type=str, help='output file name (default: report.txt)')\n parser.add_argument('-v', '--version', action='version', version='%(prog)s ' + __version__)\n \n args = parser.parse_args()\n\n if args.gff:\n logger_stderr.info('Checking gff file (%s)...', args.gff)\n elif not sys.stdin.isatty(): # if STDIN connected to pipe or file\n args.gff = sys.stdin\n logger_stderr.info('Reading from STDIN...')\n else: # no input\n parser.print_help()\n sys.exit(1)\n\n if args.fasta:\n logger_stderr.info('Checking genome fasta (%s)...', args.fasta)\n elif not sys.stdin.isatty(): # if STDIN connected to pipe or file\n args.fasta = sys.stdin\n logger_stderr.info('Reading from STDIN...')\n else: # no input\n parser.print_help()\n sys.exit(1)\n\n logger_stderr.info('Reading gff files: (%s)...\\n', args.gff)\n gff3 = Gff3(gff_file=args.gff, fasta_external=args.fasta, logger=logger_null)\n logger_stderr.info('Checking errors in the gff files: (%s)...\\n', args.gff)\n if not gff3.check_parent_boundary():\n sys.exit()\n\n gff3.check_unresolved_parents()\n gff3.check_phase()\n gff3.check_reference()\n logger_stderr.info('\\t- Checking missing attributes: (%s)...\\n', 'function4gff.FIX_MISSING_ATTR()')\n function4gff.FIX_MISSING_ATTR(gff3, logger=logger_stderr)\n\n error_set = list()\n cmd = None\n cmd = function4gff.extract_internal_detected_errors(gff3)\n if cmd:\n error_set.extend(cmd)\n cmd = None\n logger_stderr.info('\\t- Checking intra-model errors: (%s)...\\n', args.gff)\n cmd = intra_model.main(gff3, logger=logger_stderr)\n if cmd:\n error_set.extend(cmd)\n cmd = None\n logger_stderr.info('\\t- Checking inter-model errors: (%s)...\\n', args.gff)\n cmd = inter_model.main(gff3, args.gff, args.fasta, logger=logger_stderr)\n if cmd:\n error_set.extend(cmd)\n cmd = None\n logger_stderr.info('\\t- Checking single-feature errors: (%s)...\\n', args.gff)\n cmd = single_feature.main(gff3, logger=logger_stderr)\n if cmd:\n error_set.extend(cmd)\n\n if args.output:\n logger_stderr.info('Print QC report at {0:s}'.format(args.output))\n report_fh = open(args.output, 'wb')\n else:\n logger_stderr.info('Print QC report at {0:s}'.format('report.txt'))\n report_fh = open('report.txt', 'wb')\n\n\n ERROR_INFO = ERROR.INFO\n\n report_fh.write('Line_num\\tError_code\\tError_tag\\n')\n for e in sorted(error_set):\n tag = '[{0:s}]'.format(e['eTag'])\n report_fh.write('{0:s}\\t{1:s}\\t{2:s}\\n'.format(str(e['line_num']), str(e['eCode']), str(tag)))\n","sub_path":"bin/gff-QC.py","file_name":"gff-QC.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"73966031","text":"import os\nimport re\nimport sys\nimport csv\n\ndef ACQ():\n compos = os.getenv('COMPUTERNAME')\n dir = os.getcwd()\n acq_path = os.path.join(dir, compos, \"Scuba\",\"ScubaCSV.csv\")\n return acq_path\n\ndef parse_file(file_content):\n acq_file = ACQ()\n test_pattern = \"'test': '(.*)',\"\n severity_pattern = \"'severity': '(.*)',\"\n regulations_pattern = r\"'regulations': \\[(.*?)\\],\"\n result_pattern = \"'result': '(.*)',\"\n category_pattern = \"'category': '(.*)',\"\n description_pattern = \"'description': '(.*)',\"\n remediation_pattern = \"'remediation': '(.*)',\"\n cveLink_pattern = \"'cveLink': '(.*)',\"\n details_pattern = \"'details': '(.*)',\"\n data_pattern = r\"'data': \\[(.*)\\],\"\n score_pattern = \"'score': '(.*)',\"\n test_result = re.findall(test_pattern, file_content)\n severity_result = re.findall(severity_pattern, file_content)\n regulations_result = re.findall(regulations_pattern, file_content)\n result_result = re.findall(result_pattern, file_content)\n category_result = re.findall(category_pattern, file_content)\n description_result = re.findall(description_pattern, file_content)\n remediation_result = re.findall(remediation_pattern, file_content)\n cveLink_result = re.findall(cveLink_pattern, file_content)\n details_result = re.findall(details_pattern, file_content)\n data_result = re.findall(data_pattern, file_content)\n score_result = re.findall(score_pattern, file_content)\n try:\n with open(acq_file, 'w', newline='') as csvfile:\n fieldnames = ['Test', 'Severity', 'Regulations', 'Result', 'Category', 'Description', 'Remediation', 'CVELink', 'Details', 'Data', 'Score']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for i in range(len(test_result)):\n writer.writerow({'Test': test_result[i],\n 'Severity': severity_result[i],\n 'Regulations': regulations_result[i],\n 'Result': result_result[i],\n 'Category': category_result[i],\n 'Description': description_result[i],\n 'Remediation': remediation_result[i],\n 'CVELink': cveLink_result[i],\n 'Details': details_result[i],\n 'Data': data_result[i],\n 'Score': score_result[i]\n })\n except:\n print(\"Run script as administrator\")\n exit(1)\n\n\nif __name__ == \"__main__\":\n num_args = len(sys.argv)\n if num_args != 2:\n print(\"Usage: Scuba2CSV.py \")\n exit(1)\n file = open(sys.argv[1], \"r\")\n parse_file(file.read())\n","sub_path":"Scuba2CSV.py","file_name":"Scuba2CSV.py","file_ext":"py","file_size_in_byte":2833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"364104632","text":"from django.db import connection\nfrom django.conf import settings\nimport os\n\n\ndef terminal_width():\n width = 0\n try:\n import struct, fcntl, termios\n s = struct.pack('HHHH', 0, 0, 0, 0)\n x = fcntl.ioctl(1, termios.TIOCGWINSZ, s)\n width = struct.unpack('HHHH', x)[1]\n except:\n pass\n if width <= 0:\n try:\n width = int(os.environ['COLUMNS'])\n except:\n pass\n if width <= 0:\n width = 80\n return width\n\n\nclass SQLLoggerMiddleware(object):\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n\n indentation = 2\n if len(connection.queries) > 0 and settings.DEBUG:\n width = terminal_width()\n total_time = 0.0\n for query in connection.queries:\n nice_sql = query['sql'].replace('\"', '').replace(',', ', ')\n sql = \"\\033[1;31m[%s]\\033[0m %s\" % (query['time'], nice_sql)\n total_time = total_time + float(query['time'])\n while len(sql) > width - indentation:\n print(\"%s%s\" % (\" \" * indentation, sql[:width - indentation]))\n sql = sql[width - indentation:]\n print(\"%s%s\\n\" % (\" \" * indentation, sql))\n replace_tuple = (\" \" * indentation, str(total_time))\n print(\"%s\\033[1;32m[TOTAL TIME: %s seconds]\\033[0m\" % replace_tuple)\n return response","sub_path":"SSOServer/auth/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"16"}
+{"seq_id":"575967078","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Apr 30 14:54:35 2021\n\n@author: Ricardo Hopker\n\"\"\"\n\nimport streamlit as st\nimport streamlit.components.v1 as components\nimport base64\n# To make things easier later, we're also importing numpy and pandas for\n# working with sample data.\n# import numpy as np\nimport pandas as pd\nfrom constants import dict_total\n# import dill\nimport matplotlib.pyplot as plt\nimport pydeck as pdk\nfrom integrating_modules import biodigestor, cleanXopt,cleanBiodigestor,fminClean\nfrom multiJ import run_multiJ,plotRes,run_singleJ\nfrom all_best_paths_transport import createTransportSurrogateModel\n# import scipy.optimize as op\n# from Transport import load_data\nimport copy\nimport SessionState\n# import json\ndef load_session():\n session_state = SessionState.get(e_priceS=dict_total['e_priceS'],\n e_c=dict_total['e_c'],\n e_priceB=dict_total['e_priceB'],\n f_used=dict_total['f_used'],\n p_bf = dict_total['p_bf'],\n p_l = dict_total['p_l'],\n c_rskm = dict_total['c_rskm'],\n C_V_gas = dict_total['C_V_gas'],\n p_g = dict_total['p_g'],\n C_upgrade_cng = dict_total['C_upgrade_cng'],\n g_d = dict_total['g_d'],\n g_eff = dict_total['g_eff'],\n g_m = dict_total['g_m'],\n i_main_cost = dict_total['i_main_cost'],\n kd = dict_total['kd'],\n max_debt = dict_total['max_debt'],\n ke = dict_total['ke'],\n L = dict_total['L'],\n T_m3_km_cng = dict_total['T_m3_km_cng'],\n T_L_km_diesel = dict_total['T_L_km_diesel'],\n V_per_truck = dict_total['V_per_truck'],\n tax = dict_total['tax'],\n USS_to_RS = dict_total['USS_to_RS'],\n working_days = dict_total['working_days'],\n working_hours = dict_total['working_hours'],\n g_power = dict_total['g_power'],\n V_gBurn = 0.7,\n ng = 1,\n debt_level = 0.5,\n V_cng_p =0.20,\n farm1 = 1,farm2 = 0,farm3 =0,farm4 = 0,farm5 = 0,farm6 = 0,farm7 = 0,\n ng_max = dict_total['ng_max'],\n NSGA_pop = dict_total['NSGA_pop'],\n NSGA_gen = dict_total['NSGA_gen'],\n NSGA_off = dict_total['NSGA_off'],\n dict_T = dict_total['dict_T'],\n Farm_data = dict_total['Farm_data'],\n GA_pop = dict_total['GA_pop'],\n GA_gen = dict_total['GA_gen'],\n GA_off = dict_total['GA_off'],\n truck_gwp_emmited = dict_total['truck_gwp_emmited'],\n lam = float(dict_total['lam'])\n )\n return session_state\ndef update_user_dict():\n dict_totalUser = copy.deepcopy(dict_total)\n session_state = load_session()\n dict_totalUser['e_priceS'] = session_state.e_priceS\n dict_totalUser['e_c'] = session_state.e_c\n dict_totalUser['e_priceB'] = session_state.e_priceB\n dict_totalUser['f_used'] = session_state.f_used\n dict_totalUser['p_bf'] = session_state.p_bf\n dict_totalUser['p_l'] = session_state.p_l\n dict_totalUser['c_rskm'] = session_state.c_rskm\n session_state.c_km = session_state.c_rskm\n dict_totalUser['C_V_gas'] = session_state.C_V_gas\n dict_totalUser['p_g'] = session_state.p_g\n dict_totalUser['C_upgrade_cng'] = session_state.C_upgrade_cng\n dict_totalUser['g_d'] = session_state.g_d\n dict_totalUser['g_eff'] = session_state.g_eff\n dict_totalUser['g_m']= session_state.g_m\n dict_totalUser['i_main_cost'] = session_state.i_main_cost\n dict_totalUser['kd'] = session_state.kd\n dict_totalUser['max_debt'] = session_state.max_debt\n dict_totalUser['ke'] = session_state.ke\n dict_totalUser['L'] = session_state.L\n dict_totalUser['T_m3_km_cng'] = session_state.T_m3_km_cng\n dict_totalUser['T_L_km_diesel'] = session_state.T_L_km_diesel\n dict_totalUser['V_per_truck'] = session_state.V_per_truck\n dict_totalUser['tax'] = session_state.tax\n dict_totalUser['USS_to_RS'] = session_state.USS_to_RS\n dict_totalUser['working_days'] = session_state.working_days\n dict_totalUser['working_hours'] = session_state.working_hours\n dict_totalUser['g_power'] = session_state.g_power\n dict_totalUser['ng_max'] = session_state.ng_max\n dict_totalUser['NSGA_pop'] = session_state.NSGA_pop\n dict_totalUser['NSGA_gen'] = session_state.NSGA_gen\n dict_totalUser['NSGA_off'] = session_state.NSGA_off\n dict_totalUser['dict_T'] = session_state.dict_T\n dict_totalUser['Farm_data'] = session_state.Farm_data\n dict_totalUser['GA_pop'] = session_state.GA_pop\n dict_totalUser['GA_gen'] = session_state.GA_gen\n dict_totalUser['GA_off'] = session_state.GA_off\n dict_totalUser['lam'] = session_state.lam\n dict_total['truck_gwp_emmited'] = session_state.truck_gwp_emmited\n return dict_totalUser\n \ndef main():\n pages ={\"Main\":page1,\"Parameters\":page2,'Transportation':pageTransport,\"Model Explanation\":page3}\n page = st.sidebar.selectbox(\"Select your page\", tuple(pages.keys()))\n # session_state = load_session()\n pages[page]()\ndef page1():\n session_state = load_session()\n # data = pd.read_csv('location_data.csv', header=None)\n # data = data.rename(columns={0:'lat',1:'lon',2:'Volume',3:'Solid Percentage',4:'Cattle',5:'Swine',6:'Poultry'}) \n # data['id'] = list(range(len(data)))\n # data['id+1'] = list(range(1,len(data)+1))\n\n def plotMultiJ(res,dict_totalUser):\n var = plotRes(res,False,dict_totalUser)\n return var\n \n \n dict_totalUser = update_user_dict()\n dict_T = dict_totalUser['dict_T']\n Farm_data = dict_totalUser['Farm_data']\n data = pd.DataFrame(Farm_data)\n data = data.transpose()\n data = data.rename(columns={0:'lat',1:'lon',2:'Volume',3:'Solid Percentage',4:'Cattle',5:'Swine',6:'Poultry'})\n data['id'] = list(range(len(data)))\n data['id+1'] = list(range(1,len(data)+1))\n st.title('Biodigestor 2021 EM.428 MIT')\n st.header('Ricardo Hopker, Niek van Rensburg, Jacqueline Baidoo and ByeongJo Kong')\n st.write(\"\")\n st.subheader(\"Inputs:\")\n #[V_gBurn,ng,Tdig,debt_level,V_cng_p,farm1,farm2,farm3,farm4,farm5,farm6,farm7]\n session_state.V_gBurn = st.number_input('Volume of Gas burn as % of biogas produced',0.0,1.0,value = session_state.V_gBurn)\n session_state.ng = st.number_input('Number of Eletricity Generators',1,value = session_state.ng)\n # Tdig = st.number_input('Temperature of the digestor (C°): ',value = 37)\n session_state.debt_level = st.number_input('Debt level of the project',0.0,1.0,value = session_state.debt_level)\n session_state.V_cng_p = st.number_input('Volume of Gas upgraded to biodiesel for manure transportation: ',0.0,1.0,value = session_state.V_cng_p)\n session_state.farm1 = st.number_input('is farm 1 active: ',0,1,value = session_state.farm1)\n session_state.farm2 = st.number_input('is farm 2 active: ',0,1,value = session_state.farm2)\n session_state.farm3 = st.number_input('is farm 3 active: ',0,1,value = session_state.farm3)\n session_state.farm4 = st.number_input('is farm 4 active: ',0,1,value = session_state.farm4)\n session_state.farm5 = st.number_input('is farm 5 active: ',0,1,value = session_state.farm5)\n session_state.farm6 = st.number_input('is farm 6 active: ',0,1,value = session_state.farm6)\n session_state.farm7 = st.number_input('is farm 7 active: ',0,1,value = session_state.farm7)\n session_state.lam = st.number_input('Multi-objective (1 full NPV, 0 full emissions): ',0.0,1.0,value = float(session_state.lam))\n dict_totalUser['lam'] = session_state.lam\n x = [session_state.V_gBurn,session_state.ng,session_state.debt_level,\n session_state.V_cng_p,session_state.farm1,session_state.farm2,\n session_state.farm3,session_state.farm4,session_state.farm5,\n session_state.farm6,session_state.farm7]\n st.write('objective function value:')\n st.write(-biodigestor(cleanXopt(x,dict_totalUser),dict_totalUser,session_state.lam,True,False))\n active_farms= x[4:11] \n active_farms = [False if num<1 or num==False else True for num in active_farms]\n if st.checkbox('Optimize with lamda above'):\n \n # print(dict_totalUser['e_priceS'])\n \n args = (dict_totalUser,session_state.lam,True,False,False,True)\n # xopt = fminClean(x,args)\n res = run_singleJ(dict_totalUser)\n xopt = res.X\n xoptSer = pd.DataFrame(pd.Series(cleanXopt(xopt,dict_totalUser),index=['V_gBurn','ng','debt_level','V_cng_p','farm1','farm2','farm3','farm4','farm5','farm6','farm7'])).transpose()\n st.write('Best X')\n st.write(xoptSer.style.format({'V_gBurn':\"{:.2}\",'debt_level':\"{:.2}\",'V_cng_p':\"{:.2}\"}))\n # print(cleanXopt(xopt))\n st.write('Best Obj')\n st.write(-cleanBiodigestor(xopt,dict_totalUser,session_state.lam,True,False,False,True))\n \n @st.cache()\n def load_tradespace_func():\n df,F,annot = plotMultiJ(run_multiJ(dict_totalUser),dict_totalUser)\n return df,F,annot\n \n if st.checkbox('View multiobjective tradespace'):\n st.write('multiobjective tradespace:')\n df,F,annot = load_tradespace_func()\n fig,ax = plt.subplots()\n ax.scatter(df['NPV'],df['gwp'],s=20,c='r')\n ax.set_xlabel('NPV')\n ax.set_ylabel('gwp')\n ax.plot(df['NPV'],df['gwp'],c='r',lw=1)\n \n ax.scatter(annot[0],annot[1],marker='*',c='y',s=120)\n ax.scatter(F[0],F[1],c='b',s=0.5,)\n if ax.get_xlim()[0]<-3e6:\n \n ax.set_xlim([min(df['NPV'])-1000,annot[0]+1000])\n colDict = {}\n colnames = ['V_gBurn','ng','debt_level','V_cng_p','farm1','farm2','farm3','farm4','farm5','farm6','farm7'] \n for j in range(11):\n colDict[j]=colnames[j]\n df = df.rename(columns=colDict)\n st.write(fig)\n st.write('Pareto front vectors: ',df.style.format({'gwp':\"{:.2}\",'NPV':\"{:.2}\",'V_gBurn':\"{:.2}\",'debt_level':\"{:.2}\",'V_cng_p':\"{:.2}\"}))\n \n \n # wasteData\n map_data = data[['lat','lon']]\n # map_data\n # st.map(map_data)\n \n \n \n \n view_state = pdk.ViewState(\n longitude=map_data.mean()['lon'], latitude= map_data.mean()['lat'], zoom=8.5, min_zoom=5, max_zoom=15, pitch=0, bearing=-27.36)\n @st.cache()\n def active_farmsfun(tf,compare = None):\n active_farms1= x[4:11] \n active_farms1 = [0 if num<1 or num==False else 1 for num in active_farms1]\n active_farms= x[4:11] \n active_farms = [False if num<1 or num==False else True for num in active_farms]\n [distance, wIn, total_solids_perc, wComp,Tpath] = dict_T[tuple(active_farms1)]\n count = 0\n count_id =0\n if tf:\n compare = Tpath[0]\n for i in active_farms1:\n if i ==1:\n if count == compare:\n dig_id=count_id\n count = count +1\n count_id = count_id+1\n \n \n layer_active = pdk.Layer(\n \"ScatterplotLayer\",\n data[active_farms],\n get_position=['lon', 'lat'],\n auto_highlight=True,\n get_radius=1000,\n get_fill_color=['id == ' + str(dig_id)+' ? 255 : 0', 0, 0, 255],\n # get_fill_color=[0, 0, 0, 255],\n # elevation_scale=50,\n pickable=True,\n get_weight = 'Volume > 0 ? Volume : 0',\n extruded=True,\n coverage=1,\n )\n r_active = pdk.Deck(\n map_style=\"mapbox://styles/mapbox/light-v9\",\n layers=[layer_active],\n initial_view_state=view_state,\n tooltip={\"html\": \"Manure Volume: {Volume}
Farm: {id+1}\", \"style\": {\"color\": \"white\"}},\n )\n \n return r_active,Tpath\n @st.cache()\n def load_r_path(Tpath):\n r = []\n for i in Tpath:\n r_new,Tpath2 = active_farmsfun(False,i)\n r.append(r_new)\n return r\n if st.checkbox('View active farms'):\n st.write('Active farms: in red digestor location')\n r_active,Tpath = active_farmsfun(True)\n # print(Tpath)\n st.pydeck_chart(r_active)\n if st.checkbox('View manure transport path for active farms'):\n active_farms1= x[4:11] \n active_farms1 = [0 if num<1 or num==False else 1 for num in active_farms1]\n active_farms= x[4:11] \n active_farms = [False if num<1 or num==False else True for num in active_farms]\n [distance, wIn, total_solids_perc, wComp,Tpath] = dict_T[tuple(active_farms1)]\n r = load_r_path(Tpath)\n st.write('Active farms: current truck location in red')\n curr_step = st.slider('Step',0,int(len(Tpath)-1),value =0, step = 1)\n \n # r_active,Tpath = active_farmsfun(False,Tpath[curr_step])\n # print(Tpath)\n st.pydeck_chart(r[curr_step])\n @st.cache()\n def show_farmsfun():\n layer_farms = pdk.Layer(\n \"ScatterplotLayer\",\n data,\n get_position=['lon', 'lat'],\n auto_highlight=True,\n get_radius=1000,\n get_fill_color=['id * 42.5', 'id * 42.5', 0, 255],\n # get_fill_color=[0, 0, 0, 255],\n # elevation_scale=50,\n pickable=True,\n # elevation_range=[0, 3000],\n extruded=True,\n coverage=1,\n )\n r = pdk.Deck(\n map_style=\"mapbox://styles/mapbox/light-v9\",\n layers=[layer_farms],\n initial_view_state=view_state,\n tooltip={\"html\": \"Manure Volume: {Volume}
Farm: {id+1}\", \"style\": {\"color\": \"white\"}},\n )\n return r\n if st.checkbox('Show farm locations'):\n st.write('Farms:')\n r = show_farmsfun()\n st.pydeck_chart(r)\n \n @st.cache() \n def farm_heatmapFunc():\n active_farms1= x[4:11] \n active_farms1 = [0 if num<1 or num==False else 1 for num in active_farms]\n [distance, wIn, total_solids_perc, wComp,Tpath] = dict_T[tuple(active_farms1)]\n dig_id=Tpath[0]\n layer_heat = pdk.Layer(\n \"HeatmapLayer\",\n data,\n get_position=['lon', 'lat'],\n auto_highlight=True,\n get_radius=1000,\n get_fill_color=['lon==' + str(map_data['lon'].iloc[dig_id])+' ? 255 : 0', 0, 0, 255],\n # elevation_scale=50,\n pickable=True,\n elevation_range=[0, 3000],\n get_weight = 'Volume > 0 ? Volume : 0',\n extruded=True,\n coverage=1,\n )\n r = pdk.Deck(\n map_style=\"mapbox://styles/mapbox/light-v9\",\n layers=[layer_heat],\n initial_view_state=view_state,\n tooltip={\"html\": \"Manure Volume: {Volume}
Farm: {id+1}\", \"style\": {\"color\": \"white\"}},\n )\n return r\n \n if st.checkbox('Show farm heatmaps'):\n st.write('Manure volume heatmap:')\n r = farm_heatmapFunc()\n st.pydeck_chart(r)\ndef page2():\n session_state = load_session()\n st.title('Parameters: ')\n st.write('Electrical Energy: ')\n session_state.e_priceS = st.number_input('Price of electrical energy sold (R$/kWh): ',0.0,value = session_state.e_priceS)\n session_state.e_c = st.number_input('Electrical energy consumed in the farms (kWh/year): ',0.0,value = session_state.e_c)\n session_state.e_priceB = st.number_input('Price of electrical energy bought (R$/kWh): ',0.0,value = session_state.e_priceB)\n st.write('Fertilizer: ')\n session_state.f_used = st.number_input('Quantity of fertilizer used in the farms (kg/year): ',0.0,value = session_state.f_used)\n session_state.p_bf = st.number_input('Price of buying fertilizer used in the farms (R$/kg): ',0.0,value = session_state.p_bf)\n session_state.p_l = st.number_input('Selling price of fertilizer surplus (R$/kg): ',0.0,value = session_state.p_l)\n st.write('Transportation: ')\n session_state.c_rskm = st.number_input('Cost to transport manure (R$/km): ',0.0,value = session_state.c_rskm )\n session_state.c_km = session_state.c_rskm\n session_state.T_m3_km_cng = st.number_input('Truck average CNG consumption (m^3/km): ',0.0,value = session_state.T_m3_km_cng)\n session_state.T_L_km_diesel = st.number_input('Truck average diesel consumption (L/km): ',0.0,value = session_state.T_L_km_diesel)\n session_state.V_per_truck = st.number_input('Truck maximum capacity (m^3): ',0.0,value = session_state.V_per_truck)\n session_state.truck_gwp_emmited = st.number_input('Truck emission CO2 (kgCO2/km): ',0.0,value = session_state.truck_gwp_emmited)\n st.write('Biogas: ')\n session_state.C_V_gas = st.number_input('Cost to produce biogas (R$/m^3): ',0.0,value = session_state.C_V_gas)\n session_state.p_g = st.number_input('Selling price of biogas (R$/m^3): ',0.0,value = session_state.p_g)\n session_state.C_upgrade_cng = st.number_input('Cost to upgrade biogas to CNG (R$/m^3): ',0.0,value = session_state.C_upgrade_cng)\n st.write('Generator: ')\n session_state.g_d = st.number_input('Cost purchase eletricity generator (R$/unit): ',0.0,value = session_state.g_d)\n session_state.g_eff = st.number_input('Eletricity generator efficiency with biogas (%): ',0.0,1.0,value = session_state.g_eff)\n session_state.g_power = st.number_input('Eletricity generator power capacity (kW): ',0.0,value = session_state.g_power)\n session_state.g_m = st.number_input('Yealy cost of maintenance of eletricity generator (R$/(unit*year)): ',0.0,value = session_state.g_m)\n session_state.ng_max = st.number_input('Maximum number of generators (units): ',0,value = session_state.ng_max)\n st.write('Biodigestor: ')\n session_state.i_main_cost = st.number_input('Yealy cost of maintenance of biodigestor (% of investment/year): ',0.0,1.0,value = session_state.i_main_cost)\n session_state.L = st.number_input('Biodigestor life (years): ',0,value = session_state.L)\n st.write('Financial: ')\n session_state.kd = st.number_input('Cost of debt (%): ',0.0,value = session_state.kd)\n session_state.max_debt = st.number_input('Maximum debt allowed (%): ',0.0,1.0,value = session_state.max_debt)\n session_state.ke = st.number_input('Cost of equity (%): ',0.0,value = session_state.ke)\n session_state.tax = st.number_input('Tax on profits (%): ',0.0,1.0,value = session_state.tax)\n session_state.USS_to_RS = st.number_input('Corversion of US$ to R$ (R$/US$): ',0.0,value = session_state.USS_to_RS)\n session_state.working_days = st.number_input('Working days per year (days/year): ',0,365,value = session_state.working_days)\n session_state.working_hours = st.number_input('Working hours per day (hours/day): ',0,24,value = session_state.working_hours)\n st.write('Tradespace GA settings: ')\n session_state.NSGA_pop = st.number_input('GA population size (#): ',0,value = session_state.NSGA_pop)\n session_state.NSGA_gen = st.number_input('GA number of generations (#): ',0,value = session_state.NSGA_gen)\n session_state.NSGA_off = st.number_input('GA population offsprings (#/iteration): ',0,value = session_state.NSGA_off)\n st.write('Optimizer GA settings: ')\n session_state.GA_pop = st.number_input('Single objective GA population size (#): ',0,value = session_state.GA_pop)\n session_state.GA_gen = st.number_input('Single objective GA number of generations (#): ',0,value = session_state.GA_gen)\n session_state.GA_off = st.number_input('Single objective GA population offsprings (#/iteration): ',0,value = session_state.GA_off)\n\n\ndef pageTransport():\n session_state = load_session()\n st.title('Transportation Module: ')\n st.subheader('Do not forget to save your changes in the end of the page')\n # dict_T = session_state.dict_T\n Farm_data = copy.deepcopy(session_state.Farm_data)\n st.write('Farm 1: ')\n Farm_data['Farm_1'][0] = st.number_input('Farm 1 Latitude : ',-90.0,90.0,value = Farm_data['Farm_1'][0],format='%f')\n Farm_data['Farm_1'][1] = st.number_input('Farm 1 Longitude : ',-180.0,180.0,value = Farm_data['Farm_1'][1],format='%f')\n Farm_data['Farm_1'][2] = st.number_input('Farm 1 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_1'][2])\n Farm_data['Farm_1'][3] = st.number_input('Farm 1 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_1'][3])\n Farm_data['Farm_1'][4] = st.number_input('Farm 1 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_1'][4])\n Farm_data['Farm_1'][5] = st.number_input('Farm 1 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_1'][5])\n Farm_data['Farm_1'][6] = st.number_input('Farm 1 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_1'][6])\n \n st.write('Farm 2: ')\n Farm_data['Farm_2'][0] = st.number_input('Farm 2 Latitude : ',-90.0,90.0,value = Farm_data['Farm_2'][0],format='%f')\n Farm_data['Farm_2'][1] = st.number_input('Farm 2 Longitude : ',-180.0,180.0,value = Farm_data['Farm_2'][1],format='%f')\n Farm_data['Farm_2'][2] = st.number_input('Farm 2 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_2'][2])\n Farm_data['Farm_2'][3] = st.number_input('Farm 2 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_2'][3])\n Farm_data['Farm_2'][4] = st.number_input('Farm 2 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_2'][4])\n Farm_data['Farm_2'][5] = st.number_input('Farm 2 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_2'][5])\n Farm_data['Farm_2'][6] = st.number_input('Farm 2 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_2'][6])\n \n st.write('Farm 3: ')\n Farm_data['Farm_3'][0] = st.number_input('Farm 3 Latitude : ',-90.0,90.0,value = Farm_data['Farm_3'][0],format='%f')\n Farm_data['Farm_3'][1] = st.number_input('Farm 3 Longitude : ',-180.0,180.0,value = Farm_data['Farm_3'][1],format='%f')\n Farm_data['Farm_3'][2] = st.number_input('Farm 3 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_3'][2])\n Farm_data['Farm_3'][3] = st.number_input('Farm 3 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_3'][3])\n Farm_data['Farm_3'][4] = st.number_input('Farm 3 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_3'][4])\n Farm_data['Farm_3'][5] = st.number_input('Farm 3 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_3'][5])\n Farm_data['Farm_3'][6] = st.number_input('Farm 3 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_3'][6])\n \n st.write('Farm 4: ')\n Farm_data['Farm_4'][0] = st.number_input('Farm 4 Latitude : ',-90.0,90.0,value = Farm_data['Farm_4'][0],format='%f')\n Farm_data['Farm_4'][1] = st.number_input('Farm 4 Longitude : ',-180.0,180.0,value = Farm_data['Farm_4'][1],format='%f')\n Farm_data['Farm_4'][2] = st.number_input('Farm 4 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_4'][2])\n Farm_data['Farm_4'][3] = st.number_input('Farm 4 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_4'][3])\n Farm_data['Farm_4'][4] = st.number_input('Farm 4 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_4'][4])\n Farm_data['Farm_4'][5] = st.number_input('Farm 4 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_4'][5])\n Farm_data['Farm_4'][6] = st.number_input('Farm 4 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_4'][6])\n \n st.write('Farm 5: ')\n Farm_data['Farm_5'][0] = st.number_input('Farm 5 Latitude : ',-90.0,90.0,value = Farm_data['Farm_5'][0],format='%f')\n Farm_data['Farm_5'][1] = st.number_input('Farm 5 Longitude : ',-180.0,180.0,value = Farm_data['Farm_5'][1],format='%f')\n Farm_data['Farm_5'][2] = st.number_input('Farm 5 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_5'][2])\n Farm_data['Farm_5'][3] = st.number_input('Farm 5 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_5'][3])\n Farm_data['Farm_5'][4] = st.number_input('Farm 5 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_5'][4])\n Farm_data['Farm_5'][5] = st.number_input('Farm 5 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_5'][5])\n Farm_data['Farm_5'][3] = st.number_input('Farm 5 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_5'][6])\n \n st.write('Farm 6: ')\n Farm_data['Farm_6'][0] = st.number_input('Farm 6 Latitude : ',-90.0,90.0,value = Farm_data['Farm_6'][0],format='%f')\n Farm_data['Farm_6'][1] = st.number_input('Farm 6 Longitude : ',-180.0,180.0,value = Farm_data['Farm_6'][1],format='%f')\n Farm_data['Farm_6'][2] = st.number_input('Farm 6 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_6'][2])\n Farm_data['Farm_6'][3] = st.number_input('Farm 6 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_6'][3])\n Farm_data['Farm_6'][4] = st.number_input('Farm 6 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_6'][4])\n Farm_data['Farm_6'][5] = st.number_input('Farm 6 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_6'][5])\n Farm_data['Farm_6'][6] = st.number_input('Farm 6 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_6'][6])\n \n st.write('Farm 7: ')\n Farm_data['Farm_7'][0] = st.number_input('Farm 7 Latitude : ',-90.0,90.0,value = Farm_data['Farm_7'][0],format='%f')\n Farm_data['Farm_7'][1] = st.number_input('Farm 7 Longitude : ',-180.0,180.0,value = Farm_data['Farm_7'][1],format='%f')\n Farm_data['Farm_7'][2] = st.number_input('Farm 7 Manure volume (m^3): ',-180.0,180.0,value = Farm_data['Farm_7'][2])\n Farm_data['Farm_7'][3] = st.number_input('Farm 7 Manure Solid percentage (%): ',0.0,1.0,value = Farm_data['Farm_7'][3])\n Farm_data['Farm_7'][4] = st.number_input('Farm 7 Cattle Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_7'][4])\n Farm_data['Farm_7'][5] = st.number_input('Farm 7 Swine Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_7'][5])\n Farm_data['Farm_7'][6] = st.number_input('Farm 7 Poultry Manure percentage (%): ',0.0,1.0,value = Farm_data['Farm_7'][6])\n \n if st.button('Update Transportation model with new farm information'):\n st.write('Please wait a little while we update the model')\n session_state.Farm_data = copy.deepcopy(Farm_data)\n session_state.dict_T = createTransportSurrogateModel(update_user_dict())\n st.write('Done')\ndef page3():\n st.title('Model explanation and final report: ')\n st.header('This is an optimization model for biodigestors created for the MIT EM.428 class of Spring 2021')\n st.subheader('By: Ricardo Hopker, Niek van Rensburg, Jacqueline Baidoo and ByeongJo Kong')\n st.subheader('')\n pdf = 'Pset 4 Ricardo Hopker.pdf'\n pdf_file = open(pdf, 'rb')\n base64_pdf = base64.b64encode(pdf_file.read()).decode('Latin-1')\n pdf_display = f'