blablublala
',\n '')\n\n def test_for_coverage(self):\n self.assertHtmlEqualsXmlFragment('bla
', 'bla
')\n\nclass TestCharsetDetection(XmlEquivTest):\n def assertCodecEqual(self, a, b):\n self.assertEqual(codecs.lookup(a).name, codecs.lookup(b).name)\n\n def assertHtmlEqualsXml(self, html, xml, charset=None):\n htree = mechanize_mini.parsehtmlbytes(html, charset)\n xtree = ET.fromstring(xml)\n\n # prune empty text nodes from xml\n for el in xtree.iter():\n if str(el.text).strip() == '':\n el.text = None\n if str(el.tail).strip() == '':\n el.tail = None\n\n self.assertEqual(htree.outer_xml,\n ET.tostring(xtree, encoding='unicode'))\n\n def test_default(self):\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'cp1252')\n\n # yes, even if utf-8 characters are inside we still default to cp1252\n self.assertCodecEqual(mechanize_mini.detect_charset('blabläáßð«»'.encode('utf8')), 'cp1252')\n\n def test_xml_declaration(self):\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'utf8')\n\n # but meta tag overrides it\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'iso-8859-15')\n\n def test_bom(self):\n # various utf trickeries\n\n self.assertCodecEqual(mechanize_mini.detect_charset('\\uFEFFblöáðäü'.encode('utf-16-le')), 'utf-16-le')\n self.assertCodecEqual(mechanize_mini.detect_charset('\\uFEFFblöáðäü'.encode('utf-16-be')), 'utf-16-be')\n self.assertCodecEqual(mechanize_mini.detect_charset('\\uFEFFblöáðäü'.encode('utf8')), 'utf_8')\n\n # BOM overrides anything else\n self.assertCodecEqual(mechanize_mini.detect_charset(codecs.BOM_UTF8 + b''), 'utf_8')\n\n def test_meta(self):\n\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'cp1252')\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'utf-8')\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'cp1252')\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'utf-8')\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'utf-8')\n\n # multiple meta tags -> only first valid one is evaluated\n self.assertCodecEqual(mechanize_mini.detect_charset(b'blabla'), 'cp1252')\n self.assertCodecEqual(mechanize_mini.detect_charset(b'blabla'), 'utf-8')\n\n # meta content without charset -> cp1252\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'cp1252')\n\n # meta in ASCII test with UTF-16 -> gets turned into UTF-8\n self.assertCodecEqual(mechanize_mini.detect_charset(b'blabla'), 'utf-8')\n\n def test_garbage(self):\n # garbage charset -> default win1252\n\n self.assertCodecEqual(mechanize_mini.detect_charset(b''), 'cp1252')\n\n self.assertCodecEqual(mechanize_mini.detect_charset(b'blabla', 'lutscher'), 'cp1252')\n\n def test_override(self):\n self.assertCodecEqual(mechanize_mini.detect_charset(b'bla', 'utf-8'), 'utf-8')\n self.assertCodecEqual(mechanize_mini.detect_charset(b'bla', 'ASCII'), 'cp1252')\n self.assertCodecEqual(mechanize_mini.detect_charset(b'bla', 'latin-1'), 'cp1252')\n\n def test_html(self):\n # standard case\n self.assertHtmlEqualsXml(b'bla', '
bla
')\n\n # unicode characters interpreted as cp1252\n self.assertHtmlEqualsXml('a\\u2019b'.encode('utf-8'), 'a’b')\n\n # cp1252 characters misinterpreted as utf-8\n self.assertHtmlEqualsXml('aüb'.encode('cp1252'), 'a\\uFFFDb', charset='utf8')\n\nclass TestConvenience(unittest.TestCase):\n def test_text_content(self):\n content = mechanize_mini.parsefragmentstr('bla')\n self.assertEqual(content.text_content, 'bla')\n\n el = mechanize_mini.parsefragmentstr('
bla
blub \\nhola
')\n self.assertEqual(el.text_content, 'bla blub hola')\n\n def test_inner_html(self):\n el = mechanize_mini.HTML('
Hello World
')\n self.assertEqual(el.inner_html, 'Hello
World')\n\n el.inner_html = 'Goodbye
World'\n self.assertEqual(el.text, 'Goodbye ')\n self.assertEqual(len(el), 1)\n self.assertEqual(el.outer_xml, '
Goodbye World
')\n\nclass FindStuffTest(unittest.TestCase):\n def test_find_by_tag_name(self):\n test = mechanize_mini.parsefile(os.path.dirname(os.path.abspath(__file__)) + '/files/form.html')\n\n self.assertEqual(test.query_selector('form').tag, 'form')\n\n def test_find_by_class(self):\n test = mechanize_mini.parsefile(os.path.dirname(os.path.abspath(__file__)) + '/files/elements.html')\n\n # not existing\n self.assertEqual(test.query_selector('.nada'), None)\n\n # but there should be two of these\n self.assertEqual(len(list(test.query_selector_all('p.important'))), 2)\n\n def test_find_by_id(self):\n test = mechanize_mini.parsefile(os.path.dirname(os.path.abspath(__file__)) + '/files/elements.html')\n\n self.assertEqual(test.query_selector('#importantest').get('id'), 'importantest')\n\n def test_find_by_text(self):\n test = mechanize_mini.parsefile(os.path.dirname(os.path.abspath(__file__)) + '/files/elements.html')\n\n self.assertEqual(test.query_selector('.bar.baz.important').text_content, 'I am even more importanter')\n\n self.assertEqual(test.query_selector('p:contains(I am even more importanter)').get('class'), 'bar baz important')\n\nclass SelectorTest(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.f = mechanize_mini.HTML('''\n
\n
\n bar\n
\n ''')\n\n\n def test_tags(self):\n spans = list(self.f.query_selector_all('span'))\n self.assertEqual(len(spans), 3)\n self.assertEqual([e.text for e in spans], ['test', 'test2', 'bar'])\n\n def test_descendant(self):\n indiv = list(self.f.query_selector_all('div span'))\n #self.assertEqual(len(indiv), 2)\n self.assertEqual([e.text for e in indiv], ['test', 'test2'])\n\n doubldiv = list(self.f.query_selector_all('div div span'))\n self.assertEqual(len(doubldiv), 1)\n self.assertEqual(doubldiv[0].text, 'test')\n\n nope = list(self.f.query_selector_all('html div'))\n self.assertEqual(len(nope), 0)\n\n def test_class_id(self):\n clazz = list(self.f.query_selector_all('.a'))\n self.assertEqual([e.text for e in clazz], ['test', 'test2'])\n\n clazz = list(self.f.query_selector_all('#outerdiv.outerdiv div#innerdiv span.a'))\n self.assertEqual([e.text for e in clazz], ['test'])\n\n multiclazz = list(self.f.query_selector_all('.a.b'))\n self.assertEqual([e.text for e in multiclazz], ['test2'])\n\n def test_child(self):\n immed = list(self.f.query_selector_all('.outerdiv >.a'))\n self.assertEqual([e.text for e in immed], ['test2'])\n\n def test_invalid(self):\n with self.assertRaises(mechanize_mini.InvalidSelectorError):\n list(self.f.query_selector_all('a:hover')) # not supported and will never be\n\n def test_universal_selector(self):\n sel = list(self.f.query_selector_all('* div'))\n self.assertEqual([e.id for e in sel], ['innerdiv'])\n\n sel = list(self.f.query_selector_all('* html')) # this is not IE6\n self.assertEqual(sel, [])\n\n def test_additional_whitespace(self):\n immed = list(self.f.query_selector_all(\".outerdiv> \\t .a \"))\n self.assertEqual([e.text for e in immed], ['test2'])\n\n def test_contains(self):\n self.assertEqual(self.f.query_selector(\"p:contains(\\\"bar\\\")\").id, 'barp')\n self.assertEqual(self.f.query_selector(\"span:contains(ba)\").text_content, 'bar')\n\n def test_empty(self):\n self.assertEqual(self.f.query_selector(''), None)\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"genosse-einhorn/python-mechanize-mini","sub_path":"test/htmltree.py","file_name":"htmltree.py","file_ext":"py","file_size_in_byte":19429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3987369824","text":"import sys, argparse\nimport numpy as np\nimport math\nimport time \n\nfrom PIL import Image\n \n# gray scale level values from:\n# http://paulbourke.net/dataformats/asciiart/\n \n\ngscale1 = \"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\\\"^`'. \"\n \n\ngscale2 = '@%#*+=-:. '\n# gscale2 = \"@#S%?*+;:, \"\n \ndef getAverageL(image):\n \n\n im = np.array(image)\n w,h = im.shape\n \n\n return np.average(im.reshape(w*h))\n \ndef convertImageToAscii(image, w, scale , moreLevels):\n\n global gscale1, gscale2\n \n\n # image = Image.open(fileName).convert('L')\n image = image.convert(\"L\")\n\n W, H = image.size[0], image.size[1]\n # print(\"input image dims: %d x %d\" % (W, H))\n \n cols = int(W/w)\n h = w*scale\n rows = int(H/h)\n \n # print(\"cols: %d, rows: %d\" % (cols, rows))\n\n # print(\"tile dims: %d x %d\" % (w, h))\n \n\n if cols > W or rows > H:\n print(\"Image too small for specified cols!\")\n exit(0)\n \n\n aimg = []\n\n for j in range(rows):\n y1 = int(j*h)\n y2 = int((j+1)*h)\n \n # correct last tile\n if j == rows-1:\n y2 = H\n \n aimg.append(\"\")\n \n for i in range(cols):\n\n x1 = int(i*w)\n x2 = int((i+1)*w)\n \n if i == cols-1:\n x2 = W\n\n lg1 = len(gscale1)-1\n lg2 = len(gscale2)-1\n\n img = image.crop((x1, y1, x2, y2))\n \n avg = int(getAverageL(img))\n \n if moreLevels:\n gsval = gscale1[int((avg*lg1)/255)]\n else:\n gsval = gscale2[int((avg*lg2)/255)]\n \n aimg[j] += gsval\n \n return aimg\n \n\ndef main():\n\n descStr = \"This program converts an image into ASCII art.\"\n parser = argparse.ArgumentParser(description=descStr)\n\n parser.add_argument('--file', dest='imgFile', required=True)\n parser.add_argument('--scale', dest='scale', required=False)\n parser.add_argument('--out', dest='outFile', required=False)\n parser.add_argument('--w', dest='w', required=False)\n parser.add_argument('--morelevels',dest='moreLevels',action='store_true')\n \n\n args = parser.parse_args()\n \n imgFile = args.imgFile\n \n\n outFile = 'out.txt'\n if args.outFile:\n outFile = args.outFile\n \n\n if args.scale:\n scale = float(args.scale)\n \n if args.w:\n w = int(args.w)\n\n t1 = time.time()\n\n image = Image.open(imgFile)\n \n print('generating ASCII art...')\n aimg = convertImageToAscii(image, w, scale, args.moreLevels)\n \n f = open(outFile, 'w')\n \n for row in aimg:\n f.write(row + '\\n')\n \n f.close()\n print(\"ASCII art written to %s\" % outFile)\n t2 = time.time()\n print(f\"Time for generate ascii {t2 - t1}\")\n \nif __name__ == '__main__':\n main()","repo_name":"JKLeorio/asciiConventer","sub_path":"asciiImageConverter.py","file_name":"asciiImageConverter.py","file_ext":"py","file_size_in_byte":2753,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"20654873448","text":"from django.shortcuts import render\n\n\ndef example_view(req):\n # my_app/templates/my_app/example.html\n return render(req, 'my_app/example.html')\n\n\ndef variable_view(req):\n my_var = {\n # 字符串变量\n 'first_name': 'Rosalind',\n 'last_name': 'Franklin',\n # list变量\n 'some_list': [1, 2, 3],\n # 字典变量\n 'some_dict': {\n 'inside_key': 'inside_value'\n },\n # bool\n 'user_logged_in': True\n }\n # context是上下文对象,在模板文件里可以拿到\n return render(req, 'my_app/variable.html', context=my_var)\n","repo_name":"malred/i_site","sub_path":"my_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38073718145","text":"import sys\n\nin_put = sys.stdin.readline\n\n\ndef selfnum(n):\n a=b=c=d=0\n if n >= 1000:\n a = n // 1000\n if n >= 100:\n b = (n//100 )%10\n if n >= 10:\n c = (n//10)%10\n d= n%10\n\n return n+a+b+c+d\n\n\n\nd=[]\nfor i in range(1,10000):\n d.append(selfnum(i))\n\n\n\nfor i in range(1,10000):\n if not d.count(i):\n print(i)\n","repo_name":"machi107/Baekjoon-Codes","sub_path":"Silver 5/4673 셀프 넘버.py","file_name":"4673 셀프 넘버.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"41796583995","text":"import urllib.request\nimport json\nfrom datetime import datetime, timedelta\n\n\nclass requester:\n \"\"\"\n This class is to request the timestamp and weather stock_info from the API\n and return it as a dictionary validating for date interval or sending\n yesterday information\n \"\"\"\n\n def __init__(self) -> None:\n \" Defining the url for the API\"\n self.__url = \"https://api.weather.gov/stations/KBFL/observations\"\n\n def get_weather_report(self, start: str, end: str) -> dict:\n \"Method that returns the information when start and end date is provided\"\n try:\n st = datetime.strptime(start, \"%Y-%m-%dT%H:%M:%SZ\")\n e = datetime.strptime(end, \"%Y-%m-%dT%H:%M:%SZ\")\n if e < st:\n return \"start date is greater than end date\"\n except ValueError:\n return 'Incorrect start or end data format, /n \\\n format should be \"%Y-%m-%dT%H:%M:%SZ\"'\n\n api_request = self.__url + '?start=' + start + '&end=' + end\n response = urllib.request.urlopen(api_request)\n data: bytes = response.read()\n station_info: dict = json.loads(data)\n result = self.__timestamp_temp(station_info)\n return result\n\n def yesterday_weather_report(self) -> dict:\n \"Method that returns the information for yesterday\"\n today = datetime.now().strftime(\"%Y-%m-%d\")\n today = datetime.strptime(today, \"%Y-%m-%d\")\n yesterday = today - timedelta(days=1)\n start = yesterday.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n end = today.strftime(\"%Y-%m-%dT%H:%M:%SZ\")\n api_request = self.__url + '?start=' + start + '&end=' + end\n response = urllib.request.urlopen(api_request)\n data: bytes = response.read()\n station_info: dict = json.loads(data)\n result = self.__timestamp_temp(station_info)\n return result\n\n def __timestamp_temp(self, station_info: dict) -> list:\n \"Method that returns a list with only timestamp and temperature \\\n receiving the station_info from the API converted to dict\"\n result = []\n for record in station_info['features']:\n result.append((record['properties']['timestamp'],\n record['properties']['temperature']['value']))\n return result[::-1]\n","repo_name":"lfbejarano/Sri-Challenge","sub_path":"API/data_request.py","file_name":"data_request.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23389454811","text":"#! /usr/bin/python\n# -*- coding: utf-8 -*-\n\n\nimport logging\n#logging.basicConfig(level=logging.DEBUG)\n#interact = True\ninteract = False\n\nclass Solved(Exception):\n\tpass\ndef mowed(line, mowed_perpendicular_lines, L, P):\n\ttry:\n\t\tunmowed_fields = set(range(P))-set(mowed_perpendicular_lines)\n\t\tan_unmowed_field = list(unmowed_fields)[0]\n\t\tpossible_height = line[an_unmowed_field]\n\t\tlogging.debug((\"unmowed\", unmowed_fields, an_unmowed_field, mowed_perpendicular_lines))\n\texcept IndexError:\n\t\traise Solved\n\treturn all((line[i] == possible_height) or ((line[i] < possible_height) and i in mowed_perpendicular_lines) for i in range(P))\n\ndef solve_case(case):\n\tlogging.debug((\"solving\", case))\n\tN, M = case[0]\n\tgrid = case[1:]\n\tmowed_rows = []\n\tmowed_columns = []\n\ttry:\n\t\twhile True:\n\t\t\tfound_mowed = False\n\t\t\tfor line, index, mowed_lines, mowed_perpendicular_lines, L, P, debug in [(grid[i], i, mowed_rows, mowed_columns, N, M, \"rows\") for i in range(N)] + [([grid[j][i] for j in range(N)], i, mowed_columns, mowed_rows, M, N, \"columns\") for i in range(M)]:\n\t\t\t\tlogging.debug((\"checking\", debug, line, index, mowed_lines, mowed_perpendicular_lines))\n\t\t\t\tif index not in mowed_lines and mowed(line, mowed_perpendicular_lines, L, P):\n\t\t\t\t\tmowed_lines.append(index)\n\t\t\t\t\tfound_mowed = True\n\t\t\t\t\tlogging.debug(\"yes\")\n\t\t\tif len(mowed_rows) == N or len(mowed_columns) == M:\n\t\t\t\traise Solved\n\t\t\tif not found_mowed:\n\t\t\t\tlogging.debug(\"NO\")\n\t\t\t\treturn \"NO\"\n\texcept Solved:\n\t\tlogging.debug(\"YES\")\n\t\treturn \"YES\"\n\ndef case_line(case_number, cases):\n\t\"\"\"case_number != list index\"\"\"\n\tif interact:\n\t\tinput(case_number)\n\treturn \"Case #{}: {}\".format(case_number, solve_case(cases[case_number-1]))\n\ndef set_to_cases(set_):\n\treturn set_.split(\"\\n\")[1:-1]\n\ndef set_to_cases_blocks(set_):\n\treturn \"\\n\".join(set_to_cases(set_)).split(\"\\n\\n\")\n\ndef set_to_cases_blocks_numbered(set_):\n\tit = iter(set_to_cases(set_))\n\twhile True:\n\t\ttry:\n\t\t\tN, M = map(int, next(it).split(\" \"))\n\t\texcept StopIteration:\n\t\t\tbreak\n\t\telse:\n\t\t\tcase = [(N, M)]\n\t\t\tfor i in range(N):\n\t\t\t\tcase.append(next(it).split(\" \"))\n\t\t\tyield case\n\ndef solve_set(set_):\n\tcases = list(set_to_cases_blocks_numbered(set_))\n\treturn \"\\n\".join(case_line(i+1, cases) for i in range(len(cases)))\n\ntest_in = \"\"\"3\n3 3\n2 1 2\n1 1 1\n2 1 2\n5 5\n2 2 2 2 2\n2 1 1 1 2\n2 1 2 1 2\n2 1 1 1 2\n2 2 2 2 2\n1 3\n1 2 1\n3 1\n1\n2\n1\n\"\"\"\n\ntest_out = \"\"\"Case #1: YES\nCase #2: NO\nCase #3: YES\nCase #4: YES\"\"\"\n\ndef compare_test_case_line(case_number):\n\ttest_solution_line = case_line(case_number, set_to_cases(test_in))\n\ttest_out_line = test_out.split(\"\\n\")[case_number]\n\tif test_solution_line == test_out_line:\n\t\tlogging.info(\"Test line {} passed\".format(case_number))\n\telse:\n\t\tlogging.warning(\"Test line {} failed\".format(case_number))\n\t\tlogging.info(test_solution_line)\n\t\tlogging.info(test_out_line)\n\nlogging.info(list(set_to_cases_blocks_numbered(test_in)))\n\ntest_solution = solve_set(test_in)\n\nif test_solution == test_out:\n\tlogging.info(\"Test passed\")\nelse:\n\tlogging.warning(\"Test failed\")\n\tlogging.info(test_solution)\n\tlogging.info(test_out)\n\nproblem_letter = \"B\"\nattempt = 1\nfor problem_size in (\"small\", \"large\"):\n\tif input(\"Solve {} {}? (y)\".format(problem_letter, problem_size)):\n\t\tname = \"{}-{}{}\".format(problem_letter, problem_size, problem_size == \"small\" and \"-attempt{}\".format(attempt) or \"\")\n\t\twith open(name + \".in\") as file_in:\n\t\t\twith open(name + \".out\".format(problem_letter, problem_size), \"w\") as file_out:\n\t\t\t\tprint(solve_set(file_in.read()), file=file_out)\n\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_117/678.py","file_name":"678.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"28133872310","text":"import random\nfrom django.core.management.base import BaseCommand\nfrom django.contrib.admin.utils import flatten\nfrom django_seed import Seed\nfrom users import models as user_models\nfrom advertisements import models as ad_models\n\n\nclass Command(BaseCommand):\n\n help = \"This command helps to create students' advertisement\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--number\", default=2, type=int, help=\"How many ads you want to create\"\n )\n\n def handle(self, *args, **options):\n number = options.get(\"number\")\n seeder = Seed.seeder()\n all_users = user_models.User.objects.all()\n instrument = ad_models.instrumentChoice.objects.all()\n seeder.add_entity(\n ad_models.Advertisement,\n number,\n {\n \"student\": lambda x: random.choice(all_users),\n \"instrument\": lambda x: random.choice(instrument),\n \"min_fee\": lambda x: random.randint(10000, 30000),\n \"max_fee\": lambda x: random.randint(30000, 100000),\n },\n )\n\n created_ads = seeder.execute()\n created_clean = flatten(list(created_ads.values()))\n desired_lesson_days = ad_models.LessonDay.objects.all()\n lesson_type = ad_models.LessonType.objects.all()\n prefer_style = ad_models.PreferStyle.objects.all()\n\n for pk in created_clean:\n advertisement = ad_models.Advertisement.objects.get(pk=pk)\n\n for d in desired_lesson_days:\n magic_number = random.randint(0, 10)\n if magic_number % 2 == 0:\n advertisement.desired_lesson_days.add(d)\n\n for t in lesson_type:\n magic_number = random.randint(0, 10)\n if magic_number % 2 == 0:\n advertisement.lesson_type.add(t)\n\n for p in prefer_style:\n magic_number = random.randint(0, 10)\n if magic_number % 2 == 0:\n advertisement.prefer_style.add(p)\n\n self.stdout.write(self.style.SUCCESS(f\"{number} students' ads created!\"))\n","repo_name":"bolmun/music_application","sub_path":"advertisements/management/commands/seed_ads.py","file_name":"seed_ads.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"27519191173","text":"from __future__ import print_function # Python 2/3 compatibility\r\nimport boto3\r\nimport json\r\nimport decimal\r\nfrom boto3.dynamodb.conditions import Key\r\n\r\n# Define what table to query base on lex intent\r\nreturn_table = {\r\n 'aboutBooth': 'TempBoothInfo2',\r\n 'aboutEvent': 'EventInfo',\r\n 'Software_Engineering_Booth': 'workshopList'\r\n}\r\nreturn_slot = {\r\n 'aboutBooth': 'Booth',\r\n 'aboutEvent': 'eventName',\r\n 'aboutWorkshop': 'workshopName',\r\n 'listWorkshop': 'workshopList'\r\n}\r\n\r\n\r\ndef queryDB(intent_name,item_name):\r\n try:\r\n dynamodb = boto3.resource('dynamodb', region_name='us-east-1')\r\n table = dynamodb.Table(return_table[intent_name])\r\n response = table.query(\r\n IndexName='Info-index',\r\n KeyConditionExpression=Key('Name').eq(item_name)\r\n )\r\n item_name = str(response['Items'][0]['Info'])\r\n except Exception as e:\r\n item_name += ' is not found. queryDB Debug: ' + str(e)\r\n return item_name\r\n\r\ndef main(event,context):\r\n try:\r\n intent_name = event['currentIntent']['name']\r\n item_name = event['currentIntent']['slotDetails'][return_slot[intent_name]]['resolutions'][0]['value']\r\n except Exception as e:\r\n output = 'Booth not found. Debug: ' + str(e)\r\n response ={\r\n \"dialogAction\": {\r\n \"type\": \"Close\",\r\n \"fulfillmentState\": \"Fulfilled\",\r\n \"message\": {\r\n \"contentType\": \"CustomPayload\",\r\n \"content\": \"Here is what I found: \" + output\r\n },\r\n }\r\n }\r\n return response\r\n\r\n\r\n","repo_name":"180133517/fyp-cdk","sub_path":"cdkdeploy/lambda/lexResponseWithDBinPython.py","file_name":"lexResponseWithDBinPython.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"35796896770","text":"try:\n import os\n import gym_minigrid\n from gym_minigrid.wrappers import *\n from gym_minigrid.envelopes_light import *\n from gym import wrappers, logger\nexcept Exception as e:\n print(\" =========== =========== IMPORT ERROR ===========\")\n print(e)\n pass\n\nfrom configurations import config_grabber as cg\n\n\ndef make_env(env_id, seed, rank, evaluation_id, force=False, resume=False, custom_message=\"_\"):\n\n config = cg.Configuration.grab()\n\n def _thunk():\n env = gym.make(env_id)\n env.seed(seed + rank)\n\n if config.envelope:\n env = SafetyEnvelope(env)\n\n # record only the first agent\n if config.recording and rank==0:\n print(\"starting recording..\")\n eval_folder = os.path.abspath(os.path.dirname(__file__) + \"/../\" + config.evaluation_directory_name)\n if config.envelope:\n expt_dir = eval_folder + \"/\" + evaluation_id + \"_videos\"\n else:\n expt_dir = eval_folder + \"/\" + evaluation_id + \"_videos\"\n\n uid = \"___proc_n_\" + str(rank) + \" ___\" + custom_message + \"__++__\"\n env = wrappers.Monitor(env, expt_dir, uid=uid, force=force, resume=resume)\n\n return env\n\n return _thunk\n","repo_name":"pierg/wiseml-patterns","sub_path":"pytorch_a2c/envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"39346109666","text":"'''\n\n24-game gives the player 4 numbers, and ask for player to use operations +, -, * on these numbers\nin a way that the result equals to 24\n\n'''\nimport operator\nimport random\nimport itertools\n\nclass number_set():\n\n def __init__(self, a, b, c, d):\n\n self.numbers = [a, b, c, d]\n\n def start_game(self):\n print('Wecome to the game. here are the {0}'.format(self.numbers))\n\n def user_input(self):\n ask_for_input = input(\"please give 3 operations (possible: add for +, sub for -, mul for *) in the order, separate by comma\") # add, sub, mul\n\n while not(len(ask_for_input) == 13):\n ask_for_input = input(\"please check if the operations are correct\")\n\n return ask_for_input\n\n def split(self, user_input):\n x,y,z = user_input.split(',')\n\n return [x.replace(' ', ''),y.replace(' ', ''),z.replace(' ', '')]\n\n def operators(self, operators):\n\n _func = {'add': operator.add, # add\n 'sub': operator.sub, # substract\n 'mul': operator.mul # multiplication\n }\n\n self.f1 = _func[operators[0]]\n self.f2 = _func[operators[1]]\n self.f3 = _func[operators[2]]\n\n def calculate(self):\n self.result1 = self.f1(self.numbers[0], self.numbers[1])\n self.result2 = self.f2(self.result1, self.numbers[2])\n self.result3 = self.f3(self.result2, self.numbers[3])\n return self.result3\n\n def check_answer(self, result3):\n if self.result3 == 24:\n print('Correct')\n\n trial = 0\n while self.result3 != 24:\n print(\"The current answer is {}. Enter 'T' to try again. Enter 'N' to shower answer\".format(self.result3))\n choice = input()\n if choice == 'T' and trial <= 3:\n trial += 1\n user_operations = self.user_input()\n user_operations = self.split(user_operations)\n self.operators(user_operations)\n self.result3 = self.calculate()\n #print(\"The current answer is {}. Enter 'T' to try again. Enter 'N' to shower answer\".format(self.result3))\n if choice == 'T' and trial > 3:\n print('you have reached total number of trials')\n print(answer)\n else:\n print(answer)\n break\n\ndef generate_answers():\n list_all_num = list(itertools.combinations_with_replacement(range(1, 10), 4))\n #print(len(list_all_num))\n\n ops = ['add', 'sub', 'mul']\n list_all_ops = list(itertools.combinations_with_replacement(ops, 3))\n #print(list_all_ops)\n\n possible_cases = []\n all_answers = []\n for i in list_all_num:\n test = number_set(*i)\n for j in list_all_ops:\n user_operations = j\n test.operators(user_operations)\n temp = test.calculate()\n if temp == 24:\n possible_cases.append(i)\n all_answers.append([i, j])\n\n return possible_cases, all_answers\n\nif __name__ == '__main__':\n possible_cases, all_answers = generate_answers()\n\n choice = random.choice(possible_cases)\n answer_index = possible_cases.index(choice)\n answer = all_answers[answer_index] # save the answer\n\n test = number_set(*choice)\n test.start_game()\n\n user_operations = test.user_input()\n user_operations = test.split(user_operations)\n test.operators(user_operations)\n\n result = test.calculate()\n test.check_answer(result)\n\n\n","repo_name":"ailjia/24-Game","sub_path":"pair-programming.py","file_name":"pair-programming.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"11172478056","text":"import sys\n\ninput = sys.stdin.readline\n\ndef translate_letter_2_index(letter):\n return ord(letter) - ord(\"A\")\n\ndef dfs(depth, x, y):\n global result\n\n if depth > result:\n result = depth\n\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n\n if (0<=nx
= n//2+1 and med == None:\n med = num\n\nprint(round(s/n), med, mode, max_n - min_n, sep='\\n')","repo_name":"kim-mg/algorithm","sub_path":"baekjoon/1 sort/statistics_2108.py","file_name":"statistics_2108.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"33296724813","text":"from http.server import HTTPServer, BaseHTTPRequestHandler\nimport os\n\nfrom huawei_lte_api.AuthorizedConnection import AuthorizedConnection\nfrom huawei_lte_api.Client import Client\n\n\nclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.end_headers()\n self.wfile.write(prometheusExporter().encode())\n\n\ndef prometheusExporter():\n # Auth to router\n connection = AuthorizedConnection('http://' + os.environ['ROUTER_USER'] + ':' + os.environ['ROUTER_PASS'] + '@' + os.environ['ROUTER_ADDRESS'] + '/')\n # Init Client\n client = Client(connection)\n\n # Common attributes\n device = 'deviceName=\"' + client.device.information().get('DeviceName') + \\\n '\",iccid=\"' + client.device.information().get('Iccid') + '\"'\n band = client.device.signal().get('band')\n deviceband = device\n if band is not None:\n deviceband = device + ',band=\"' + band + '\"'\n\n # Get signal attributes\n signal = {\n 'band': {'help': 'The signal band the LTE connection is using', 'type': 'gauge', 'device': device, 'value': band},\n 'rsrp': {'help': 'The average power received from a single Reference signal in dBm', 'type': 'gauge', 'device': deviceband, 'value': client.device.signal().get('rsrp')},\n 'rsrq': {'help': 'Indicates quality of the received signal in db', 'type': 'gauge', 'device': deviceband, 'value': client.device.signal().get('rsrq')},\n 'rssi': {'help': 'Represents the entire received power including the wanted power from the serving cell as well as all co-channel power and other sources of noise in dBm', 'type': 'gauge', 'device': deviceband, 'value': client.device.signal().get('rssi')},\n 'rscp': {'help': 'Denotes the power measured by a receiver on a particular physical communication channel in dBm', 'type': 'gauge', 'device': deviceband, 'value': client.device.signal().get('rscp')},\n 'sinr': {'help': 'The signal-to-noise ratio of the given signal in dB', 'type': 'gauge', 'device': deviceband, 'value': client.device.signal().get('sinr')},\n 'ecio': {'help': 'The EC/IO is a measure of the quality/cleanliness of the signal from the tower to the modem and indicates the signal-to noise ratio in dB', 'type': 'gauge', 'device': deviceband, 'value': client.device.signal().get('ecio')}\n }\n\n # Format for metric\n for attribute, info in signal.items():\n if info['value'] is not None:\n info['value'] = info['value'].replace(\"dBm\", \"\")\n info['value'] = info['value'].replace(\"dB\", \"\")\n info['value'] = info['value'].replace(\">=\", \"\")\n\n # Format data for prometheus\n response = []\n for attribute, info in signal.items():\n if attribute is not None and info['value'] is not None:\n response.append('#HELP ' + attribute + ' ' + info['help'])\n response.append('#TYPE ' + attribute + ' ' + info['type'])\n response.append(\n attribute + '{' + info['device'] + '} ' + info['value'])\n\n return '\\n'.join(response)\n\n\nhttpd = HTTPServer(('', os.environ['HTTP_PORT']), SimpleHTTPRequestHandler)\nhttpd.serve_forever()\n","repo_name":"Lomany/lte-signal-exporter","sub_path":"lte-signal-exporter.py","file_name":"lte-signal-exporter.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23134136152","text":"fhand = open(\"headpp.ply\")\nfout = open(\"headp_no_normal.ply\", \"w\")\nheader_ended = False\nfor line in fhand:\n if not header_ended:\n fout.write(line)\n else:\n fout.write(\" \".join(line.split()[:3]))\n fout.write(\"\\n\")\n if \"end_header\" in line:\n header_ended = True\nfout.close()\n","repo_name":"JingkangZhang/PersonalWebsite","sub_path":"ply_remove_normal.py","file_name":"ply_remove_normal.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"43858759645","text":"# Middle Node\n# Bruce Englert, Meghana Gupta, Ray Grant\nimport random\nimport time\n\nimport Functions\nimport Modified_SSL_Handshake\nimport MySQLdb\n\n\n# DIP - Delayed Intermediate Protocol\n\nprivate_key = Functions.generate_private_key()\nONLINE_PORT = 5432\nOFFLINE_PORT = 5433\nonline_shared_key = b''\noffline_shared_key = b''\n\nonline_n = random.randint(100, 200)\noffline_n = random.randint(100, 200)\n\nnext_time = 0\n\n\ndef perform_online_handshake(online_node_socket):\n global online_shared_key\n [successful_handshake, computed_shared_key] = Modified_SSL_Handshake.server_ssl_handshake(online_node_socket,\n \"Middle Node\",\n private_key)\n online_shared_key = computed_shared_key\n return successful_handshake\n\n\ndef perform_offline_handshake(online_node_socket):\n global offline_shared_key\n [successful_handshake, shared_k] = Modified_SSL_Handshake.client_ssl_handshake(online_node_socket, \"Middle Node\",\n private_key)\n offline_shared_key = shared_k\n return successful_handshake\n\n\ndef send_n(node_socket):\n global online_n\n online_n = random.randint(100, 200)\n print(\"[Middle Node] Sending authorization n.\", online_n)\n [iv, encrypted_n] = Functions.aes_encrypt(online_shared_key, bytes([online_n]))\n n_msg = {\"n\": {\"iv\": iv, \"encrypted_n\": encrypted_n}}\n node_socket.sendall(Functions.wrap_to_send(n_msg))\n\n\ndef send_next_time(node_socket):\n global next_time\n next_time = random.randint(5, 20)\n [iv, encrypted_time] = Functions.aes_encrypt(online_shared_key, bytes([next_time]))\n next_t_msg = {\"next_time\": {\"iv\": iv, \"encrypted_time\": encrypted_time}}\n print(\"[Middle Node] Sending next time\", next_time)\n node_socket.sendall(Functions.wrap_to_send(next_t_msg))\n\n\ndef receive_verify_online_n(node_socket):\n global online_n\n\n n_msg = Functions.read_message_with_delimiter(node_socket)\n decrypted_n_bytes = Functions.aes_decrypt(n_msg[\"n\"][\"iv\"], online_shared_key, n_msg[\"n\"][\"encrypted_n\"])\n decrypted_n = int.from_bytes(decrypted_n_bytes, byteorder='big')\n\n if decrypted_n == online_n-1:\n print(\"[Middle Node] n was received and verified\")\n else:\n print(\"[Middle Node] given n failed authorization test\", online_n)\n print(\"should be: \", decrypted_n)\n node_socket.close()\n\n\ndef sanitize_data(data_string):\n return MySQLdb.escape_string(data_string).decode()\n\n\ndef handle_DH_1_online_connection():\n global online_shared_key\n\n online_socket = Modified_SSL_Handshake.handle_node_connection(5432)\n perform_online_handshake(online_socket) # TODO check if returns true\n\n given_dh_value = Functions.read_message_with_delimiter(online_socket)\n\n # send encrypted n\n send_n(online_socket)\n send_next_time(online_socket)\n online_socket.close()\n return given_dh_value\n\n\ndef initiate_DH_offline_connection(node_1_public_dh):\n #TODO: perform ssl and get shared key\n offline_socket = Modified_SSL_Handshake.connect_to_node(5433)\n\n # send online DH\n offline_socket.sendall(Functions.wrap_to_send(node_1_public_dh))\n\n node_3_dh = Functions.read_message_with_delimiter(offline_socket)\n offline_socket.close()\n return node_3_dh\n\n\ndef handle_DH_2_online_connection(node_2_public_dh):\n print(\"opening online connection...\")\n online_socket = Modified_SSL_Handshake.handle_node_connection(5432)\n\n # receive n-1\n receive_verify_online_n(online_socket)\n\n # send offline DH\n online_socket.sendall(Functions.wrap_to_send(node_2_public_dh))\n print(\"[Middle Node] sent DH\")\n\n send_n(online_socket)\n time.sleep(2)\n send_next_time(online_socket)\n\n online_socket.close()\n\n\ndef transfer_data(data):\n offline_socket = Modified_SSL_Handshake.connect_to_node(5433)\n print(\"connected to offline node\")\n offline_socket.send(Functions.wrap_to_send(data))\n print(\"sent\")\n offline_socket.close()\n\n\ndef receive_transfer_data():\n online_socket = Modified_SSL_Handshake.handle_node_connection(5432)\n\n receive_verify_online_n(online_socket)\n data_to_transfer = Functions.read_message_with_delimiter(online_socket)\n\n send_n(online_socket)\n time.sleep(2)\n send_next_time(online_socket)\n print(\"[Middle Node] Received data\")\n online_socket.close()\n return data_to_transfer\n\n\ndef main():\n online_dh_value = handle_DH_1_online_connection()\n print(\"[Middle Node] Received online dh part\")\n offline_dh_value = initiate_DH_offline_connection(online_dh_value)\n print(\"[Middle Node] Received offline dh part\")\n time.sleep(next_time-2)\n handle_DH_2_online_connection(offline_dh_value)\n print(\"[Middle Node] Transferring data...\")\n\n # runs 10 times to simulate real world use\n for i in range(1, 10):\n print(\"sleeping...\", next_time)\n time.sleep(next_time - 2)\n print(\"sending data to transfer\")\n data_to_transfer = receive_transfer_data()\n print(\"transfering data...\")\n transfer_data(data_to_transfer)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"ray836/Final-Project-CS5490","sub_path":"Middle_Node.py","file_name":"Middle_Node.py","file_ext":"py","file_size_in_byte":5246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32571828928","text":"\n\n# write to a file\nwith open('fruit.txt', 'w') as f:\n f.write('apple\\nbanana\\ncherry\\n')\n# this will overwrite the file\n\n# append to a file without overwriting\nwith open('fruit.txt', 'a') as f:\n f.write('\\npear\\n')\n\n# read and write to a file\nwith open('fruit.txt', 'a+') as myfile:\n myfile.write('\\norange')\n myfile.seek(0)\n content = myfile.read()\n\nprint(content)\n\n\nwith open(\"vegetables.txt\", \"a\") as f:\n f.write(\"broccoli\\n\")\n# this will look for existing file, and create it if not exists\n","repo_name":"mayfiete/python_mega_course","sub_path":"writing_text_to_file.py","file_name":"writing_text_to_file.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23409323156","text":"import unittest\nfrom datetime import datetime\n\nfrom zope.component import queryMultiAdapter\nfrom zope.interface.verify import verifyObject\nfrom Products.Silva.testing import TestRequest, Transaction\n\nfrom silva.app.news.interfaces import INewsItem, IAgendaItem\nfrom silva.app.news.datetimeutils import local_timezone\nfrom silva.app.news.tests.SilvaNewsTestCase import SilvaNewsTestCase\nfrom silva.core.interfaces import IFeedEntry\n\nfrom dateutil.relativedelta import relativedelta\n\n\nclass TestFeeds(SilvaNewsTestCase):\n \"\"\" Test atom and rss feeds\n \"\"\"\n\n def setUp(self):\n with Transaction():\n super(TestFeeds, self).setUp()\n # Publication\n factory = self.root.manage_addProduct['silva.app.news']\n factory.manage_addNewsPublication('source', 'Publication')\n factory.manage_addNewsFilter('filter', 'Filter')\n factory.manage_addNewsViewer('viewer', 'Viewer')\n\n self.root.filter.set_show_agenda_items(True)\n self.root.filter.add_source(self.root.source)\n self.root.viewer.add_filter(self.root.filter)\n self.root.viewer.set_hide_expired_events(False)\n\n # Items\n self.add_published_news_item(\n self.root.source, 'raining', 'The rain is coming')\n self.add_published_news_item(\n self.root.source, 'cows', 'Cows are moving in town')\n start_event = datetime(2010, 10, 9, 8, 20, 00, tzinfo=local_timezone)\n end_event = start_event + relativedelta(hours=+2)\n self.add_published_agenda_item(\n self.root.source, 'war', 'This is War', start_event, end_event)\n\n def test_feeds_agenda_item(self):\n entry = queryMultiAdapter(\n (self.root.source.war, TestRequest()),\n IFeedEntry)\n self.assertTrue(verifyObject(IAgendaItem, self.root.source.war))\n self.assertTrue(verifyObject(IFeedEntry, entry))\n self.assertEqual(entry.id(), 'http://localhost/root/source/war')\n self.assertEqual(entry.title(), 'This is War')\n self.assertEqual(entry.url(), 'http://localhost/root/source/war')\n self.assertEqual(entry.authors(), ['manager'])\n self.assertEqual(entry.description(), '')\n self.assertEqual(entry.keywords(), [])\n self.assertEqual(entry.html_description(), \"\")\n self.assertEqual(entry.location(), '')\n self.assertEqual(entry.start_datetime(), '2010-10-09T08:20:00+02:00')\n self.assertEqual(entry.end_datetime(), '2010-10-09T10:20:00+02:00')\n\n def test_feeds_news_item(self):\n entry = queryMultiAdapter(\n (self.root.source.cows, TestRequest()),\n IFeedEntry)\n self.assertTrue(verifyObject(INewsItem, self.root.source.cows))\n self.assertTrue(verifyObject(IFeedEntry, entry))\n self.assertEqual(entry.id(), 'http://localhost/root/source/cows')\n self.assertEqual(entry.title(), 'Cows are moving in town')\n self.assertEqual(entry.url(), 'http://localhost/root/source/cows')\n self.assertEqual(entry.authors(), ['manager'])\n self.assertEqual(entry.description(), '')\n self.assertEqual(entry.keywords(), [])\n self.assertEqual(entry.html_description(), \"\")\n\n def test_functional_rss_feed_from_viewer(self):\n \"\"\"Test that you can get a rss feeds from a news viewer.\n \"\"\"\n with self.layer.get_browser() as browser:\n self.assertEqual(\n browser.open('http://localhost/root/viewer/rss.xml'),\n 200)\n self.assertEqual(\n browser.content_type,\n 'text/xml;charset=UTF-8')\n\n items = browser.xml.xpath(\n '//rss:item', namespaces={'rss': \"http://purl.org/rss/1.0/\"})\n # We have two news items, and one agenda item.\n self.assertEquals(3, len(items))\n\n def test_functional_atom_feed_from_viewer(self):\n \"\"\"Test that you can get an atom from a news viewer.\n \"\"\"\n with self.layer.get_browser() as browser:\n self.assertEqual(\n browser.open('http://localhost/root/viewer/atom.xml'),\n 200)\n self.assertEqual(\n browser.content_type,\n 'text/xml;charset=UTF-8')\n\n items = browser.xml.xpath(\n '//atom:entry', namespaces={'atom': \"http://www.w3.org/2005/Atom\"})\n # We have two news items, and one agenda item.\n self.assertEquals(3, len(items))\n\n def test_functional_rss_feed_from_publication(self):\n \"\"\"Test that you can get a rss feeds from a default news publication.\n \"\"\"\n with self.layer.get_browser() as browser:\n # Feeds are disabled by default (container settings)\n self.assertEqual(\n browser.open('http://localhost/root/source/rss.xml'),\n 404)\n # If you enable them when they should work\n self.root.source.set_allow_feeds(True)\n self.assertEqual(\n browser.open('http://localhost/root/source/rss.xml'),\n 200)\n self.assertEqual(\n browser.content_type,\n 'text/xml;charset=UTF-8')\n\n items = browser.xml.xpath(\n '//rss:item', namespaces={'rss': \"http://purl.org/rss/1.0/\"})\n # We only have two items, since the feed is only enabled\n # for news and not agenda items\n self.assertEquals(2, len(items))\n\n def test_functional_atom_feed_from_publication(self):\n \"\"\"Test that you can get an atom from a default news publication.\n \"\"\"\n with self.layer.get_browser() as browser:\n self.assertEqual(\n browser.open('http://localhost/root/source/atom.xml'),\n 404)\n # If you enable them when they should work\n self.root.source.set_allow_feeds(True)\n self.assertEqual(\n browser.open('http://localhost/root/source/atom.xml'),\n 200)\n self.assertEqual(\n browser.content_type,\n 'text/xml;charset=UTF-8')\n\n items = browser.xml.xpath(\n '//atom:entry', namespaces={'atom': \"http://www.w3.org/2005/Atom\"})\n # We only have two items, since the feed is only enabled\n # for news and not agenda items\n self.assertEquals(2, len(items))\n\n\ndef test_suite():\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestFeeds))\n return suite\n","repo_name":"silvacms/silva.app.news","sub_path":"src/silva/app/news/tests/test_feeds.py","file_name":"test_feeds.py","file_ext":"py","file_size_in_byte":6608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"33305725557","text":"graph_or_tree = {\r\n\"A\" :[\"B\",\"C\"],\r\n\"B\" :[\"D\",\"E\"],\r\n\"C\" :[\"B\",\"F\"],\r\n\"D\": [],\r\n\"E\" : [\"F\"],\r\n\"F\" :[],\r\n\"G\" :[\"B\",\"A\",\"L\",\"A\",\"J\",\"I\"]\r\n}\r\nprint(graph_or_tree[\"G\"])\r\nvisited_path=[]\r\nparent ={}\r\ndfs_path=[]\r\nfor node in graph_or_tree.keys() :\r\n parent[node] =None\r\ndef DFS(node):\r\n visited_path.append(node)\r\n dfs_path.append(node)\r\n\r\n for i in graph_or_tree[node]:\r\n if i not in visited_path:\r\n parent[i] = node\r\n DFS(i)\r\n \r\nDFS(\"A\")\r\nprint(\"The graph = \",graph_or_tree)\r\nprint(\"=============Depth First Search Algorithm===========\")\r\nprint(\"traversal path of depth first search =\\t\",*dfs_path,sep = \" -> \")\r\n\r\n\r\n","repo_name":"thebrokencoder-code/python-dfs","sub_path":"dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"45752086553","text":"import os\nimport shutil\nimport datetime\nimport msvcrt\nimport psutil\nimport locale\nimport pyperclip\nfrom tqdm import tqdm\n\nlocale.setlocale(locale.LC_TIME, 'pt_BR.UTF-8')\n\ndef copy_files(source, destination):\n total_files = 0\n total_size = 0\n\n # Percorre todos os arquivos e diretórios de origem\n for item in source:\n if os.path.isfile(item):\n total_files += 1\n total_size += os.path.getsize(item)\n elif os.path.isdir(item):\n for root, _, filenames in os.walk(item):\n for filename in filenames:\n file_path = os.path.join(root, filename)\n total_files += 1\n total_size += os.path.getsize(file_path)\n\n print(f\"Total de arquivos a copiar: {total_files}\")\n print(f\"Tamanho total: {total_size} bytes\")\n print(\"Copiando arquivos:\")\n\n # Copia os arquivos e diretórios de origem para o destino\n with tqdm(total=total_size, unit='B', unit_scale=True, ncols=80) as progress_bar:\n for item in source:\n if os.path.isfile(item):\n shutil.copy(item, destination)\n progress_bar.update(os.path.getsize(item))\n elif os.path.isdir(item):\n for root, _, filenames in os.walk(item):\n for filename in filenames:\n file_path = os.path.join(root, filename)\n shutil.copy(file_path, destination)\n progress_bar.update(os.path.getsize(file_path))\n\n print(\"Copying files: Done\")\n print(\"\")\n\ndef rename_files(folder_path):\n files = os.listdir(folder_path)\n for file in files:\n if file.endswith(\".LRV\"):\n new_name = os.path.splitext(file)[0] + \".MP4\"\n os.rename(os.path.join(folder_path, file), os.path.join(folder_path, new_name))\n\ndef create_folder_structure(date, guide_name, tour_name, base_path):\n year_folder = os.path.join(base_path, date.strftime(\"%Y\"))\n month_number = date.strftime('%m')\n month_name = date.strftime('%B').upper()\n folder_name = f\"{date.day} DE {month_name} {date.year} - {tour_name.upper()} - {guide_name.upper()}\"\n folder_path = os.path.join(year_folder, f\"{month_number}. {month_name}\", folder_name)\n os.makedirs(folder_path, exist_ok=True)\n footage_path = os.path.join(folder_path, \"Footage\")\n proxy_path = os.path.join(folder_path, \"Proxy Media\")\n os.makedirs(footage_path, exist_ok=True)\n os.makedirs(proxy_path, exist_ok=True)\n return folder_path, footage_path, proxy_path\n\ndef write_message_file(date, tour_name, folder_path):\n formatted_date = date.strftime(\"%d de %B de %Y\").lstrip(\"0\").upper()\n message = f\"*Litoral Vídeos* 📹🏖☀😎\\n\\nOlá!\\n\\nSegue, o link do YouTube com a filmagem do seu passeio de *{tour_name}* do dia *{formatted_date}*:\\n\\n[LINK DO VÍDEO]\\n\\nAqui também vai um link com as imagens aéreas do Ceará que separamos para vocês:\\n\\nhttps://youtu.be/4C7cDVfsGf4\\n\\nObrigado pela sua visita e aproveite a filmagem!\\n\\nQualquer dúvida estamos à disposição.\"\n file_path = os.path.join(folder_path, \"message.txt\")\n with open(file_path, \"w\", encoding='utf-8') as file:\n file.write(message)\n\ndef format_participants_text(pasted_text):\n \n participants = []\n lines = pasted_text.split(\"[\")\n for line in lines:\n if line.strip():\n name = line.split(\":\")[-1].strip()\n participants.append(name.title())\n return participants\n\ndef write_participants_file(participants, folder_path):\n file_path = os.path.join(folder_path, \"participants.txt\")\n with open(file_path, \"w\") as file:\n for participant in participants:\n file.write(participant + \"\\n\")\n\ndef get_sd_card_path():\n drives = psutil.disk_partitions(all=True)\n for drive in drives:\n if drive.fstype.lower() == 'fat32' or drive.fstype.lower() == 'fat':\n return drive.mountpoint\n raise ValueError(\"Nenhum cartão SD detectado\")\n\ndef get_files_to_copy(sd_card_path):\n files_to_copy = []\n for root, _, filenames in os.walk(sd_card_path):\n for filename in filenames:\n file_path = os.path.join(root, filename)\n files_to_copy.append(file_path)\n return files_to_copy\n\ndef get_user_input():\n print(\"De que dia é a filmagem?\")\n print(\"\")\n\n print(\"1) Hoje\")\n print(\"2) Ontem\")\n print(\"3) Especificar data (Formato: DD/MM/AAAA)\")\n print(\"\")\n\n option = int(input(\"Opção: \"))\n if option == 1:\n date = datetime.date.today()\n elif option == 2:\n date = datetime.date.today() - datetime.timedelta(days=1)\n elif option == 3:\n print(\"\")\n date_str = input(\"Digite a data (DD/MM/AAAA): \")\n date = datetime.datetime.strptime(date_str, \"%d/%m/%Y\").date()\n else:\n raise ValueError(\"Opção inválida\")\n os.system(\"cls\")\n\n guide_name = input(\"Nome do guia? \")\n os.system(\"cls\")\n\n print(\"Qual passeio?\")\n print(\"\")\n\n print(\"1) Morro Branco\")\n print(\"2) Lagoinha\")\n print(\"3) Canoa Quebrada\")\n print(\"4) Outro\")\n print(\"\")\n\n tour_option = int(input(\"Opção: \"))\n if tour_option == 1:\n tour_name = \"Morro Branco\"\n elif tour_option == 2:\n tour_name = \"Lagoinha\"\n elif tour_option == 3:\n tour_name = \"Canoa Quebrada\"\n elif tour_option == 4:\n tour_name = input(\"Digite o nome do passeio: \")\n else:\n raise ValueError(\"Opção inválida\")\n os.system(\"cls\")\n\n print(\"Cole o texto com os participantes e pressione Enter quando terminar:\")\n participants_text = \"\"\n while True:\n line = input()\n if line.lower() == \"sair\" or line == \"\":\n break\n participants_text += line + \"\\n\"\n\n participants = format_participants_text(participants_text)\n\n formatted_date = date.strftime(\"%d de %B de %Y\").lstrip(\"0\").upper()\n tour_name = tour_name.upper()\n guide_name = guide_name.upper()\n\n clipboard_text = f\"{formatted_date} - {tour_name} - {guide_name}\"\n pyperclip.copy(clipboard_text)\n\n return date, guide_name, tour_name, participants\n\ndef wait_for_keypress():\n print(\"\\nProcesso finalizado com sucesso. Aperte qualquer tecla para encerrar...\")\n msvcrt.getch()\n\ntry:\n # Get SD card path\n sd_card_path = get_sd_card_path()\n print(f\"Cartão SD detectado em: {sd_card_path}\")\n print(\"\")\n\n # Get user input\n date, guide_name, tour_name, participants = get_user_input()\n\n # Copy files from SD card\n files_to_copy = get_files_to_copy(sd_card_path)\n destination_folder = f\"bkp-{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}\"\n destination_path = os.path.join(\"D:\\\\\", destination_folder)\n os.makedirs(destination_path, exist_ok=True)\n print(\"INICIANDO BACKUP DO CARTÃO:\")\n print(\"\")\n\n copy_files(files_to_copy, destination_path)\n\n # Create folder structure\n base_path = r\"D:\\ARQUIVO\"\n folder_path, footage_path, proxy_path = create_folder_structure(date, guide_name, tour_name, base_path)\n\n # Copy files\n print(\"INICIANDO CÓPIA DOS ARQUIVOS BRUTO:\")\n print(\"\")\n\n copy_files([os.path.join(destination_path, file) for file in files_to_copy if file.endswith(\".MP4\")], footage_path)\n\n print(\"INICIANDO CÓPIA DOS ARQUIVOS DE MÍDIAS PROXY:\")\n print(\"\")\n copy_files([os.path.join(destination_path, file) for file in files_to_copy if file.endswith(\".LRV\")], proxy_path)\n\n # Rename files in Proxy Media folder\n rename_files(proxy_path)\n\n # Write message file\n write_message_file(date, tour_name, folder_path)\n\n # Write participants file\n write_participants_file(participants, folder_path)\n\n # Wait for keypress to exit\n wait_for_keypress()\n\n os.startfile(folder_path)\n\nexcept ValueError as e:\n print(f\"Erro: {str(e)}\")\nexcept Exception as e:\n print(f\"Ocorreu um erro durante a execução do script: {str(e)}\")\n wait_for_keypress()\n","repo_name":"EriJohnson/litoral_videos_backup_sd_card","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72543534593","text":"from conans import ConanFile, CMake, tools\nimport sys, os\n\ndef option_on_off(option):\n return \"ON\" if option else \"OFF\"\n\nclass LMDBConan(ConanFile):\n name = \"lmdb\"\n version = \"0.9.24\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n url = \"https://github.com/k-nuth/conan-lmdb\"\n license = \"OpenLDAP Public License\"\n\n generators = \"cmake\"\n\n options = {\"shared\": [True, False],\n \"fPIC\": [True, False],\n \"verbose\": [True, False],\n }\n\n default_options = \"shared=False\", \\\n \"fPIC=True\", \\\n \"verbose=False\"\n\n # exports = \"conanfile.py\", \"mdb.def\", \"win32/*\", \"LICENSE.md\" # \"CMakeLists.txt\",\n exports_sources = [\"CMakeLists.txt\"]\n build_policy = \"missing\"\n\n @property\n def msvc_mt_build(self):\n return \"MT\" in str(self.settings.get_safe(\"compiler.runtime\"))\n\n @property\n def fPIC_enabled(self):\n if self.settings.compiler == \"Visual Studio\":\n return False\n else:\n return self.options.fPIC\n\n @property\n def is_shared(self):\n if self.options.shared and self.msvc_mt_build:\n return False\n else:\n return self.options.shared\n\n\n def config_options(self):\n if self.settings.compiler == \"Visual Studio\":\n self.options.remove(\"fPIC\")\n if self.options.shared and self.msvc_mt_build:\n self.options.remove(\"shared\")\n\n def configure(self):\n del self.settings.compiler.libcxx #Pure-C \n\n def package_id(self):\n self.info.options.verbose = \"ANY\"\n\n def source(self):\n # extension = \"zip\" if sys.platform == \"win32\" else \"tar.gz\" % self.folder_name\n extension = \"zip\" if sys.platform == \"win32\" else \"tar.gz\" #% self.build_folder\n \n base_name = \"LMDB_%s\" % (self.version)\n zip_name = \"%s.%s\" % (base_name, extension)\n url = \"https://github.com/LMDB/lmdb/archive/%s\" % (zip_name)\n self.output.info(\"Downloading %s...\" % url)\n tools.download(url, zip_name)\n tools.unzip(zip_name, \".\")\n os.unlink(zip_name)\n os.rename(\"lmdb-%s\" % base_name, \"lmdb\")\n\n def build(self):\n # cmake = CMake(self.settings)\n # shared = \"-DBUILD_SHARED_LIBS=1\" if self.options.shared else \"\"\n # self.run('cmake %s %s %s' % (self.conanfile_directory, cmake.command_line, shared))\n # self.run(\"cmake --build . %s\" % cmake.build_config)\n\n cmake = CMake(self)\n cmake.verbose = self.options.verbose\n\n cmake.definitions[\"ENABLE_SHARED\"] = option_on_off(self.is_shared)\n cmake.definitions[\"ENABLE_POSITION_INDEPENDENT_CODE\"] = option_on_off(self.fPIC_enabled)\n\n\n cmake.configure(source_dir=self.source_folder)\n cmake.build()\n\n def package(self):\n self.copy(\"lmdb.h\", dst=\"include\", src=\"lmdb/libraries/liblmdb\")\n self.copy(\"*.lib\", dst=\"lib\", src=\"lib\", keep_path=True)\n self.copy(\"*.a\", dst=\"lib\", src=\"lib\", keep_path=True)\n self.copy(\"*.pdb\", dst=\"lib\", src=\"lib\", keep_path=True)\n self.copy(\"*.dll\", dst=\"bin\", src=\"lib\", keep_path=True)\n self.copy(\"*.so\", dst=\"bin\", src=\"lib\", keep_path=True)\n self.copy(\"*.exe\", dst=\"bin\", src=\"bin\", keep_path=True)\n\n def package_info(self):\n if self.settings.build_type == \"Debug\":\n self.cpp_info.libs = [\"lmdbd\"]\n else:\n self.cpp_info.libs = [\"lmdb\"]\n \n if self.settings.os == \"Windows\":\n self.cpp_info.libs.append(\"ntdll\")\n else:\n self.cpp_info.libs.append(\"pthread\")\n","repo_name":"k-nuth/conan-lmdb","sub_path":"conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"26025461074","text":"from quafing.multipdf import multipdf_init\nfrom quafing.multipdf.multipdf_collection import MultiPdfCollection\n\ndef create_multi_pdf(mdpdfType, data,colmetadata,calculate=True,*args,**kwargs):\n\t\"\"\"\n\tcreate a multipdf object from data and (column)metadata\n\n\t:param mdpdfType: str; Type of multidimensional pdf to create. See quafing.multipdf.__init__() for valid types\n\t:param data: pandas DataFrame; (columnar) data from whhih to create multipdf. \n\t:param colmetadta: array of dictionaries; metadata for each column\n\t:param calculate: bool; keyword to trigger calculation of (component) pdfs for created multipdf object. default True\n\t:param args: optional; arguments to be passed to multi_pdf class calculate_pdf() function\n\t:param kwargs: optional; keyword arguments to be passed to multi_pdf class calculate_pdf() function\n\t:return mdpdf: MultiDimensionalPdf object of specified type \n\t\"\"\"\n\tmdpdf = multipdf_init(mdpdfType)\n\tmdpdf._import_data(data,colmetadata)\n\tmdpdf._basic_validation()\n\tif calculate:\n\t mdpdf.calculate_pdf(*args,**kwargs) \n\treturn mdpdf\n\n\ndef create_mdpdf_collection(mdpdfType, group_data, group_labels,colmetadata, calculate=True, validate_metadata=False, *args, **kwargs):\n \"\"\"\n Create a multi-dimesional pdf ccolletion object from groups of data.\n\n :param mdpdfType: str; Type of multidimensional pdfs to create. See quafing.multipdf.__init__() for valid types\n :param group_data: list of pandas DDataFrames with the data for grouos of respondents\n :param group_labels: list of labels associated with the groups\n :param colmetadata: column metadata of the data/questions of ech group\n :param calculate: bool (default True). If True calculate denssity estimates for all groups\n :param validate_metaata: bool (default False). If true peform extended validation of metadata conformity between groups\n :param args: optional positional arguments to pass to create_multi_pdf() method \n :param kwargs: optional keyword arguments to pass to create_multi_pdf() method\n :return mpdf_collection: collection of multi-dimensional pdfs (type MultiPdfCollection)\n \n \"\"\"\n mdpdfs = []\n for i, data in enumerate(group_data):\n mdpdf = create_multi_pdf(mdpdfType,data, colmetadata, calculate=calculate, *args, **kwargs)\n mdpdfs.append(mdpdf)\n mdpdf_collection = MultiPdfCollection(mdpdfs,group_labels, colmetadata, mdpdfType, validate_metadata=validate_metadata)\n return mdpdf_collection","repo_name":"SDCCA/quafing","sub_path":"quafing/multipdf/multipdf.py","file_name":"multipdf.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"11513214976","text":"#Ler o nome, idade e sexo de 4 pessoas e mostrar no final, a média das idades, o nome do homem mais\r\n#velho e quantas mulheres tem menos de 20 anos\r\n\r\nsomaidades = 0;\r\nconthomem = 0;\r\nmaisvelho = 0;\r\ncontmulhermenoridade = 0;\r\ncontpessoas = 0;\r\n\r\nfor c in range(0, 4):\r\n nome = str(input(f\"Digite o nome da {c+1} pessoa: \")).upper().strip();\r\n idade = int(input(\"Digite a idade dessa pessoa: \"));\r\n sexo = str(input(\"Digite M se a pessoa for mulher e H se for homem: \")).upper();\r\n somaidades = somaidades + idade;\r\n contpessoas = contpessoas + 1;\r\n\r\n if sexo == \"H\": #DESCOBRINDO HOMEM MAIS VELHO\r\n conthomem = conthomem + 1;\r\n if conthomem == 1:\r\n nome_domaisvelho = nome;\r\n maisvelho = idade;\r\n else:\r\n if maisvelho < idade:\r\n maisvelho = idade;\r\n nome_domaisvelho = nome;\r\n\r\n if sexo == \"M\": #DESCOBRINDO QUANTIDADES DE MULHERES COM MENOS DE 20\r\n if idade < 20:\r\n contmulhermenoridade = contmulhermenoridade + 1;\r\n\r\nmedia = somaidades / (contpessoas);\r\n\r\nprint(f\"A média das {contpessoas} idades é {media}.\");\r\nprint(f\"O nome do homem mais velho é: {nome_domaisvelho}.\");\r\nprint(f\"E houveram {contmulhermenoridade} mulheres abaixo de 20 anos.\");\r\n\r\n\r\n\r\n\r\n","repo_name":"GabriellyBailon/Cursos","sub_path":"CursoEmVideo/Python/Mundo 2/ex056.py","file_name":"ex056.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7908819478","text":"import pandas as pd\nimport numpy as np\nimport cv2\nfrom context import RAWDATADIR\nfrom helpers import read_before_and_after\n\ndef add_lags(\n df, \n n_lags=3,\n lag_cols = [\n 'Altitude', \n 'Delta', \n 'east_median',\n 'north_median',\n 'east_median_sift', \n 'north_median_sift', \n 'n_matches', \n 'n_matches_sift'\n ]):\n\n Xy = df.copy()\n\n for i in range(1, n_lags + 1):\n lag_feats = df.groupby('sequence')[lag_cols].shift(i)\n leap_feats = df.groupby('sequence')[lag_cols].shift(-i)\n diff_feats = df.groupby('sequence')[lag_cols].diff(i)\n leap_diff_feats = df.groupby('sequence')[lag_cols].diff(-i)\n\n Xy = Xy.join(lag_feats, rsuffix=f'_lag_{i}')\n Xy = Xy.join(leap_feats, rsuffix=f'_leap_{i}')\n \n Xy = Xy.join(diff_feats, rsuffix=f'_diff_{i}')\n Xy = Xy.join(leap_diff_feats, rsuffix=f'_leap_diff_{i}')\n\n return Xy.fillna(0.0)\n\nclass ImageFeatureExtractor:\n def __init__(self, train_dir=RAWDATADIR / 'train/train', test_dir=RAWDATADIR / 'test/test') -> None:\n self.train_dir = train_dir\n self.test_dir = test_dir\n\n self.clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))\n\n self.shitomasi_params = dict(\n maxCorners = 100,\n qualityLevel = 0.3,\n minDistance = 7,\n blockSize = 7 )\n\n self.lk_params = dict(\n winSize = (15,15),\n maxLevel = 2,\n criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)\n )\n\n self.sift = cv2.SIFT_create()\n\n def _apply_clahe_multichannel(self, img):\n \"\"\"Expects [h, w, c]\"\"\"\n processed = []\n for c_index in range(img.shape[-1]):\n processed.append(self.clahe.apply(img[:, :, c_index]))\n \n return np.dstack(processed)\n\n def _get_lk_features(self, img1, img2, apply_clahe=True):\n gray1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n gray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n\n if apply_clahe:\n gray1, gray2 = self.clahe.apply(gray1), self.clahe.apply(gray2)\n \n p0 = cv2.goodFeaturesToTrack(gray1, mask = None, **self.shitomasi_params)\n\n if p0 is None:\n return None\n\n # calculate optical flow\n p1, st, err = cv2.calcOpticalFlowPyrLK(gray1, gray2, p0, None, **self.lk_params)\n\n # Select good points\n good_new = p1[st==1]\n good_old = p0[st==1]\n\n if np.sum(st) == 0:\n return None\n\n diffs = []\n centroids = []\n for _, (new, old) in enumerate(zip(good_new, good_old)):\n point1 = old.ravel()\n point2 = new.ravel()\n\n diff = point2 - point1\n\n # Flip for North/East axis alignment with X, Y on image\n diff[0] = - diff[0]\n diffs.append(point2 - point1)\n \n centroid = (point1 + point2) / 2\n centroids.append(centroid)\n\n mean, median, std = np.mean(diffs, axis=0), np.median(diffs, axis=0), np.std(diffs, axis=0)\n c_mean = np.mean(centroids, axis=0)\n \n feats = {\n 'east_mean': mean[0], 'east_median': median[0], 'east_std': std[0],\n 'north_mean': mean[1], 'north_median': median[1], 'north_std': std[1],\n 'centroid_east': 60 - c_mean[0], 'centroid_north': 60 - c_mean[1], 'n_matches': np.sum(st),\n }\n\n return pd.Series(feats)\n\n def _get_sift_features(self, img1, img2):\n \n img1, img2 = self._apply_clahe_multichannel(img1), self._apply_clahe_multichannel(img2)\n \n # find the keypoints and descriptors with SIFT\n kp1, des1 = self.sift.detectAndCompute(img1, None)\n kp2, des2 = self.sift.detectAndCompute(img2, None)\n \n # Check keypoint detection\n if len(kp1) <=1 or len(kp2) <= 1:\n return None\n\n # FLANN parameters\n FLANN_INDEX_KDTREE = 1\n index_params = dict(algorithm = FLANN_INDEX_KDTREE, trees = 5)\n search_params = dict(checks=50) # or pass empty dictionary\n\n flann = cv2.FlannBasedMatcher(index_params, search_params)\n matches = flann.knnMatch(des1,des2,k=2)\n \n # Need to draw only good matches, so create a mask\n matchesMask = [[0,0] for i in range(len(matches))]\n\n # ratio test as per Lowe's paper\n for i, (m,n) in enumerate(matches):\n if m.distance < 0.7 * n.distance:\n matchesMask[i]=[1,0]\n \n # Check match number\n masked_matches = np.asarray(matches)[np.asanyarray(matchesMask) == 1]\n if len(masked_matches) == 0:\n return None\n \n diffs = []\n centroids = []\n pts1 = []\n pts2 = []\n \n for i, m in enumerate(masked_matches):\n point2 = np.asarray(kp2[m.trainIdx].pt)\n point1 = np.asarray(kp1[m.queryIdx].pt)\n \n diff = point2 - point1\n pts1.append(point1)\n pts2.append(point2)\n\n # Flip for North/East axis alignment with X, Y on image\n diff[0] = - diff[0]\n diffs.append(point2 - point1)\n \n centroid = (point1 + point2) / 2\n centroids.append(centroid)\n\n mean, median, std = np.mean(diffs, axis=0), np.median(diffs, axis=0), np.std(diffs, axis=0)\n c_mean = np.mean(centroids, axis=0)\n\n feats = {\n 'east_mean_sift': mean[0], 'east_median_sift': median[0], 'east_std_sift': std[0],\n 'north_mean_sift': mean[1], 'north_median_sift': median[1], 'north_std_sift': std[1],\n 'centroid_east_sift': 60 - c_mean[0], 'centroid_north_sift': 60 - c_mean[1],\n 'n_matches_sift': len(masked_matches), \n }\n\n return pd.Series(feats)\n\n def get_features_from_row(self, row):\n base_dir = self.test_dir if pd.isna(row['North']) else self.train_dir\n \n img1, img2 = read_before_and_after(str(base_dir / row.name))\n\n sift_features = self._get_sift_features(img1, img2)\n lk_features = self._get_lk_features(img1, img2)\n\n if (sift_features is None) and (lk_features is None):\n return None\n else:\n return pd.concat([lk_features, sift_features])\n","repo_name":"guischmitd/kddbr-2022","sub_path":"kddbr/feature_extraction.py","file_name":"feature_extraction.py","file_ext":"py","file_size_in_byte":6348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"20550719334","text":"# 16*. Напишите программу,\n# которая вычисляет процентное содержание символов G (гуанин) и C (цитозин)\n# в введенной строке (программа не должна зависеть от регистра вводимых символов).\n# Например, в строке \"acggtgttat\" процентное содержание символов G и C равно 4/10 ⋅ 100 = 40.0\n# где 4 - это количество символов G и C, а 10 -- это длина строки.\nstring = input(\"Введите символы \")\nspis2 = []\nspis = [i for i in string]\nfor i in spis:\n if i == 'g' or i == 'G' or i == 'c' or i == 'C':\n spis2.append(i)\nprint(f\"Содержание гуанина и цитозина составялет {len(spis2) / len(spis) * 100} %\")","repo_name":"Janyasvetlovskiy/Evgeniy_Svetlovskiy_Homeworks1","sub_path":"sr1/task_16.py","file_name":"task_16.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70924262915","text":"# Stwórz dwie zmienne s1 i s2 przechowujące dowolne wyrazy, utwórz nowy łańcuch s3, dołączając s2 w środku s1.\n\ns1 = \"maslo\"\ns2 = \"maslane\"\n\nsrodek = int(len(s1)/2\n )\ns1_1 = s1[0:srodek]\ns1_2 = s1[srodek:len(s1)]\ns3 = s1_1 + s2 + s1_2\nprint(s3\n )\n# Utwórz skrypt, który zapyta użytkownika o tytuł książki, nazwisko autora, liczbę stron, a następnie:\ntytul = input(str(('Podaj tytuł ksiązki')\n ))\n\nstrony = input('podaj liczbę stron'\n )\nnazwisko = input(str('podaj nazwisko autora')\n )\ny = int(strony.isalpha()\n )\ntytul_1 = tytul.replace(\" \", \"\"\n )\nx = tytul_1.isalpha(\n)\ntytul_t = tytul.title(\n)\nnazwisko_t = nazwisko.title(\n)\ncalosc = tytul + strony + nazwisko\n\nprint(x, y\n )\nprint(tytul_t, nazwisko_t\n )\nprint(tytul_t, nazwisko_t, strony\n )\nprint(len(calosc)\n )\n\n\n\n\n","repo_name":"Jarwes00/KursPython2022","sub_path":"Homework/Ex_klasy_string.py","file_name":"Ex_klasy_string.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11604685863","text":"# 给定一个 n × n 的二维矩阵表示一个图像。\n#\n# 将图像顺时针旋转 90 度。\n#\n# 说明:\n#\n# 你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。\n#\n# 来源:力扣(LeetCode)\n# 链接:https://leetcode-cn.com/problems/rotate-image\n# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\nfrom typing import List\n\n\nclass Solution:\n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n if not matrix:\n return\n\n width = len(matrix[0])\n height = len(matrix)\n\n for h in range(height):\n for w in range(h, width):\n matrix[h][w], matrix[w][h] = matrix[w][h], matrix[h][w]\n\n for h in range(height):\n matrix[h].reverse()\n\n\ndef main():\n matrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n answer = [\n [7, 4, 1],\n [8, 5, 2],\n [9, 6, 3]\n ]\n\n # matrix[0][0] = matrix[2][0]\n # matrix[0][1] = matrix[1][0]\n # matrix[0][2] = matrix[0][0]\n #\n # matrix[1][0] = matrix[2][1]\n # matrix[1][1] = matrix[1][1]\n # matrix[1][2] = matrix[0][1]\n #\n # matrix[2][0] = matrix[2][2]\n # matrix[2][1] = matrix[1][2]\n # matrix[2][2] = matrix[0][2]\n\n matrix = [\n [1, 2, 3, 4],\n [5, 6, 7, 8],\n [9, 10, 11, 12],\n [13, 14, 15, 16]\n ]\n answer = [\n [13, 9, 5, 1],\n [14, 10, 6, 2],\n [15, 11, 7, 3],\n [16, 12, 8, 4]\n ]\n\n solution = Solution()\n solution.rotate(matrix)\n assert matrix == answer, matrix\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"imckl/leetcode","sub_path":"medium/48-rotate-image.py","file_name":"48-rotate-image.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"13478249276","text":"from django.shortcuts import render\n\n# Create your views here.\nimport MySQLdb\nfrom django.shortcuts import render, redirect\nfrom sims.models import Student\n\ndef sqlconnect():\n conn = MySQLdb.connect(host=\"localhost\", user=\"root\", passwd=\"wangyutai\", db=\"sms\", charset='utf8')\n return conn\n\n\n# Create your views here.\n# 学生信息列表处理函数\ndef index(request):\n # conn = sqlconnect()\n # with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:\n # cursor.execute(\"SELECT id,student_no,student_name FROM sims_student\")\n # students = cursor.fetchall()\n students = Student.objects.all()\n return render(request, 'student/index.html', {'students': students})\n\n\n# 学生信息新增处理函数\ndef add(request):\n if request.method == 'GET':\n return render(request, 'student/add.html')\n else:\n student_no = request.POST.get('student_no', '')\n student_name = request.POST.get('student_name', '')\n # conn = sqlconnect()\n # with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:\n # cursor.execute(\"INSERT INTO sims_student (student_no,student_name) \"\n # \"values (%s,%s)\", [student_no, student_name])\n # conn.commit()\n student = Student()\n student.student_name = student_name\n student.student_no = student_no\n student.save()\n return redirect('../')\n\n\n# 学生信息修改处理函数\ndef edit(request):\n if request.method == 'GET':\n id = request.GET.get(\"id\")\n conn = sqlconnect()\n with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:\n cursor.execute(\"SELECT id,student_no,student_name FROM sims_student where id =%s\", [id])\n student = cursor.fetchone()\n return render(request, 'student/edit.html', {'student': student})\n else:\n id = request.POST.get(\"id\")\n student_no = request.POST.get('student_no', '')\n student_name = request.POST.get('student_name', '')\n conn = sqlconnect()\n with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:\n cursor.execute(\"UPDATE sims_student set student_no=%s,student_name=%s where id =%s\",\n [student_no, student_name, id])\n conn.commit()\n return redirect('../')\n\n\n# 学生信息删除处理函数\ndef delete(request):\n id = request.GET.get(\"id\")\n conn = sqlconnect()\n with conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) as cursor:\n cursor.execute(\"DELETE FROM sims_student WHERE id =%s\", [id])\n conn.commit()\n return redirect('../')\n","repo_name":"751329612/3","sub_path":"sims/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"44390166391","text":"import argparse\nimport os\nimport pickle\nfrom cv2 import log\n\nimport numpy as np\nimport torch\nimport torchattacks\nfrom matplotlib import pyplot as plt\n\nimport torchvision\nfrom torchvision import models, transforms\nfrom torchvision.datasets import ImageFolder\nfrom utils import *\nfrom generator_cifar10 import Generator, Discriminator\nimport collections\nfrom collections import Counter\nimport json\nfrom cifar10_models import *\nimport copy\n\n\nclass NpEncoder(json.JSONEncoder):\n def default(self, obj):\n if isinstance(obj, np.integer):\n return int(obj)\n if isinstance(obj, np.floating):\n return float(obj)\n if isinstance(obj, np.ndarray):\n return obj.tolist()\n return json.JSONEncoder.default(self, obj)\n\n\ndef calculate_pcc(x, y):\n \"\"\"\n Calculate pearsonr mimic `scipy.stats.pearsonr`\n :param x: Logit output (N, num_classes)\n :param y: Logit output (N, num_classes)\n :return: N\n \"\"\"\n pearson = []\n for i, j in zip(x, y):\n mean_x = torch.mean(i)\n mean_y = torch.mean(j)\n xm = i.sub(mean_x)\n ym = j.sub(mean_y)\n\n r_num = xm.dot(ym)\n r_den = torch.norm(xm, 2) * torch.norm(ym, 2)\n r_val = r_num / r_den\n pearson.append(r_val.item())\n return pearson\n\n\ndef load_model(archs):\n model_list = {}\n for arch, ckpt_path in archs.items():\n normalize = Normalize(mean=[0.4914, 0.4822, 0.4465],\n std=[0.2023, 0.1994, 0.2010])\n model = globals()[arch]()\n ckpt = torch.load(ckpt_path)\n model = torch.nn.Sequential(normalize, model)\n model.load_state_dict(ckpt['state_dict'])\n # model = model[1] # only use the model, rather than the normalize\n model.eval()\n model.to(device)\n model_list[arch] = model\n return model_list\n\n\ndef calculate_mertic(pert, labels, adv_logits, clean_logits, pert_logits):\n \"\"\"\n Calculate the metric\n :param pert:\n :param labels:\n :param adv_logits:\n :param clean_logits:\n :param pert_logits:\n :return: numpy list\n \"\"\"\n clean_pert_logits = clean_logits + pert_logits\n\n clean_pred = torch.argmax(clean_logits, dim=1)\n adv_pred = torch.argmax(adv_logits, dim=1)\n pert_pred = torch.argmax(pert_logits, dim=1)\n adv_ops_pred = torch.argmax(clean_pert_logits, dim=1)\n\n accuracy_clean = torch.sum(clean_pred == labels).item()\n accuracy_adv = torch.sum(adv_pred == labels).item()\n accuracy_op = torch.sum(adv_pred == adv_ops_pred).item()\n accuracy_op_fr = torch.sum((adv_pred == adv_ops_pred) == (adv_pred != clean_pred)).item()\n fooling_num = torch.sum(adv_pred != clean_pred).item()\n accuracy_adv_pert = torch.sum(adv_pred == pert_pred).item()\n\n pert_norm = [torch.norm(pi, p=2).item() for pi in pert]\n\n pcc_value_adv_clean = calculate_pcc(adv_logits, clean_logits)\n pcc_value_adv_pert = calculate_pcc(adv_logits, pert_logits)\n pcc_value_adv_pert_clean = calculate_pcc(adv_logits, clean_pert_logits)\n\n return adv_pred.cpu().data.numpy(), pert_pred.cpu().data.numpy(), adv_ops_pred.cpu().data.numpy(), \\\n accuracy_clean, accuracy_adv, accuracy_op, accuracy_op_fr, fooling_num, accuracy_adv_pert,\\\n pert_norm, pcc_value_adv_clean, pcc_value_adv_pert, pcc_value_adv_pert_clean\n\n\n\n\ndef test_advops_generator(generator, model_list):\n fooling_num = 0\n accuracy_op = 0\n accuracy_clean = 0\n accuracy_adv = 0\n accuracy_adv_pert = 0\n l2_norms_list = []\n total_cnt = 0\n mertics_dict = {}\n tmp_dict = {\n \"adv_cls\":[],\n \"pert_cls\":[],\n \"clean_pert_cls\":[],\n\n \"l2_norms_list\":[],\n \"pcc_adv_clean\":[],\n \"pcc_value_adv_pert\":[],\n \"pcc_value_adv_pert_clean\":[],\n\n \"acc_clean\":0,\n \"acc_adv\":0,\n \"acc_op\":0,\n \"acc_op_fr\":0,\n \"fooling_num\":0,\n \"accuracy_adv_pert\":0,\n \"total_samples\":0,\n }\n for i, batch in enumerate(validation_loader):\n\n images, labels = batch\n images, labels = images.to(device), labels.to(device)\n\n # train the discriminator with fake data\n pert = generator(images)\n adv_images = torch.clamp(images + pert, 0, 1)\n\n pert = 1.0 / 2 * (pert + 1)\n for key, model in model_list.items():\n with torch.no_grad():\n f_adv = model(adv_images)\n f_clean = model(images)\n f_pert = model(pert)\n\n adv_pred, pert_pred, adv_ops_pred, \\\n acc_clean, acc_adv, acc_op, acc_op_fr, fooling_num, adv_pert_num, \\\n pert_norm, \\\n pcc_value_adv_clean, pcc_value_adv_pert, pcc_value_adv_pert_clean = calculate_mertic(pert, labels,\n f_adv, f_clean,\n f_pert)\n\n if key not in mertics_dict:\n mertics_dict[key] = copy.deepcopy(tmp_dict)\n mertics_dict[key]['adv_cls'].extend(adv_pred)\n mertics_dict[key]['pert_cls'].extend(pert_pred)\n mertics_dict[key]['clean_pert_cls'].extend(adv_ops_pred)\n\n mertics_dict[key]['acc_clean'] += acc_clean\n mertics_dict[key]['acc_adv'] += acc_adv\n mertics_dict[key]['acc_op'] += acc_op\n mertics_dict[key]['acc_op_fr'] += acc_op_fr\n mertics_dict[key]['fooling_num'] += fooling_num\n mertics_dict[key]['accuracy_adv_pert'] += adv_pert_num\n\n mertics_dict[key]['l2_norms_list'].extend(pert_norm)\n mertics_dict[key]['pcc_adv_clean'].extend(pcc_value_adv_clean)\n mertics_dict[key]['pcc_value_adv_pert'].extend(pcc_value_adv_pert)\n mertics_dict[key]['pcc_value_adv_pert_clean'].extend(pcc_value_adv_pert_clean)\n\n mertics_dict[key]['total_samples'] += images.size(0)\n return mertics_dict\n\n\ndef post_propress_dict_data(data_dict, model_list):\n for key, model in model_list.items():\n # most common top100\n data_dict[key]['adv_cls'] = Counter(data_dict[key]['adv_cls']).most_common(100)\n data_dict[key]['pert_cls'] = Counter(data_dict[key]['pert_cls']).most_common(100)\n data_dict[key]['clean_pert_cls'] = Counter(data_dict[key]['clean_pert_cls']).most_common(100)\n\n data_dict[key]['acc_clean'] = round(\n data_dict[key]['acc_clean'] * 100 / data_dict[key]['total_samples'], 2)\n data_dict[key]['acc_adv'] = round(\n data_dict[key]['acc_adv'] * 100 / data_dict[key]['total_samples'], 2)\n data_dict[key]['acc_op'] = round(\n data_dict[key]['acc_op'] * 100 / data_dict[key]['total_samples'], 2)\n data_dict[key]['acc_op_fr'] = round(\n data_dict[key]['acc_op_fr'] * 100 / data_dict[key]['total_samples'], 2)\n data_dict[key]['fooling_num'] = round(\n data_dict[key]['fooling_num'] * 100 / data_dict[key]['total_samples'], 2)\n data_dict[key]['accuracy_adv_pert'] = round(\n data_dict[key]['accuracy_adv_pert'] * 100 / data_dict[key]['total_samples'], 2)\n\n data_dict[key]['l2_norms_list'] = round(np.mean(data_dict[key]['l2_norms_list']), 2)\n data_dict[key]['pcc_adv_clean'] = round(np.mean(data_dict[key]['pcc_adv_clean']), 2)\n data_dict[key]['pcc_value_adv_pert'] = round(np.mean(data_dict[key]['pcc_value_adv_pert']), 2)\n data_dict[key]['pcc_value_adv_pert_clean'] = round(\n np.mean(data_dict[key]['pcc_value_adv_pert_clean']), 2)\n return data_dict\n\n\ndef get_model_list(model_name):\n normalize = Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n model_list = {}\n for mn in model_name:\n if \"resnet50\" in mn.lower():\n model = models.resnet50(pretrained=True)\n elif \"vgg16\" in mn.lower():\n model = models.vgg16(pretrained=True)\n elif \"densenet121\" in mn.lower():\n model = models.densenet121(pretrained=True)\n elif \"resnext\" in mn.lower():\n model = models.resnext50_32x4d(pretrained=True)\n elif \"wideresnet\" in mn.lower():\n model = models.wide_resnet50_2(pretrained=True)\n elif \"mnasnet\" in mn.lower():\n model = models.mnasnet1_0(pretrained=True)\n elif \"squeezenet\" in mn.lower():\n model = models.squeezenet1_0(pretrained=True)\n\n model = torch.nn.Sequential(normalize, model)\n model.eval()\n model.to(device)\n model_list[mn] = model\n return model_list\n\n\ndef load_cifar10(args):\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n ])\n testset = torchvision.datasets.CIFAR10(root=args.data_path, train=False,\n download=True, transform=transform_test)\n return testset\n\ndef get_args():\n parser = argparse.ArgumentParser(description=\"Args Container\")\n parser.add_argument(\"--data_dir\", type=str, default=r'/mnt/jfs/wangdonghua/pythonpro/AdvOps/cifar10_models/data')\n parser.add_argument(\"--ckpt_path\", type=str, default='checkpoints/')\n parser.add_argument(\"--model_ckpt\", type=str, default='cifar10_models/checkpoints/')\n parser.add_argument(\"--model_name\", type=str, default='resnet50', help=\"model name of the evluation model\")\n parser.add_argument(\"--loss_idx\", type=int, default=0, help=\"0: custom_loss, 1: mse_loss, 2:kl_loss\")\n parser.add_argument(\"--input_size\", type=int, default=224)\n parser.add_argument(\"--batch_size\", type=int, default=200)\n args = parser.parse_args()\n return args\n\n\nif __name__ == \"__main__\":\n idx2label, _ = get_imagenet_dicts()\n args = get_args()\n\n test_transform = transforms.Compose([\n transforms.Resize(256),\n transforms.CenterCrop(args.input_size),\n transforms.ToTensor(),\n ])\n # dataset\n test_data = load_cifar10(args)\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n model_name_list = {\n 'preactresnet18':f\"{args.model_ckpt}/CIFAR10_preactresnet18.pth.tar\",\n 'wideresnet':f\"{args.model_ckpt}/CIFAR10_wideresnet.pth.tar\",\n \"resnet50\": f\"{args.model_ckpt}/CIFAR10_resnet50.pth.tar\",\n \"densenet121\": f\"{args.model_ckpt}/CIFAR10_densenet121.pth.tar\",\n \"vgg16\": f\"{args.model_ckpt}/CIFAR10_vgg16.pth.tar\",\n \"vgg19\": f\"{args.model_ckpt}/CIFAR10_vgg19.pth.tar\"\n }\n\n model_list = load_model(model_name_list)\n\n model_name_list = list(model_name_list.keys())\n logit_type = [\"custom_loss\", \"mse_loss\", \"kl_loss\"]\n\n specific_str = f'{model_name_list[args.model_name]}_{logit_type[args.loss_idx]}'\n\n validation_loader = torch.utils.data.DataLoader(test_data, batch_size=args.batch_size)\n\n generator_ckpt_file_dict = {\n \"CIFAR10_resnet50\": f'{args.ckpt_path}/CIFAR10_Generator_for_resnet50.pth',\n \"CIFAR10_vgg16\": f'{args.ckpt_path}/CIFAR10_Generator_for_vgg16.pth',\n \"CIFAR10_vgg19\": f'{args.ckpt_path}/CIFAR10_Generator_for_vgg19.pth',\n \"CIFAR10_densenet121\": f'{args.ckpt_path}/CIFAR10_Generator_for_densenet121.pth',\n \"CIFAR10_preactresnet18\": f'{args.ckpt_path}/CIFAR10_Generator_for_preactresnet18.pth',\n \"CIFAR10_wideresnet50\": f'{args.ckpt_path}/CIFAR10_Generator_for_wideresnet50.pth',\n }\n\n ckpt_file = generator_ckpt_file_dict[f\"CIFAR10_{args.model_name}\"]\n\n g = Generator(3, 3)\n g.load_state_dict(torch.load(ckpt_file))\n g = g.to(device)\n g.eval()\n model_name = model_name_list[0]\n attack_metric_dict = test_advops_generator(g, model_list)\n attack_metric_dict = post_propress_dict_data(attack_metric_dict, model_list)\n print(f\"Target model: {model_name}\\n Attack: AdvOpsGAN\\n\", attack_metric_dict)\n result_dict = {\n \"attack\": \"AdvOpsGAN\",\n \"target_model\": model_name,\n \"result\": attack_metric_dict\n }\n try:\n json_string = json.dumps(result_dict, sort_keys=False, cls=NpEncoder)\n with open(f\"baseline_evaluate_result/{model_name}_AdvOpsGAN_{specific_str}.json\", 'w') as fw:\n fw.write(json_string)\n except:\n with open(f\"baseline_evaluate_result/{model_name}_AdvOpsGAN_{specific_str}.pkl\", 'w') as fw:\n pickle.dump(result_dict, fw)\n finally:\n np.save(f\"baseline_evaluate_result/{model_name}_AdvOpsGAN_{specific_str}.npy\", result_dict)\n","repo_name":"winterwindwang/AdvOps","sub_path":"baseline_methods_transfer_gan_cifar10.py","file_name":"baseline_methods_transfer_gan_cifar10.py","file_ext":"py","file_size_in_byte":12469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31266492915","text":"import io\nimport os\nimport json\nimport logging\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nimport matplotlib.pyplot as plt\n\ntfkl = tf.keras.layers\ntfkc = tf.keras.callbacks\ntfd = tfp.distributions\ntfb = tfp.bijectors\n\ndtype = tf.float32\n\nlogger = logging.getLogger(__name__)\n\n\ndef pretty_json(hp):\n json_hp = json.dumps(hp, indent=2)\n return \"\".join(\"\\t\" + line for line in json_hp.splitlines(True))\n\n\ndef lognormal_pdf(loc, scale):\n \"\"\" Lognormal definition as in Wikipedia (FU scipy) \"\"\"\n\n def pdf_fn(x):\n norm = np.sqrt(2 * np.pi) * scale * x\n arg = - (np.log(x) - loc) ** 2 / (2 * scale ** 2)\n return np.exp(arg) / norm\n\n return pdf_fn\n\n\ndef plot_to_image(figure):\n \"\"\"\n Converts the matplotlib plot specified by 'figure' to a PNG image and\n returns it. The supplied figure is closed and inaccessible after this\n call.\n \"\"\"\n\n # Save the plot to a PNG in memory.\n buf = io.BytesIO()\n # plt.savefig(buf, format='png')\n figure.savefig(buf, format='png')\n\n # Closing the figure prevents it from being displayed directly inside\n # the notebook.\n plt.close(figure)\n buf.seek(0)\n\n # Convert PNG buffer to TF image\n image = tf.image.decode_png(buf.getvalue(), channels=4)\n\n # Add the batch dimension\n image = tf.expand_dims(image, 0)\n\n return image\n\n\ndef fig_mean_to_std_distribution(df: pd.DataFrame):\n \"\"\"\n Plot the distribution of the mean to standard deviation ratios\n of the predicted distributions\n \"\"\"\n\n label = 'mean to std ratio of predicted distributions'\n\n fig = plt.figure()\n plt.hist(df['mean'] / df['std'], bins=100, label=label)\n plt.legend()\n\n return fig\n\n\ndef fig_median_to_pct_range_distribution(\n df: pd.DataFrame, qtile_range: tuple[float, float]\n):\n \"\"\"\n Plot the distribution of the ratio btw the median and some percentile\n range.\n\n Params\n ------\n df: table with the columns:\n `q_050`: median\n `q_`: first element of qtile_range\n `q_`: second element of qtile_range\n qtile_range:\n \"\"\"\n\n q1, q2 = qtile_range\n c1, c2 = f'q_{int(q1 * 100):03d}', f'q_{int(q2 * 100):03d}'\n label = f'median to ({c2} - {c1}) ratio of predicted distributions'\n\n fig = plt.figure()\n plt.hist(df['q_050'] / (df[c2] - df[c1]), bins=100, label=label)\n plt.legend()\n\n return fig\n\n\ndef fig_pct_skew(df: pd.DataFrame):\n \"\"\"\n Plot distribution percentile of true values vs fraction of\n observations that belong to a lower percentile\n\n Params\n ------\n df: table with the columns:\n `pct`: percentile to which the observed value corresponds to\n `frac`: fraction of observations that belong to a lower predicted\n percentile\n \"\"\"\n\n label = ('Predicted percentile vs fraction of observations '\n 'that belong to a lower predicted percentile')\n\n fig = plt.figure(figsize=(15, 10))\n plt.scatter(df['pct'], df['frac'], alpha=0.2, s=20, label=label)\n plt.plot([0, 1], [0, 1], color='black', linestyle='dashed')\n plt.legend()\n\n return fig\n\n\ndef fig_pct_skew_discrete(df: pd.DataFrame, quantiles: list):\n \"\"\"\n For a discrete number of predicted percentiles calculate and visualize\n the fraction of observations that are below this percentile\n\n Params\n ------\n df: table with the columns:\n q_< pct >: predicted distribution percentiles\n y: observed value\n \"\"\"\n\n frac = [(df['y'] < df[f'q_{int(q * 100):03d}']).mean()\n for q in quantiles]\n\n label = ('Predicted percentile vs fraction of observations \\n'\n 'that belong to a lower predicted percentile')\n\n fig = plt.figure()\n plt.scatter(quantiles, frac, label=label)\n plt.plot([0, 1], [0, 1], color='black', linestyle='dashed')\n plt.legend()\n\n return fig\n\n\ndef evaluate_percentile_model(\n model,\n ds,\n log_dir: str,\n log_data: dict,\n quantiles: tuple,\n qtile_range: tuple[float, float]\n):\n \"\"\" Compare predicted percentiles against observations \"\"\"\n\n save_dir = os.path.join(log_dir, 'train')\n file_writer = tf.summary.create_file_writer(save_dir)\n\n df = pd.DataFrame()\n df['y'] = np.hstack(list(ds.map(lambda x, y: y).as_numpy_iterator()))\n\n pct_columns = [f'q_{int(x * 100):03d}' for x in quantiles]\n df[pct_columns] = model.predict(ds.map(lambda x, y: x))\n\n fig = fig_pct_skew_discrete(df, quantiles=quantiles)\n\n with file_writer.as_default():\n name = 'predicted pct vs frac of observations with lower predicted pct'\n img = plot_to_image(fig)\n tf.summary.image(name, img, step=0)\n\n fig = fig_median_to_pct_range_distribution(df, qtile_range=qtile_range)\n\n with file_writer.as_default():\n name = \"median to pct-range of predicted distributions\"\n img = plot_to_image(fig)\n tf.summary.image(name, img, step=0)\n\n with file_writer.as_default():\n log_data = pretty_json(log_data)\n tf.summary.text(\"experiment_args\", log_data, step=0)\n\n\ndef evaluate_parametrized_pdf_model(\n model, ds, log_dir: str, log_data: dict, clusters: int = 20\n):\n \"\"\" Compare predicted distributions against observations \"\"\"\n\n save_dir = os.path.join(log_dir, 'train')\n file_writer = tf.summary.create_file_writer(save_dir)\n\n distribution_fn = model.layers[-1].function\n\n model_deterministic = tf.keras.Model(\n inputs=model.inputs,\n outputs=[model.layers[-2].output])\n\n df = pd.DataFrame()\n\n df['y'] = np.hstack(list(ds.map(lambda x, y: y).as_numpy_iterator()))\n\n # predict distribution parameters\n df[['p1', 'p2']] = model_deterministic.predict(ds.map(lambda x, y: x))\n\n distribution = distribution_fn(df[['p1', 'p2']].values)[0]\n\n df['mean'] = distribution.mean()\n df['std'] = distribution.stddev()\n df['pct'] = distribution.cdf(df[['y']].values)\n\n # fraction of prediction with lower percentile\n df = df.assign(frac=lambda x: (x['pct'].sort_values() * 0 + 1).cumsum() / x.shape[0])\n\n \"\"\"\n Figures\n \"\"\"\n\n fig = fig_mean_to_std_distribution(df=df)\n\n with file_writer.as_default():\n name = \"mean to std ratio of predicted distributions\"\n img = plot_to_image(fig)\n tf.summary.image(name, img, step=0)\n\n fig = fig_pct_skew(df.iloc[:1_000])\n\n with file_writer.as_default():\n name = 'predicted pct vs frac of observations with lower predicted pct'\n img = plot_to_image(fig)\n tf.summary.image(name, img, step=0)\n\n with file_writer.as_default():\n log_data = pretty_json(log_data)\n tf.summary.text(\"experiment_args\", log_data, step=0)\n","repo_name":"ImScientist/probabilistic-forecasting-travel-time","sub_path":"src/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":6798,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70661302914","text":"\"\"\"\nExtensions for pyrestcli Resource and Manager classes\n\n.. module:: carto.resources\n :platform: Unix, Windows\n :synopsis: Extensions for pyrestcli Resource and Manager classes\n\n.. moduleauthor:: Daniel Carrion \n.. moduleauthor:: Alberto Romeu \n\n\n\"\"\"\n\nimport warnings\n\nfrom pyrestcli.resources import Resource, Manager as PyRestCliManager\n\nfrom .exceptions import CartoException\n\n\nclass AsyncResource(Resource):\n def run(self, **client_params):\n \"\"\"\n Actually creates the async job on the CARTO server\n\n\n :param client_params: To be send to the CARTO API. See CARTO's\n documentation depending on the subclass\n you are using\n :type client_params: kwargs\n\n\n :return:\n :raise: CartoException\n \"\"\"\n try:\n self.send(self.get_collection_endpoint(),\n http_method=\"POST\",\n **client_params)\n except Exception as e:\n raise CartoException(e)\n\n def refresh(self):\n \"\"\"\n Updates the information of the async job against the CARTO server.\n After calling the :func:`refresh` method you should check the `state`\n attribute of your resource\n\n :return:\n \"\"\"\n if self.get_resource_endpoint() is None:\n raise CartoException(\"Async job needs to be run or retrieved \\\n first!\")\n\n super(AsyncResource, self).refresh()\n\n\nclass WarnAsyncResource(AsyncResource):\n \"\"\"\n AsyncResource class for resources that represent non-public CARTO APIs.\n You'll be warned not to used the in production environments\n \"\"\"\n def __init__(self, auth_client, **kwargs):\n \"\"\"\n Initializes the resource\n :param auth_client: Client to make (non)authorized requests\n :param kwargs: Initial value for attributes\n :return:\n \"\"\"\n\n warnings.warn('This is part of a non-public CARTO API and may change in \\\n the future. Take this into account if you are using \\\n this in a production environment', FutureWarning)\n super(WarnAsyncResource, self).__init__(auth_client, **kwargs)\n\n\nclass WarnResource(Resource):\n \"\"\"\n Resource class for resources that represent non-public CARTO APIs.\n You'll be warned not to used the in production environments\n \"\"\"\n def __init__(self, auth_client, **kwargs):\n \"\"\"\n Initializes the resource\n :param auth_client: Client to make (non)authorized requests\n :param kwargs: Initial value for attributes\n :return:\n \"\"\"\n\n warnings.warn('This is part of a non-public CARTO API and may change in the future. Take this into account if you are using this in a production environment', FutureWarning)\n super(WarnResource, self).__init__(auth_client, **kwargs)\n\n\nclass Manager(PyRestCliManager):\n \"\"\"\n Manager class for resources\n \"\"\"\n def __init__(self, auth_client):\n \"\"\"\n :param auth_client: Client to make (non)authorized requests\n\n :return:\n \"\"\"\n self.paginator = self.paginator_class(self.json_collection_attribute,\n auth_client.base_url)\n super(PyRestCliManager, self).__init__(auth_client)\n","repo_name":"CartoDB/carto-python","sub_path":"carto/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":154,"dataset":"github-code","pt":"61"}
+{"seq_id":"32943105487","text":"#! /usr/bin/env python3\n\nimport os\nimport cv2\nimport math\nimport torch\nimport warnings\nimport numpy as np\nfrom cv_bridge import CvBridge\nfrom pyquaternion import Quaternion as PyQuaternion\n\n# import the custom packages\nimport lib.my_utils as my_utils\nfrom yofo.model import Yofo\n\n# import the necessary ROS packages\nimport rospy\nimport message_filters\nfrom sensor_msgs.msg import Image\nfrom gazebo_msgs.msg import ModelStates\nfrom geometry_msgs.msg import Pose, Point\n\n\n\nPKG_PATH = os.path.dirname(os.path.abspath(__file__))\nMODELS_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"..\", \"models\")\n\nMODELS = [\n \"X1-Y1-Z2\",\n \"X1-Y2-Z1\",\n \"X1-Y2-Z2\",\n \"X1-Y2-Z2-CHAMFER\",\n \"X1-Y2-Z2-TWINFILLET\",\n \"X1-Y3-Z2\",\n \"X1-Y3-Z2-FILLET\",\n \"X1-Y4-Z1\",\n \"X1-Y4-Z2\",\n \"X2-Y2-Z2\",\n \"X2-Y2-Z2-FILLET\"]\n\nPOSES = [\"UP\", \"DOWN\", \"NORTH\", \"SOUTH\", \"EAST\", \"WEST\"]\n\n\ndef init(camera_name):\n \"\"\"\n Initialize the camera parameters\n \"\"\"\n from sensor_msgs.msg import Image, CameraInfo\n from gazebo_msgs.srv import GetModelState\n camera_info = rospy.wait_for_message(\"/camera/color/camera_info\", CameraInfo)\n rospy.wait_for_service(\"/gazebo/get_model_state\")\n camera_state_srv = rospy.ServiceProxy('/gazebo/get_model_state', GetModelState)\n camera_state = camera_state_srv(camera_name, \"\") # Change this to your model name\n camera_pose = my_utils.rob2cam(camera_state.pose) # Convert to camera axis convention\n\n # Build camera reference frame\n camera_frame = np.zeros((4, 4), dtype=np.float64)\n camera_frame[:, 3] = [camera_pose.position.x, camera_pose.position.y, camera_pose.position.z, 1]\n camera_frame[:3, :3] = camera_pose.orientation.rotation_matrix\n\n # Convert camera pose to numpy\n camera_pose.position = np.array((\n abs(camera_pose.position.x),\n abs(camera_pose.position.y),\n camera_pose.position.z), dtype=np.float64)\n # Convert quaternion to pyquaternion\n camera_pose.orientation = PyQuaternion(\n x=camera_pose.orientation.x,\n y=camera_pose.orientation.y,\n z=camera_pose.orientation.z,\n w=camera_pose.orientation.w\n )\n camera_view = (camera_info.width, camera_info.height)\n camera_matrix = np.array(camera_info.K).reshape((3, 3))\n dist_coeffs = np.array(camera_info.D)\n\n return camera_frame, camera_view, camera_matrix, dist_coeffs\n\n\ndef detect_yofo(image):\n pred = yofo(image).squeeze()\n clss = pred.argmax(dim=0, keepdim=True).flatten().cpu().item()\n conf = pred[clss].cpu().item()\n #clss = pred.sum(axis=0).argmax(dim=0, keepdim=True).flatten().cpu()\n #conf = pred.sum(axis=0)[clss].cpu().item()\n return clss, conf\n\n\ndef detect_yolo(image):\n pred = yolo(image).pandas()\n return pred\n\n\n###############################################################################\n# Callback\n###############################################################################\ndef camera_callback(image_color, image_depth, model_infos):\n global image_view\n image_color = CvBridge().imgmsg_to_cv2(image_color, \"bgr8\")\n depth = CvBridge().imgmsg_to_cv2(image_depth, \"32FC1\")\n\n # Convert depth map to rgb grayscale\n image_depth = -depth + depth.max()\n image_depth *= 255 / 0.20\n image_depth = cv2.cvtColor(image_depth, cv2.COLOR_GRAY2RGB)\n\n # CREATE THE ESTIMATED MODEL STATES MESSAGE\n estimated_model_states = ModelStates()\n\n res = detect_yolo(image_depth)\n for x1, y1, x2, y2, clss_conf, clss_id, clss_nm in res.xyxy[0].to_numpy()[:, :7]:\n if clss_conf < 0.65:\n continue\n\n x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)\n\n # crop the depth image from the bounding box\n depth_crop = depth[y1:y2, x1:x2]\n depth_crop_max = depth_crop.max()\n depth_crop_min = depth_crop.max()\n\n model_info = model_infos[clss_id]\n\n # Find the contour of the object\n thresh = depth_crop_max - 0.005\n rect, angle, depth_crop = my_utils.min_area_crop(depth_crop, thresh)\n if depth_crop is None: # Object was not found\n continue\n\n # Resize the cropped depth image to a 32x32 image\n depth_crop = cv2.resize(depth_crop, (32, 32), interpolation=cv2.INTER_NEAREST)\n depth_crop = np.expand_dims(depth_crop, axis=(0, 3))\n\n # Infer pose using custom model\n pose_id, pose_conf = detect_yofo(torch.from_numpy(depth_crop))\n\n model_size = model_info[\"size\"]\n\n # Get the camera facing axis of the object\n model_height = depth_crop_max - depth_crop_min\n if pose_id == 0: # up\n axis = 2\n elif pose_id == 1: # down\n axis = 2\n else:\n if model_height < model_size[0] + 0.005:\n axis = 0\n else:\n axis = 1\n\n # Find the x-y-z coordinates of the object\n model_xyz = np.array(\n [int(rect[0][0] + x1),\n int(rect[0][1] + y1),\n depth_crop_max + model_height/2,\n 1],\n dtype=np.float32)\n model_xyz[:2] /= image_color.shape[1], image_color.shape[0]\n model_xyz[:2] -= 0.5\n #model_xyz[:2] -= model_xyz[:2]*2*0.02 # correct for perspective\n model_xyz[:2] *= (0.900, 0.900)\n model_xyz = np.dot(camera_frame, model_xyz)\n\n # Calculate xy-plane rotation mod 180°\n rotZ = - rect[2] / 90 * (math.pi/2)\n horizontal = rect[1][0] < rect[1][1] # rect long side is along x-axis\n\n # Calculate the object quaternion\n if pose_id == 0: # UP\n rotZ = rotZ if horizontal else rotZ + math.pi / 2\n quat = PyQuaternion(axis=(0, 0, 1), angle=0) # z-axis along world-frame z-axis\n elif pose_id == 1: # DOWN\n rotZ = rotZ if horizontal else rotZ + math.pi / 2\n quat = PyQuaternion(axis=(0, 1, 0), angle=math.pi) # z-axis along world-frame negative z-axis\n elif pose_id == 2: # NORTH\n quat = PyQuaternion(axis=(1, 0, 0), angle=math.pi/2)\n rotZ += 0\n elif pose_id == 3: # SOUTH\n quat = PyQuaternion(axis=(1, 0, 0), angle=math.pi/2)\n rotZ += math.pi\n elif pose_id == 4: # EAST\n quat = PyQuaternion(axis=(1, 0, 0), angle=math.pi/2)\n rotZ += -math.pi/2\n elif pose_id == 5: # WEST\n quat = PyQuaternion(axis=(1, 0, 0), angle=math.pi/2)\n rotZ += math.pi/2\n else:\n raise ValueError(\"Unknown pose id: {}\".format(pose_id))\n if axis == 0:\n quat *= PyQuaternion(axis=(0, 0, 1), angle=math.pi / 2)\n else:\n pass\n quat = PyQuaternion(axis=(0, 0, 1), angle=rotZ) * quat # apply x-y world plane rotation\n\n # Store the estimated pose\n estimated_model_states.name.append(model_info[\"name\"])\n estimated_model_states.pose.append(Pose(\n Point(*model_xyz[:3]),\n quat\n ))\n\n \"\"\"\n VISUALIZATION\n \"\"\"\n rot_tra = np.zeros((4, 4), dtype=np.float64)\n # Rotation matrix\n rot_tra[:3, :3] = quat.rotation_matrix\n # Trasform matrix\n rot_tra[:4, 3] = (*model_xyz[:3], 1.0)\n\n # Axes of the model\n axes = np.ones((4, 4), dtype=np.float64)\n axes[:, :3] = np.array([\n [0, 0, 0], # origin\n [.1, 0, 0], # x\n [0, .1, 0], # y\n [0, 0, .1]]) # z\n axes = np.dot(rot_tra, axes.T)[:3, :]\n (axes_2dproj, _) = cv2.projectPoints(\n axes,\n camera_frame[:3, :3], abs(camera_frame[:3, 3]),\n camera_matrix, dist_coeffs)\n axes_2dproj = axes_2dproj.reshape(-1, 2).astype(np.int32)\n\n cv2.line(image_color,\n axes_2dproj[0],\n axes_2dproj[1],\n (0, 0, 255), 2) # B G R\n cv2.line(image_color,\n axes_2dproj[0],\n axes_2dproj[2],\n (0, 255, 0), 2)\n cv2.line(image_color,\n axes_2dproj[0],\n axes_2dproj[3],\n (255, 0, 0), 2)\n\n # visualize the yolo bounding box\n # cv2.rectangle(image_show, (x1, y1), (x2, y2), (0, 255, 0), 2)\n\n # visualize the rotated bounding box\n box = np.int0(cv2.boxPoints(rect) + (x1, y1))\n cv2.drawContours(image_color, [box], 0, (0, 0, 255), 2)\n\n # visualize the pose\n text = f\"{POSES[pose_id]} {pose_conf:.2f}\"\n cv2.putText(image_color, text, (x1, y1-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 0), 1)\n\n # visualize the class\n text = f\"{model_info['name']} {clss_conf:.2f}\"\n cv2.putText(image_color, text, (x1, y2+10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 0), 1)\n\n # Send the estimated model poses\n pub_model_states.publish(estimated_model_states)\n image_view = image_color\n\n\nif __name__ == \"__main__\":\n # Ignore warnings due to YOLOv5 spamming the console when running on CPU\n warnings.simplefilter(\"ignore\")\n\n # Setting default device for pytorch\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n torch.set_grad_enabled(False)\n\n print(\"Initializing vision node\")\n rospy.init_node(\"lego_builder_vision\")\n\n print(\" Loading camera sensor parameters\")\n camera_frame, camera_view, camera_matrix, dist_coeffs = init(\"kinect\")\n\n print(\" Loading pytorch models\")\n yolo = torch.hub.load(\n f\"{PKG_PATH}/yolo/yolov5\",\n \"custom\",\n path=f\"{PKG_PATH}/yolo/best.20epoch.pt\",\n force_reload=True,\n device=device,\n source=\"local\").eval()\n print(f\" + Loaded YOLO on {device}\")\n\n yofo = Yofo().eval()\n yofo.load_state_dict(torch.load(f\"{PKG_PATH}/yofo/last.pt\", map_location=device))\n print(f\" + Loaded YOFO on {device}\")\n\n print(f\" Loading 3D models dimensions\")\n model_infos = []\n for model in MODELS:\n model_infos.append({\n \"name\": model,\n \"size\": my_utils.get_model_size(f\"lego_{model}\", f\"{PKG_PATH}/../models\")\n })\n\n print(f\" Initializing ROS publisher and ROS subscriber\")\n pub_model_states = rospy.Publisher(\"estimated_model_states\", ModelStates, queue_size=1)\n\n sub_image_color = message_filters.Subscriber(\"/camera/color/image_raw\", Image)\n sub_image_depth = message_filters.Subscriber(\"/camera/depth/image_raw\", Image)\n ts = message_filters.TimeSynchronizer([sub_image_color, sub_image_depth], 1, reset=True) # exact sync\n ts.registerCallback(camera_callback, model_infos)\n\n rate = rospy.Rate(1)\n image_view = np.zeros((camera_view[1], camera_view[0], 3), dtype=np.uint8)\n print(f\"Starting main loop...\")\n # Visualize results from camera_callback\n while not rospy.is_shutdown():\n cv2.imshow(\"Predictions\", image_view)\n cv2.waitKey(1)\n rate.sleep()\n","repo_name":"zabealbe/lego-builder","sub_path":"src/lego_builder/lego_builder_vision/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10853,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"}
+{"seq_id":"71097274433","text":"from AthenaConfiguration.ComponentAccumulator import ComponentAccumulator\nfrom AthenaConfiguration.ComponentFactory import CompFactory\nfrom SCT_Cabling.SCT_CablingConfig import SCT_CablingToolCfg\nfrom SCT_ConditionsTools.SCT_ConditionsToolsConfig import SCT_ConfigurationConditionsToolCfg\nfrom SCT_GeoModel.SCT_GeoModelConfig import SCT_ReadoutGeometryCfg\n\n\ndef SCT_RodDecoderCfg(flags, prefix=\"InDet\", suffix=\"\", **kwargs):\n acc = ComponentAccumulator()\n acc.merge(SCT_ReadoutGeometryCfg(flags))\n kwargs.setdefault(\"SCT_CablingTool\", acc.popToolsAndMerge(SCT_CablingToolCfg(flags)))\n kwargs.setdefault(\"ConfigTool\", acc.popToolsAndMerge(SCT_ConfigurationConditionsToolCfg(flags)))\n acc.setPrivateTools(CompFactory.SCT_RodDecoder(name=prefix+\"SCTRodDecoder\"+suffix,\n **kwargs))\n return acc\n\n\ndef SCTRawDataProviderToolCfg(flags, prefix=\"InDet\", suffix=\"\", **kwargs):\n acc = ComponentAccumulator()\n kwargs.setdefault(\"Decoder\", acc.popToolsAndMerge(SCT_RodDecoderCfg(flags, prefix=prefix, suffix=suffix)))\n acc.setPrivateTools(CompFactory.SCTRawDataProviderTool(name=prefix+\"SCTRawDataProviderTool\"+suffix,\n **kwargs))\n return acc\n\n\ndef SCTRawDataProviderCfg(flags, prefix=\"InDet\", suffix=\"\", **kwargs):\n \"\"\" Configures the main algorithm for SCT raw data decoding \"\"\"\n acc = ComponentAccumulator() \n kwargs.setdefault(\"ProviderTool\", acc.popToolsAndMerge(SCTRawDataProviderToolCfg(flags, prefix, suffix)))\n acc.addEventAlgo(CompFactory.SCTRawDataProvider(name=prefix+\"SCTRawDataProvider\"+suffix,\n **kwargs))\n return acc\n\n\n\ndef TrigSCTRawDataProviderCfg(flags, suffix, RoIs):\n \"\"\" Configures the SCT raw data decoding with trigger args \"\"\"\n\n from RegionSelector.RegSelToolConfig import regSelTool_SCT_Cfg\n\n regSelAcc = regSelTool_SCT_Cfg(flags)\n regSelTools = regSelAcc.popPrivateTools()\n trigargs = {\n 'prefix' : 'Trig',\n 'suffix' : suffix,\n 'RegSelTool' : regSelTools,\n 'RDOKey' : 'SCT_RDOs',\n 'RoIs' : RoIs, \n 'isRoI_Seeded': True,\n 'RDOCacheKey' : 'SctRDOCache',\n 'BSErrCacheKey' : 'SctBSErrCache'\n }\n\n dataPrepAcc = SCTRawDataProviderCfg(flags, **trigargs)\n dataPrepAcc.merge(regSelAcc)\n return dataPrepAcc\n\ndef SCTOverlayRawDataProviderCfg(flags, prefix=\"InDet\", suffix=\"\", **kwargs):\n \"\"\" Configures the main algorithm for SCT raw data decoding for data overlay \"\"\"\n kwargs.setdefault(\"RDOKey\", flags.Overlay.BkgPrefix + \"SCT_RDOs\")\n kwargs.setdefault(\"LVL1IDKey\", flags.Overlay.BkgPrefix + \"SCT_LVL1ID\")\n kwargs.setdefault(\"BCIDKey\", flags.Overlay.BkgPrefix + \"SCT_BCID\")\n return SCTRawDataProviderCfg(flags, prefix, suffix, **kwargs)\n\n\ndef SCTEventFlagWriterCfg(flags, prefix=\"InDet\", suffix=\"\", **kwargs):\n acc = ComponentAccumulator()\n acc.addEventAlgo(CompFactory.SCTEventFlagWriter(name=prefix+\"SCTEventFlagWriter\"+suffix,\n **kwargs))\n return acc\n","repo_name":"Yusuf-Manjra/athena","sub_path":"InnerDetector/InDetEventCnv/SCT_RawDataByteStreamCnv/python/SCT_RawDataByteStreamCnvConfig.py","file_name":"SCT_RawDataByteStreamCnvConfig.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72708722753","text":"import requests\nimport os\nimport time\nimport logging\nSERVER_URL = \"https://cert/api/v1/\"\nTOKEN = \"your token\"\nCERT_FILE_NAME = \"cert\"\nLOCAL_PATH = os.path.dirname(os.path.abspath(__file__))\nTIMESTAMP = str(int(time.time()))\nMOVE_PATH = \"/etc/XrayR/cert\"\nTMP_PATH = \"/tmp/cert\"+TIMESTAMP+\"/\"\n\nlogging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s-----client:CertDownloader', level=logging.INFO,filename=LOCAL_PATH+'/log')\n\ndef move_cert(fname):\n logging.info(\"move cert\")\n if os.path.exists(MOVE_PATH):\n if os.path.exists(MOVE_PATH+\"_\"+\"bak\"):\n os.system(\"rm -rf \"+MOVE_PATH+\"_\"+\"bak\")\n os.rename(MOVE_PATH,MOVE_PATH+\"_\"+\"bak\")\n os.mkdir(MOVE_PATH)\n os.system(\"unzip \"+LOCAL_PATH+\"/cert/\"+fname+\" -d \"+TMP_PATH)\n try:\n os.system(\"mv \"+TMP_PATH+\"fullchain.pem \"+MOVE_PATH+\"/fullchain.pem\")\n os.system(\"mv \"+TMP_PATH+\"privkey.pem \"+MOVE_PATH+\"/privkey.pem\")\n except:\n logging.warning(\"move cert error\")\n logging.info(\"move cert success\")\n os.system(\"rm -rf \"+TMP_PATH)\n restart_xrayr=os.popen(\"XrayR restart\")\n if \"成功\" in restart_xrayr.read():\n logging.info(\"restart xrayr success\")\n else:\n logging.warning(\"restart xrayr error\")\n restart_xrayr.close()\n\n \n \ndef flag_set():\n if not os.path.exists(LOCAL_PATH+\"/cert\"):\n os.mkdir(LOCAL_PATH+\"/cert\")\n for root, dirs, files in os.walk(LOCAL_PATH+\"/cert\"):\n if len(files) == 0:\n logging.info(\"no local files\")\n return True\n elif len(files) == 1:\n logging.info(\"one local file\")\n if files[0].split(\"_\")[0] == CERT_FILE_NAME:\n logging.info(\"file name match\")\n return files[0]\n\ndef main():\n IN_UPDATE = False\n logging.info(\"update cert\")\n download_flag = flag_set()\n if download_flag==True:\n logging.info(\"download cert by first time\")\n r = requests.get(SERVER_URL+CERT_FILE_NAME+\"_\"+TIMESTAMP, params={\"token\": TOKEN,\"download\":True})\n elif download_flag==None:\n return logging.info(\"download_flag is None[file in cert folder are more than one]\")\n else:\n logging.info(\"check update by timestamp\")\n IN_UPDATE = True\n r = requests.get(SERVER_URL+download_flag.split(\".\")[0], params={\"token\": TOKEN})\n if r.status_code == 200 and \"error\" not in r.text:\n fname = r.headers[\"content-disposition\"].split(\";\")[1].split(\"=\")[1].replace('\"', '')\n if IN_UPDATE: os.remove(LOCAL_PATH+\"/cert/\"+download_flag)\n with open(LOCAL_PATH+\"/cert/\"+fname, \"wb\") as f:\n f.write(r.content)\n logging.info(\"download success\")\n move_cert(fname)\n else:\n msg=\"have error or status code not 200: \"+str(r.status_code)+\":\"+r.text\n logging.info(msg)\n\nif __name__ == \"__main__\":\n main()\n # https://cert/api/v1/cert_16687041030?token=\n","repo_name":"yuanweize/CertDeliver","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16934447295","text":"from datetime import datetime\n\nimport alerts.geomodel.alert as alert\nimport alerts.geomodel.factors as factors\n\n\nclass MockMMDB:\n '''Mocks a MaxMind database connection with a dictionary of records mapping\n IP adresses to dictionaries containing information about ASNs.\n '''\n\n def __init__(self, records):\n self.records = records\n\n def get(self, ip):\n return self.records.get(ip)\n\n def close(self):\n return\n\n\ndef null_origin(ip):\n return alert.Origin(\n ip=ip,\n city='Null',\n country='NA',\n latitude=0.0,\n longitude=0.0,\n observed=datetime.now(),\n geopoint='0.0,0.0')\n\n\n# A set of records for a mocked MaxMind database containing information about\n# ASNs used to test the `asn_movement` factor implementation with.\nasn_mvmt_records = {\n '1.2.3.4': {\n 'autonomous_system_number': 54321,\n 'autonomous_system_organization': 'CLOUDFLARENET'\n },\n '4.3.2.1': {\n 'autonomous_system_number': 12345,\n 'autonomous_system_organization': 'MOZILLA_SFO1'\n },\n '5.6.7.8': {\n 'autonomous_system_number': 67891,\n 'autonomous_system_organization': 'AMAZONAWSNET'\n }\n}\n\n\ndef test_asn_movement():\n factor = factors.asn_movement(\n MockMMDB(asn_mvmt_records),\n 'WARNING')\n\n test_hops = [\n alert.Hop(\n origin=null_origin('1.2.3.4'),\n destination=null_origin('4.3.2.1')),\n alert.Hop(\n origin=null_origin('4.3.2.1'),\n destination=null_origin('5.6.7.8'))\n ]\n\n test_alert = alert.Alert(\n username='tester',\n hops=test_hops,\n severity='INFO',\n factors=[])\n\n pipeline = [factor]\n\n modified_alert = factors.pipe(test_alert, pipeline)\n\n assert modified_alert.username == test_alert.username\n assert modified_alert.severity == 'WARNING'\n assert len(modified_alert.factors) == 1\n assert 'asn_hops' in modified_alert.factors[0]\n assert len(modified_alert.factors[0]['asn_hops']) == 2\n\n asn_key = 'autonomous_system_organization'\n asn1 = modified_alert.factors[0]['asn_hops'][0][0][asn_key]\n asn2 = modified_alert.factors[0]['asn_hops'][0][1][asn_key]\n asn3 = modified_alert.factors[0]['asn_hops'][1][0][asn_key]\n asn4 = modified_alert.factors[0]['asn_hops'][1][1][asn_key]\n\n assert asn1 == 'CLOUDFLARENET'\n assert asn2 == 'MOZILLA_SFO1'\n assert asn3 == 'MOZILLA_SFO1'\n assert asn4 == 'AMAZONAWSNET'\n","repo_name":"mozilla/MozDef","sub_path":"tests/alerts/geomodel/test_factors.py","file_name":"test_factors.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","stars":2170,"dataset":"github-code","pt":"61"}
+{"seq_id":"24666056054","text":"\"\"\"For interacting with the Discord API\"\"\"\n\nimport asyncio\nimport logging\nfrom urllib.parse import quote\n\nimport aiohttp\nimport hikari\nfrom sanic.exceptions import BadRequest, NotFound\n\nfrom munchi.config import Config\nfrom munchi.db import Database\n\nconfig = Config()\ndb = Database().db\nrest = hikari.RESTApp()\n\n\nasync def get_guild(guild: int) -> dict:\n \"\"\"Get a guild (as bot)\"\"\"\n headers = {\"Authorization\": f\"Bot {config.token}\"}\n\n async with aiohttp.ClientSession() as session:\n async with await session.get(\n f\"https://discord.com/api/v10/guilds/{guild}?with_counts=true\",\n headers=headers,\n ) as resp:\n resp.raise_for_status()\n data = await resp.json()\n\n async with await session.get(\n f\"https://discord.com/api/v10/guilds/{guild}/channels\",\n headers=headers,\n ) as resp:\n resp.raise_for_status()\n data[\"channels\"] = await resp.json()\n\n return data\n\n\nasync def get_user_guild(guild_id, token) -> dict:\n \"\"\"Get a user's guild via the bot (Uses user's token to check if bot is in guild)\"\"\"\n async with rest.acquire(token) as client:\n g = None\n\n # Check if user has and can manage guild\n for guild in await client.fetch_my_guilds():\n if guild.my_permissions.all(guild.my_permissions.MANAGE_GUILD) and str(\n guild.id\n ) == str(guild_id):\n g = guild\n break\n\n if not g:\n return\n\n # Get guild information from bot\n return await get_guild(guild_id)\n\n\nasync def get_token(code: str) -> str:\n \"\"\"Get token from code\"\"\"\n async with aiohttp.ClientSession() as session:\n async with await session.post(\n \"https://discord.com/api/v10/oauth2/token\",\n data={\n \"client_id\": config.application_id,\n \"client_secret\": config.client_secret,\n \"grant_type\": \"authorization_code\",\n \"code\": code,\n \"redirect_uri\": config.redirect_uri,\n },\n ) as resp:\n logging.debug(\"ERROR\", await resp.json())\n\n if resp.status != 200:\n raise BadRequest(str(await resp.json()))\n\n return (await resp.json())[\"access_token\"]\n\n\nasync def member_in_guild(guild: int, member: int) -> bool:\n \"\"\"Check if member is in guild\"\"\"\n # TODO: Use v10 API (I don't know how to do this with intents yet)\n headers = {\"Authorization\": f\"Bot {config.token}\"}\n\n async with aiohttp.ClientSession() as session:\n async with await session.get(\n f\"https://discord.com/api/v6/guilds/{guild}/members/{member}\",\n headers=headers,\n ) as resp:\n if resp.status in (403, 404):\n return False\n\n resp.raise_for_status()\n\n return True\n\n\nasync def get_user_guild_and_db(guild_id, token):\n guild = await get_user_guild(guild_id, token)\n\n if not guild:\n raise NotFound(\"Guild not found\")\n\n query = {\"guild\": guild_id}\n server = await db[\"server\"].find_one(query)\n\n if not server:\n await db[\"server\"].insert_one(query)\n server = await db[\"server\"].find_one(query)\n\n return guild, server, query\n\n\nasync def process_reaction_message(message):\n channel_id = message[\"channel\"]\n message_id = message[\"message\"]\n reactions = message[\"roles\"]\n\n for reaction in reactions.keys():\n headers = {\"Authorization\": f\"Bot {config.token}\"}\n\n status = None\n\n async with aiohttp.ClientSession() as session:\n # Retry in case of rate limit\n while not status or status == 429:\n status = (\n await session.put(\n f\"https://discord.com/api/v10/channels/{channel_id}/messages/{message_id}/reactions/{quote(reaction)}/@me\",\n headers=headers,\n )\n ).status\n\n asyncio.sleep(0.25)\n","repo_name":"wxllow/munchi","sub_path":"dashboard/backend/discord.py","file_name":"discord.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"285077033","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras import backend as K\nK.set_image_dim_ordering('th')\nimport matplotlib.pyplot as plt\nfrom scipy import io as spio\nimport numpy as np\n\n\n# In[2]:\n\n\n#loading data\nemnist = spio.loadmat(\"Data/emnist-letters.mat\")\n#Dataset structure \n#emnist[dataset][0][0][0][0][0][0] this is the array for the image pixel values\n#emnist[dataset][0][0][0][0][0][1] this is the array for the labels of the image\n#emnist[dataset][0][0][1][0][0][0] this is the array for the test image pixel values\n#emnist[dataset][0][0][1][0][0][1] this is the array for the labels of the test images\n\n\n# In[3]:\n\n\nx_train = emnist[\"dataset\"][0][0][0][0][0][0] #training images\nx_train = x_train.astype(np.float32)\ny_train = emnist[\"dataset\"][0][0][0][0][0][1] #training labels\n\n\n# In[4]:\n\n\nx_test = emnist[\"dataset\"][0][0][1][0][0][0] #test images\nx_test = x_test.astype(np.float32)\ny_test = emnist[\"dataset\"][0][0][1][0][0][1] #test labels\n\n\n# In[5]:\n\n\ntrain_labels = y_train\ntest_labels = y_test\n\n\n# In[6]:\n\n\n#normalize the test and train \nx_train /= 255\nx_test /= 255\n\n\n# In[7]:\n\n\nx_train.shape[0]\n\n\n# In[8]:\n\n\nx_test.shape[0]\n\n\n# In[9]:\n\n\nx_train = x_train.reshape(x_train.shape[0], 1, 28, 28, order = \"A\")\nx_test = x_test.reshape(x_test.shape[0], 1, 28, 28, order = \"A\")\n\n\n# In[10]:\n\n\nx_train.shape\n\n\n# In[11]:\n\n\ny_train.shape\n\n\n# In[12]:\n\n\n#encode the labels aka make it into an array of zeros and ones\ny_train = np_utils.to_categorical(y_train)\ny_test = np_utils.to_categorical(y_test)\n\n\n# In[13]:\n\n\ny_train.shape\n\n\n# In[14]:\n\n\ny_train[0]\n\n\n# In[20]:\n\n\n#confirm the data is loaded correctly\nsample = 5437\nimg = x_train[sample]\nplt.imshow(img[0], cmap = 'gray')\n\n\n# In[21]:\n\n\n#confirm label is correct\ntrain_labels[sample][0]\n\n\n# In[23]:\n\n\nnum_classes = y_test.shape[1]\n\n\n# In[26]:\n\n\n#create model\nmodel = Sequential()\nlayer1 = Conv2D(30,(5,5), input_shape = (1,28,28), activation = 'relu', name = 'layer1')\nmodel.add(layer1)\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nlayer2 = Conv2D(15, (3,3), activation='relu', name = 'layer2')\nmodel.add(layer2)\nmodel.add(MaxPooling2D(pool_size = (2,2)))\nmodel.add(Dropout(0.2))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation = 'relu'))\nmodel.add(Dense(50, activation = 'relu'))\nmodel.add(Dense(num_classes, activation='softmax'))\n#compile model\nmodel.compile(loss = 'categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\nmodel.summary()\n\n\n# In[36]:\n\n\nmodel.fit(x_train, y_train, validation_data=(x_test, y_test), epochs = 6, batch_size = 1000)\n\n\n# In[37]:\n\n\nscores = model.evaluate(x_test, y_test, verbose=0)\nprint(\"Large CNN Error = %.2f%%\" % (100-scores[1]*100))\n\n","repo_name":"holdenDuncan/SLUAVLegacyCode","sub_path":"imageProcessing/classification/EMNIST.py","file_name":"EMNIST.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"34970789693","text":"from src.ui.parameter_ui_challenge_simulation import Parameter_UI\nfrom src.models.arena import Arena\nfrom src.models.fish import Fish\nfrom src.models.leader_robot import LeaderRobot\nfrom src.models.agent import (\n attract,\n repulse,\n align,\n check_in_radii_vision,\n normalize,\n get_zone_neighbours,\n)\nfrom src.util.util import Util\nfrom src.util.serialize import serialize\n\nimport random\nimport time\nimport queue\nimport os\nimport sys\nimport logging\nimport numpy as np\nimport yaml # pyyaml\nfrom pathlib import Path\nfrom scipy.spatial import distance_matrix\nfrom logging.handlers import TimedRotatingFileHandler\nfrom datetime import datetime\n\npath_root = Path(__file__).parents[1]\nsys.path.append(str(path_root))\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import pyqtSignal, QObject\n\nFORMAT = \"\\t%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n\n# setup logging\nlogging.basicConfig(format=FORMAT, level=logging.INFO)\nnumba_logger = logging.getLogger(\"numba\")\nnumba_logger.setLevel(logging.WARNING)\n\nnp.warnings.filterwarnings(\"error\", category=np.VisibleDeprecationWarning)\n\n\nclass Behavior(QObject):\n \"\"\"\n Controller class of the challenge simulation. In the event loop, it handles the agents movement.\n This class does not connect to RoboTracker or Unity.\n \"\"\"\n\n update_positions = pyqtSignal(list, name=\"update_positions\")\n update_ellipses = pyqtSignal(LeaderRobot, list, name=\"update_ellipses\")\n\n def __init__(self, layout=None, DEBUG_VIS=None, config=None):\n super().__init__()\n\n self.world = None\n self.target = None\n\n self.parameter_ui = None\n\n # load config\n self.config = config\n if self.config is None:\n path = (Path(__file__).parents[1]) / \"cfg/config.yml\"\n logging.info(f\"BEHAVIOR: config path: {path}\")\n self.config = yaml.safe_load(open(path))\n # setup logging\n formatter = logging.Formatter(\n \"\\t%(asctime)s - %(name)s - %(levelname)s - %(message)s\"\n )\n\n logger = logging.getLogger()\n handler = TimedRotatingFileHandler(\n Path.home() / self.config[\"LOGGING\"][\"BEHAVIOR\"], when=\"H\", interval=1\n )\n handler.setFormatter(formatter)\n handler.setLevel(logging.INFO)\n logger.addHandler(handler)\n\n # setup util\n self.util = Util(self.config)\n # setup debug visualization\n self.debug_vis = DEBUG_VIS\n\n # setup default parameters\n self.default_num_fish = self.config[\"DEFAULTS\"][\"number_of_fish\"]\n self.optimisation = self.config[\"DEBUG\"][\"optimisation\"]\n\n self.zoa = self.config[\"DEFAULTS\"][\"zoa\"]\n self.zoo = self.config[\"DEFAULTS\"][\"zoo\"]\n self.zor = self.config[\"DEFAULTS\"][\"zor\"]\n\n # time step in seconds\n self.time_step = self.config[\"DEFAULTS\"][\"time_step\"]\n\n # logging\n self.setup_logging()\n\n # arena\n self.arena = Arena(\n [0, 0], self.config[\"ARENA\"][\"width\"], self.config[\"ARENA\"][\"height\"]\n )\n self.middle_pos = [self.arena.width / 2, self.arena.height / 2]\n self.middle_pos_cm = self.util.map_px_to_cm(self.middle_pos)\n\n # initialize robot\n self.behavior_robot = LeaderRobot(self.arena, self.config)\n # self.controlled = False\n self.trigger_next_robot_step = False\n self.flush_robot_target = False\n self.action = []\n self.just_started = False\n\n # initialize fish\n self.reset_fish(self.config[\"DEFAULTS\"][\"number_of_fish\"])\n\n # numba\n self.initiate_numba()\n\n self.parent_layout = (\n layout if self.debug_vis is not None else self.setup_parameter_layout()\n )\n\n # setup parameter ui widget\n self.setup_parameter_ui() # fill parameter layout\n\n # step logger\n self._step_logger = []\n self.exec_time = 0\n self.exec_stepper = 0\n\n self.last_time = datetime.now()\n\n # setup command queue\n self.com_queue = queue.LifoQueue()\n\n # setup debug vis\n if self.debug_vis is not None:\n self.setup_debug_vis()\n\n # catch key events\n if self.debug_vis is not None:\n app = QApplication.instance()\n app.installEventFilter(self)\n self.movelist = []\n\n self.turn_left = False\n self.turn_right = False\n\n logging.info(\"Behavior: Initialized!\")\n\n def initiate_numba(self) -> None:\n \"\"\"\n Initially executes reused functions sped up by JIT compiler numba\n \"\"\"\n repulse(np.asarray([[0.0, 0.0]]), np.asarray([0, 0]))\n align(np.asarray([[0.0, 0.0]]))\n attract(np.asarray([[0.0, 0.0]]), np.asarray([0, 0]))\n check_in_radii_vision(\n np.asarray([[0.0, 0.0]]),\n np.asarray([[0.0, 0.0]]),\n np.asarray([[0.0, 0.0]]),\n 0.0,\n np.asarray([0.0, 0.0]),\n np.asarray([0.0, 0.0]),\n )\n get_zone_neighbours(\n np.asarray([1.4, 2.0, 43.0321, 4214.3123, 2.5]),\n np.zeros((5, 2)),\n np.zeros((5, 2)),\n 10,\n 50,\n 150,\n )\n normalize(np.asarray([1.4, 2.0]))\n\n def setup_logging(self) -> None:\n now = datetime.now()\n formatter = logging.Formatter(\"%(asctime)s -8s %(message)s\")\n self.fish_logger = logging.getLogger(\"fish_logger\")\n fish_handler = TimedRotatingFileHandler(\n Path.home() / self.config[\"LOGGING\"][\"FISH\"], when=\"H\", interval=1\n )\n fish_handler.setFormatter(formatter)\n # handler.setLevel(logging.CRITICAL)\n self.fish_logger.addHandler(fish_handler)\n self.fish_logger.warning(f\"Started a new behavior: {now}\")\n self.fish_logger.propagate = False\n\n self.logcounter = 0\n\n def setup_parameter_layout(self):\n logging.info(\"Behavior: Setting up parameter layout\")\n self.app = QApplication(sys.argv)\n layout = QVBoxLayout()\n\n title_label = QLabel(\"Parameter Window
\")\n layout.addWidget(title_label)\n title_label.move(60, 15)\n\n self.window = QWidget()\n self.window.setWindowTitle(\"Parameter window\")\n self.window.setGeometry(100, 100, 200, 200)\n self.window.move(60, 15)\n self.window.setLayout(layout)\n self.window.show()\n\n return layout\n\n def setup_debug_vis(self) -> None:\n self.debug_vis.setArena(self.arena)\n\n def setup_parameter_ui(self) -> None:\n logging.info(\"Behavior: Setting up parameter ui\")\n self.parameter_ui = Parameter_UI(self, False, self.config)\n #\n self.parent_layout.addLayout(self.parameter_ui)\n\n #\n # looping method\n #\n\n def next_speeds(self, robots, fish, timestep):\n \"\"\"\n looping method:\n - the simulation agents are managed\n \"\"\"\n try:\n if self.optimisation:\n start_time = time.time()\n\n try:\n # execute all commands in queue first\n while not (self.com_queue.empty()):\n command = self.com_queue.get()\n if self.config[\"DEBUG\"][\"console\"]:\n logging.info(command)\n try:\n func = getattr(self, command[0])\n args = command[1:]\n func(*args)\n except Exception as e:\n logging.error(\n f\"BEHAVIOR: Command not found or error in command execution! {command}\"\n )\n logging.error(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logging.error(exc_type, fname, exc_tb.tb_lineno)\n\n except Exception as e:\n logging.error(f\"BEHAVIOR: Error in command queue\")\n logging.error(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logging.error(exc_type, fname, exc_tb.tb_lineno)\n\n # TICK - update all fish one time step forward (tick)\n try:\n all_agents = [self.behavior_robot]\n all_agents.extend(self.allfish)\n all_pos = np.asarray(\n [np.array(a.pos, dtype=np.float64) for a in all_agents]\n )\n all_dir = np.asarray([a.dir for a in all_agents])\n dist_m = distance_matrix(all_pos, all_pos)\n\n for id_f, f in enumerate(all_agents):\n f.tick(all_pos, all_dir, dist_m[id_f])\n # check if fish following the robot\n if id_f != 0:\n robot_pos = all_pos[0]\n robot_dir = all_dir[0]\n f.check_following(robot_pos, robot_dir)\n except Exception as e:\n logging.error(f\"BEHAVIOR: Error in tick\")\n logging.error(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logging.error(exc_type, fname, exc_tb.tb_lineno)\n\n # MOVE - move everything by new updated direction and speed\n try:\n try:\n for f in all_agents:\n f.move()\n except Exception as e:\n logging.error(f\"BEHAVIOR: Error in all agents move\")\n logging(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logging.error(exc_type, fname, exc_tb.tb_lineno)\n\n except Exception as e:\n logging.error(f\"BEHAVIOR: Error in move\")\n logging.error(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logging.error(exc_type, fname, exc_tb.tb_lineno)\n\n # Update fish in tracking view and send positions\n serialized = serialize(self.behavior_robot, self.allfish)\n self.update_positions.emit(serialized)\n\n # log fish every few ticks when user controlled\n if self.behavior_robot.user_controlled:\n if self.logcounter == 5:\n self.fish_logger.info(f\"{serialized}\")\n self.logcounter = 0\n self.logcounter += 1\n\n if self.optimisation:\n end_time = time.time()\n exec_time = end_time - start_time\n\n if self.exec_stepper == 100:\n self.exec_stepper = 0\n self.exec_time = 0\n self.exec_stepper += 1\n self.exec_time += exec_time\n mean_exec_time = self.exec_time / self.exec_stepper\n logging.info(\n f\"mean tick takes {mean_exec_time} seconds; last tick took {exec_time} seconds\"\n )\n\n except Exception as e:\n logging.error(f\"BEHAVIOR: Error in next_speeds!\")\n logging.error(e)\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n logging.error(exc_type, fname, exc_tb.tb_lineno)\n\n def run_thread(self) -> None:\n timestep = 0\n while True:\n self.next_speeds([], [], timestep)\n timestep += 1\n time.sleep(self.time_step)\n\n def __del__(self) -> None:\n pass\n\n def app_exec(self) -> None:\n sys.exit(self.app.exec_())\n\n def serialize(self) -> list:\n out = []\n # robot\n robo_dict = {\n \"id\": self.behavior_robot.id,\n \"orientation\": np.around(self.behavior_robot.ori, decimals=2),\n \"position\": np.rint(self.behavior_robot.pos).tolist(),\n }\n out.append(robo_dict)\n # fish\n for a in self.allfish:\n fish_dict = {\n \"id\": a.id,\n \"orientation\": np.around(a.ori, decimals=2),\n \"position\": np.rint(a.pos).tolist(),\n \"following\": a.following,\n \"repulsed\": a.repulsed,\n }\n # out.append([np.rint(a.pos).tolist(), np.around(a.ori, decimals=2), a.id])\n out.append(fish_dict)\n\n return out\n\n def queue_command(self, command) -> None:\n self.com_queue.put((command[0], command[1]))\n\n #\n # Commands\n #\n # region \n def reset_fish(self, num) -> None:\n \"\"\"\n Receive position reset for current fish\n \"\"\"\n self.allfish = [\n Fish(\n id=i + 1,\n pos=np.asarray(\n [\n random.randint(1, self.arena.width - 1),\n random.randint(1, self.arena.height - 1),\n ]\n ),\n ori=random.randint(0, 360),\n arena=self.arena,\n config=self.config,\n dir=None,\n zor=self.zor,\n zoo=self.zoo,\n zoa=self.zoa,\n )\n for i in range(num)\n ]\n\n # always set fish with id 1 to position 1500,500 if existing\n if len(self.allfish) > 0:\n if self.allfish[0].id == 1:\n self.allfish[0].pos = np.asarray([1500, 500])\n else:\n logging.error(\"BEHAVIOR: Fish with id 1 not existing!\")\n\n self.update_ellipses.emit(self.behavior_robot, self.allfish)\n if self.parameter_ui:\n self.parameter_ui.num_fish_spinbox.setValue(num)\n\n def control_robot(self, flag) -> None:\n \"\"\"\n Receive robot user control trigger\n \"\"\"\n self.behavior_robot.controlled = flag\n self.controlled = flag\n self.behavior_robot.user_controlled = flag\n\n if not flag:\n self.behavior_robot.max_speed = self.config[\"DEFAULTS\"][\"max_speed\"]\n self.behavior_robot.stop = False\n\n def change_robodir(self, dir):\n \"\"\"\n - receives joystick input and translates it into robot direction\n - dir cannot be [0,0]\n \"\"\"\n # dir cannot be [0,0]\n if not (np.abs(dir) == np.asarray([0.0, 0.0])).all():\n self.behavior_robot.stop = False\n np_dir = np.asarray(dir)\n dir_len = np.linalg.norm(np_dir)\n self.behavior_robot.max_speed = self.config[\"DEFAULTS\"][\"max_speed\"] + 10\n self.behavior_robot.new_dir = (\n np_dir / dir_len if dir_len != 0 and dir_len > 1 else np_dir\n )\n else:\n self.behavior_robot.max_speed = 0\n self.behavior_robot.stop = True\n\n def change_zones(self, zone_dir):\n \"\"\"\n Change zone radii for all agents\n \"\"\"\n self.zor = zone_dir.get(\"zor\", self.zor)\n self.zoo = zone_dir.get(\"zoo\", self.zoo)\n self.zoa = zone_dir.get(\"zoa\", self.zoa)\n\n self.behavior_robot.change_zones(self.zor, self.zoo, self.zoa)\n for f in self.allfish:\n f.change_zones(self.zor, self.zoo, self.zoa)\n\n if self.debug_vis:\n self.update_ellipses.emit(self.behavior_robot, self.allfish)\n\n self.parameter_ui.zor_spinbox.setValue(self.zor)\n self.parameter_ui.zoo_spinbox.setValue(self.zoo)\n self.parameter_ui.zoa_spinbox.setValue(self.zoa)\n\n def set_zone_preset(self, size):\n \"\"\"\n Change zone radii for all agents to preset\n \"\"\"\n if size == 0:\n self.zor = self.config[\"ZONE_MODES\"][\"SMALL\"][\"zor\"]\n self.zoo = self.config[\"ZONE_MODES\"][\"SMALL\"][\"zoo\"]\n self.zoa = self.config[\"ZONE_MODES\"][\"SMALL\"][\"zoa\"]\n\n if size == 1:\n self.zor = self.config[\"ZONE_MODES\"][\"LARGE\"][\"zor\"]\n self.zoo = self.config[\"ZONE_MODES\"][\"LARGE\"][\"zoo\"]\n self.zoa = self.config[\"ZONE_MODES\"][\"LARGE\"][\"zoa\"]\n\n if size == 2:\n self.zor = self.config[\"ZONE_MODES\"][\"CHALL\"][\"zor\"]\n self.zoo = self.config[\"ZONE_MODES\"][\"CHALL\"][\"zoo\"]\n self.zoa = self.config[\"ZONE_MODES\"][\"CHALL\"][\"zoa\"]\n\n for f in self.allfish:\n f.change_zones(self.zor, self.zoo, self.zoa)\n\n if self.debug_vis:\n self.update_ellipses.emit(self.behavior_robot, self.allfish)\n\n self.parameter_ui.zor_spinbox.setValue(self.zor)\n self.parameter_ui.zoo_spinbox.setValue(self.zoo)\n self.parameter_ui.zoa_spinbox.setValue(self.zoa)\n\n def set_speed(self, speed):\n \"\"\"\n Set speed of all fish\n \"\"\"\n for f in self.allfish:\n if f.id != 0:\n f.max_speed = speed\n\n def challenge_status(self, toggle):\n \"\"\"\n Receive challenge status update\n \"\"\"\n status = \"started!\" if toggle == 1 else \"stopped!\"\n logging.info(f\"Challenge {status}\")\n\n # endregion\n","repo_name":"jotpio/behavior_HF","sub_path":"src/challenge_simulation.py","file_name":"challenge_simulation.py","file_ext":"py","file_size_in_byte":17272,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16368815613","text":"from flask_restful import Resource, reqparse\nfrom flask_jwt import jwt_required\nfrom models.user import UserModel\n\n\nclass User(Resource):\n parse = reqparse.RequestParser()\n parse.add_argument(\n \"unique_name\",\n type=str,\n required=True,\n help=\"This field cannot be empty!\",\n )\n parse.add_argument(\n \"first_name\",\n type=str,\n required=True,\n help=\"This field cannot be empty\",\n )\n parse.add_argument(\n \"last_name\",\n type=str,\n required=True,\n help=\"This field cannot be empty\",\n )\n parse.add_argument(\n \"is_admin\",\n type=bool,\n required=True,\n help=\"This field cannot be empty\",\n )\n parse.add_argument(\n \"password\",\n type=str,\n required=True,\n help=\"This field cannot be empty\",\n )\n\n @jwt_required()\n def get(self, unique_name):\n user = UserModel.find_by_unique_name(unique_name)\n if user:\n return user.json()\n return {\"message\": \"User not found.\"}\n\n @jwt_required()\n def delete(self, unique_name):\n user = UserModel.find_by_unique_name(unique_name)\n if user:\n user.delete_from_db()\n return {\"message\": \"User deleted.\"}, 200\n\n @jwt_required()\n def put(self, unique_name):\n data = User.parse.parse_args()\n user = UserModel.find_by_unique_name(unique_name)\n if user:\n if user.password != data[\"password\"]:\n return {\"message\": \"Password does not match\"}\n\n user.name = data[\"name\"]\n user.first_name = data[\"first_name\"]\n user.last_name = data[\"last_name\"]\n user.is_admin = data[\"is_admin\"]\n user.save_to_db()\n else:\n return {\"message\": \"Please register first\"}\n return user.json(), 202\n\n\nclass UserRegister(Resource):\n \"\"\"\n Handle new users register\n \"\"\"\n\n parse = reqparse.RequestParser()\n parse.add_argument(\n \"unique_name\",\n type=str,\n required=True,\n help=\"This field cannot be empty!\",\n )\n parse.add_argument(\n \"first_name\",\n type=str,\n required=True,\n help=\"This field cannot be empty\",\n )\n parse.add_argument(\n \"last_name\",\n type=str,\n required=True,\n help=\"This field cannot be empty\",\n )\n parse.add_argument(\n \"is_admin\",\n type=bool,\n required=True,\n help=\"This field cannot be empty\",\n )\n parse.add_argument(\n \"password\",\n type=str,\n required=True,\n help=\"This field cannot be empty\",\n )\n\n def post(self):\n data = UserRegister.parse.parse_args()\n if UserModel.find_by_unique_name(data[\"unique_name\"]):\n return {\"message\": \"User already exists\"}\n\n # user = UserModel(\n # data[\"unique_name\"],\n # data[\"name\"],\n # data[\"first_name\"],\n # data[\"is_admin\"],\n # data[\"password\"],\n # )\n user = UserModel(**data)\n user.save_to_db()\n\n return {\"message\": \"User created successfully\"}, 202\n","repo_name":"iteemhe/office-hours-queue","sub_path":"api/resources/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"6568266115","text":"__author__ = 'Rakatak'\n# given values\n\ndef egcd(a, b):\n x,y, u,v = 0,1, 1,0\n while a != 0:\n q, r = b//a, b%a\n m, n = x-u*q, y-v*q\n b,a, x,y, u,v = a,r, u,v, m,n\n gcd = b\n return gcd, x, y\n\ndef modinv(a, m):\n gcd, x, y = egcd(a, m)\n if gcd != 1:\n return None # modular inverse does not exist\n else:\n return x % m\n\np = 41\nq = 17\ne = 39\nm = 9\n\nn = p * q\nprint(\"n = \" + str(n))\nphiN = (p - 1) * (q - 1)\nprint(\"phiN = \" + str(phiN))\nd = modinv(e, phiN)\nprint(\"Inverse to phiN and e is \" + str(d))\nprint(\"d = \" + str(d))\nvalueOne = (d*e) % phiN\nprint(\"valueOne = \" + str(valueOne))\nprint(\"Public key is (e, n) => (3, \" + str(n) + \")\")\nprint(\"Private key is (d, n) => (27, \" + str(n) + \")\")\nc = m**e % n\nprint(\"Encrypted Message of 9 is \" + str(c))\ndM = c**d % n\nprint(\"Decrypted Message of \" + str(c) + \" is \" + str(dM))\n","repo_name":"Rakatak/SichereVerteilteSysteme","sub_path":"A3/RSAExp.py","file_name":"RSAExp.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"894084895","text":"# library doc string\n\n\n# import libraries\nimport shap\nimport joblib\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns; sns.set()\n\nfrom sklearn.preprocessing import normalize\nfrom sklearn.model_selection import train_test_split\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.metrics import plot_roc_curve, classification_report\n\n\ndef import_data(pth):\n '''\n returns dataframe for the csv found at pth\n\n input:\n pth: a path to the csv\n output:\n df: pandas dataframe\n '''\n df = pd.read_csv(pth)\n df['Churn'] = df['Attrition_Flag'].apply(lambda val: 0 if val == \"Existing Customer\" else 1)\n return df\n\n\ndef perform_eda(df):\n '''\n perform eda on df and save figures to images folder\n input:\n df: pandas dataframe\n\n output:\n None\n '''\n df['Churn'] = df['Attrition_Flag'].apply(lambda val: 0 if val == \"Existing Customer\" else 1)\n plt.figure(figsize=(20,10)) \n df['Churn'].hist();\n plt.savefig('./images/churn.png')\n\n plt.figure(figsize=(20,10))\n df['Customer_Age'].hist();\n plt.savefig('./images/test.png')\n \n\n\ndef encoder_helper(df, category_lst, response='Churn'):\n '''\n helper function to turn each categorical column into a new column with\n propotion of churn for each category - associated with cell 15 from the notebook\n\n input:\n df: pandas dataframe\n category_lst: list of columns that contain categorical features\n response: string of response name [optional argument that could be used for naming variables or index y column]\n\n output:\n df: pandas dataframe with new columns for\n '''\n for category in category_lst:\n category_list=[]\n category_groups = df.groupby(category).mean()['Churn']\n\n for val in df[category]:\n category_list.append(category_groups.loc[val])\n \n df[category+'_'+response] = category_list\n return df\n\n\ndef perform_feature_engineering(df, response=['Customer_Age', 'Dependent_count', 'Months_on_book',\n 'Total_Relationship_Count', 'Months_Inactive_12_mon',\n 'Contacts_Count_12_mon', 'Credit_Limit', 'Total_Revolving_Bal',\n 'Avg_Open_To_Buy', 'Total_Amt_Chng_Q4_Q1', 'Total_Trans_Amt',\n 'Total_Trans_Ct', 'Total_Ct_Chng_Q4_Q1', 'Avg_Utilization_Ratio',\n 'Gender_Churn', 'Education_Level_Churn', 'Marital_Status_Churn', \n 'Income_Category_Churn', 'Card_Category_Churn']):\n '''\n input:\n df: pandas dataframe\n response: string of response name [optional argument that could be used for naming variables or index y column]\n\n output:\n X_train: X training data\n X_test: X testing data\n y_train: y training data\n y_test: y testing data\n '''\n y = df['Churn']\n X_data = pd.DataFrame()\n X_data[response] = df[response]\n model_dict = dict()\n X_data_2 = X_data\n X_train, X_test, y_train, y_test = train_test_split(X_data, y, test_size= 0.3, random_state=42)\n \n model_dict['X_train']=X_train\n model_dict['X_test']=X_test\n model_dict['y_train']=y_train\n model_dict['y_test']=y_test\n \n return (model_dict, X_data_2)\n\ndef classification_report_image(y_train,\n y_test,\n y_train_preds_lr,\n y_train_preds_rf,\n y_test_preds_lr,\n y_test_preds_rf,\n output_pth):\n '''\n produces classification report for training and testing results and stores report as image\n in images folder\n input:\n y_train: training response values\n y_test: test response values\n y_train_preds_lr: training predictions from logistic regression\n y_train_preds_rf: training predictions from random forest\n y_test_preds_lr: test predictions from logistic regression\n y_test_preds_rf: test predictions from random forest\n\n output:\n None\n '''\n\n plt.clf()\n plt.rc('figure', figsize=(5, 5))\n plt.text(0.01, 1, str('Random Forest Train Results'), {\n 'fontsize': 10}, fontproperties='monospace')\n \n plt.text(0.01, 0.7, str(classification_report(y_test, y_test_preds_rf)), {\n 'fontsize': 10}, fontproperties='monospace') # approach improved by OP -> monospace!\n \n plt.text(0.01, 0.6, str('Random Forest Test Results'), {\n 'fontsize': 10}, fontproperties='monospace')\n \n plt.text(0.01, 0.3, str(classification_report(y_train, y_train_preds_rf)), {\n 'fontsize': 10}, fontproperties='monospace') # approach improved by OP -> monospace!\n \n plt.text(0.6, 1, str('Logistic Regression Train Results'), {\n 'fontsize': 10}, fontproperties='monospace')\n \n plt.text(0.6, 0.7, str(classification_report(y_train, y_train_preds_lr)), {\n 'fontsize': 10}, fontproperties='monospace') # approach improved by OP -> monospace!\n \n plt.text(0.6, 0.6, str('Logistic Regression Test Results'), {\n 'fontsize': 10}, fontproperties='monospace')\n \n plt.text(0.6, 0.3, str(classification_report(y_test, y_test_preds_lr)), {\n 'fontsize': 10}, fontproperties='monospace') # approach improved by OP -> monospace!\n\n plt.savefig(output_pth + 'model_results.png')\n \ndef feature_importance_plot(cv_rfc, X_data, output_pth):\n '''\n creates and stores the feature importances in pth\n input:\n model: model object containing feature_importances_\n X_data: pandas dataframe of X values\n output_pth: path to store the figure\n\n output:\n None\n '''\n \n # Calculate feature importances\n importances = cv_rfc.best_estimator_.feature_importances_\n # importances = model.feature_importances_\n # Sort feature importances in descending order\n indices = np.argsort(importances)[::-1]\n\n # Rearrange feature names so they match the sorted feature importances\n names = [X_data.columns[i] for i in indices]\n\n # Create plot\n plt.figure(figsize=(20,5))\n\n # Create plot title\n plt.title(\"Feature Importance\")\n plt.ylabel('Importance')\n\n # Add bars\n plt.bar(range(X_data.shape[1]), importances[indices])\n\n # Add feature names as x-axis labels\n plt.xticks(range(X_data.shape[1]), names, rotation=90)\n # plt.subplots_adjust(bottom=.15)\n # Save Plot\n plt.savefig(output_pth + 'features.png')\n\ndef train_models(feature_engineering_dict):\n '''\n train, store model results: images + scores, and store models\n input:\n X_train: X training data\n X_test: X testing data\n y_train: y training data\n y_test: y testing data\n output:\n None\n '''\n X_train = feature_engineering_dict['X_train']\n X_test = feature_engineering_dict['X_test']\n y_train = feature_engineering_dict['y_train']\n y_test = feature_engineering_dict['y_test']\n\n # grid search\n rfc = RandomForestClassifier(random_state=42)\n lrc = LogisticRegression(solver='lbfgs', max_iter=3000)\n\n param_grid = { \n 'n_estimators': [200, 500],\n 'max_features': ['auto', 'sqrt'],\n 'max_depth' : [4,5,100],\n 'criterion' :['gini', 'entropy']\n }\n\n cv_rfc = GridSearchCV(estimator=rfc, param_grid=param_grid, cv=5)\n cv_rfc.fit(X_train, y_train)\n\n lrc.fit(X_train, y_train)\n\n y_train_preds_rf = cv_rfc.best_estimator_.predict(X_train)\n y_test_preds_rf = cv_rfc.best_estimator_.predict(X_test)\n\n y_train_preds_lr = lrc.predict(X_train)\n y_test_preds_lr = lrc.predict(X_test)\n\n lrc_plot = plot_roc_curve(lrc, X_test, y_test)\n plt.savefig('./images/model_1.png')\n # plots\n plt.figure(figsize=(15, 8))\n ax = plt.gca()\n rfc_disp = plot_roc_curve(cv_rfc.best_estimator_, X_test, y_test, ax=ax, alpha=0.8)\n lrc_plot.plot(ax=ax, alpha=0.8)\n plt.savefig('./images/model_2.png')\n\n \n # save best model\n joblib.dump(cv_rfc.best_estimator_, './models/rfc_model.pkl')\n joblib.dump(lrc, './models/logistic_model.pkl')\n \n rfc_model = joblib.load('./models/rfc_model.pkl')\n lr_model = joblib.load('./models/logistic_model.pkl')\n\n lrc_plot = plot_roc_curve(lr_model, X_test, y_test)\n plt.savefig('./images/model_3.png')\n\n plt.figure(figsize=(15, 8))\n ax = plt.gca()\n rfc_disp = plot_roc_curve(rfc_model, X_test, y_test, ax=ax, alpha=0.8)\n lrc_plot.plot(ax=ax, alpha=0.8)\n plt.savefig('./images/model_4.png')\n \n \n return y_train, y_test, y_train_preds_lr, y_train_preds_rf, y_test_preds_lr, y_test_preds_rf, rfc_model, lr_model, cv_rfc\nif __name__ == \"__main__\":\n df = import_data('./data/bank_data.csv')\n perform_eda(import_data('./data/bank_data.csv'))\n category_list=['Gender','Education_Level','Marital_Status','Income_Category','Card_Category']\n df = (encoder_helper(df,category_list))\n model_dict, X_data = perform_feature_engineering(df)\n a,b,c,d,e,f,rfc_model, lr_model, cv_rfc = train_models(model_dict)\n # classification_report_image(a,b,c,d,e,f,'./images/')\n feature_importance_plot(cv_rfc, X_data, './')\n","repo_name":"gonzalezpear/churn_udacity_project","sub_path":"churn_library.py","file_name":"churn_library.py","file_ext":"py","file_size_in_byte":10158,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"35621576079","text":"\"\"\"Provides verification helper methods\"\"\"\n\nfrom utility.hash_util import hash_block, hash_string_256\nfrom wallet import Wallet\n\n\nclass VerficationHelper:\n \n @staticmethod\n def valid_proof(transactions, last_hash, proof):\n guess = (str([tx.to_ordered_dict() for tx in transactions]) + str(last_hash) + str(proof)).encode() \n guess_hash = hash_string_256(guess)\n # print(guess_hash)\n return guess_hash[0:4] == '0000'\n\n @classmethod\n def verify_chain(cls, blockchain):\n for (index, block) in enumerate(blockchain):\n if index == 0:\n continue\n if block.previous_hash != hash_block(blockchain[index-1]):\n return False\n\n if not cls.valid_proof(block.trax[:-1], block.previous_hash, block.proof):\n print('Proof of work is invalid')\n return False\n return True\n\n @staticmethod\n def verify_trax(transaction, get_balance, check_funds=True):\n if check_funds == True:\n sender_balance = get_balance(transaction.tx_sender)\n return sender_balance >= transaction.tx_amount and Wallet.verify_traxSign(transaction)\n else:\n return Wallet.verify_traxSign(transaction)\n\n @classmethod\n def verify_allTrax(cls, open_trax, get_balance):\n return all([cls.verify_trax(el,get_balance, False) for el in open_trax])","repo_name":"MWaris97/Projects","sub_path":"FYP/source/TessChain/utility/verificationHelper.py","file_name":"verificationHelper.py","file_ext":"py","file_size_in_byte":1400,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"43348856698","text":"import json\nfrom pathlib import Path\nfrom unittest.mock import Mock\n\nimport pytest\nimport textwrap\nimport responses as rsps\nimport click\nfrom ruamel.yaml import YAML\n\nfrom archery.bot import (\n CommentBot, CommandError, CrossbowCommentFormatter, group\n)\n\n\n@pytest.fixture\ndef responses():\n with rsps.RequestsMock() as mock:\n yield mock\n\n\ndef load_fixture(name):\n path = Path(__file__).parent / 'fixtures' / name\n with path.open('r') as fp:\n if name.endswith('.json'):\n return json.load(fp)\n elif name.endswith('.yaml'):\n yaml = YAML()\n return yaml.load(fp)\n else:\n return fp.read()\n\n\ndef github_url(path):\n return 'https://api.github.com:443/{}'.format(path.strip('/'))\n\n\n@group()\ndef custom_handler():\n pass\n\n\n@custom_handler.command()\n@click.pass_obj\ndef extra(obj):\n return obj\n\n\n@custom_handler.command()\n@click.option('--force', '-f', is_flag=True)\ndef build(force):\n return force\n\n\n@custom_handler.command()\n@click.option('--name', required=True)\ndef benchmark(name):\n return name\n\n\ndef test_click_based_commands():\n assert custom_handler('build') is False\n assert custom_handler('build -f') is True\n\n assert custom_handler('benchmark --name strings') == 'strings'\n with pytest.raises(CommandError):\n assert custom_handler('benchmark')\n\n assert custom_handler('extra', extra='data') == {'extra': 'data'}\n\n\ndef test_crossbow_comment_formatter():\n job = load_fixture('crossbow-job.yaml')\n msg = load_fixture('crossbow-success-message.md')\n\n formatter = CrossbowCommentFormatter(crossbow_repo='ursa-labs/crossbow')\n response = formatter.render(job)\n expected = msg.format(\n repo='ursa-labs/crossbow',\n branch='ursabot-1',\n revision='f766a1d615dd1b7ee706d05102e579195951a61c',\n status='has been succeeded.'\n )\n assert response == textwrap.dedent(expected).strip()\n\n\n@pytest.mark.parametrize('fixture_name', [\n # the bot is not mentioned, nothing to do\n 'event-issue-comment-not-mentioning-ursabot.json',\n # don't respond to itself, it prevents recursive comment storms!\n 'event-issue-comment-by-ursabot.json',\n # non-authorized user sent the comment, do not respond\n 'event-issue-comment-by-non-authorized-user.json',\n])\ndef test_noop_events(fixture_name):\n payload = load_fixture(fixture_name)\n\n handler = Mock()\n bot = CommentBot(name='ursabot', token='', handler=handler)\n bot.handle('issue_comment', payload)\n\n handler.assert_not_called()\n\n\ndef test_issue_comment_without_pull_request(responses):\n responses.add(\n responses.GET,\n github_url('/repositories/169101701/issues/19'),\n json=load_fixture('issue-19.json'),\n status=200\n )\n responses.add(\n responses.GET,\n github_url('repos/ursa-labs/ursabot/pulls/19'),\n json={},\n status=404\n )\n responses.add(\n responses.POST,\n github_url('/repos/ursa-labs/ursabot/issues/19/comments'),\n json={}\n )\n\n def handler(command, **kwargs):\n pass\n\n payload = load_fixture('event-issue-comment-without-pull-request.json')\n bot = CommentBot(name='ursabot', token='', handler=handler)\n bot.handle('issue_comment', payload)\n\n post = responses.calls[2]\n assert json.loads(post.request.body) == {\n 'body': \"The comment bot only listens to pull request comments!\"\n }\n\n\ndef test_respond_with_usage(responses):\n responses.add(\n responses.GET,\n github_url('/repositories/169101701/issues/26'),\n json=load_fixture('issue-26.json'),\n status=200\n )\n responses.add(\n responses.GET,\n github_url('/repos/ursa-labs/ursabot/pulls/26'),\n json=load_fixture('pull-request-26.json'),\n status=200\n )\n responses.add(\n responses.GET,\n github_url('/repos/ursa-labs/ursabot/issues/comments/480243811'),\n json=load_fixture('issue-comment-480243811.json')\n )\n responses.add(\n responses.POST,\n github_url('/repos/ursa-labs/ursabot/issues/26/comments'),\n json={}\n )\n\n def handler(command, **kwargs):\n raise CommandError('test-usage')\n\n payload = load_fixture('event-issue-comment-with-empty-command.json')\n bot = CommentBot(name='ursabot', token='', handler=handler)\n bot.handle('issue_comment', payload)\n\n post = responses.calls[3]\n assert json.loads(post.request.body) == {'body': '```\\ntest-usage\\n```'}\n\n\n@pytest.mark.parametrize(('command', 'reaction'), [\n ('@ursabot build', '+1'),\n ('@ursabot listen', '-1'),\n])\ndef test_issue_comment_with_commands(responses, command, reaction):\n responses.add(\n responses.GET,\n github_url('/repositories/169101701/issues/26'),\n json=load_fixture('issue-26.json'),\n status=200\n )\n responses.add(\n responses.GET,\n github_url('/repos/ursa-labs/ursabot/pulls/26'),\n json=load_fixture('pull-request-26.json'),\n status=200\n )\n responses.add(\n responses.GET,\n github_url('/repos/ursa-labs/ursabot/issues/comments/480248726'),\n json=load_fixture('issue-comment-480248726.json')\n )\n responses.add(\n responses.POST,\n github_url(\n '/repos/ursa-labs/ursabot/issues/comments/480248726/reactions'\n ),\n json={}\n )\n\n def handler(command, **kwargs):\n if command == 'build':\n return True\n else:\n raise ValueError('Only `build` command is supported.')\n\n payload = load_fixture('event-issue-comment-build-command.json')\n payload[\"comment\"][\"body\"] = command\n\n bot = CommentBot(name='ursabot', token='', handler=handler)\n bot.handle('issue_comment', payload)\n\n post = responses.calls[3]\n assert json.loads(post.request.body) == {'content': reaction}\n\n\n# TODO(kszucs): properly mock it\n# def test_crossbow_submit():\n# from click.testing import CliRunner\n# runner = CliRunner()\n# result = runner.invoke(\n# bot, ['crossbow', 'submit', '-g', 'wheel', '--dry-run']\n# )\n# assert result.exit_code == 0\n","repo_name":"snowflakedb/libsnowflakeclient","sub_path":"deps/arrow-0.17.1/dev/archery/archery/tests/test_bot.py","file_name":"test_bot.py","file_ext":"py","file_size_in_byte":6137,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"61"}
+{"seq_id":"30909564890","text":"from pynput import keyboard\n\nfrom mqtt.mqtt_client import MQTTClient\nfrom virtual_devices.button_v import ButtonV, ButtonState\n\nclient1 = MQTTClient(\"fogdevices.agh.edu.pl\")\nbutton_1 = ButtonV(2, 3, client1)\nbutton_2 = ButtonV(2, 4, client1)\nbutton_3 = ButtonV(2, 5, client1)\n\nbuttons = [button_1, button_2, button_3]\n\n\"\"\"\nExample shows simple simulation of button pressing/releasing in reaction for keyboard pressing. Pressing 0,1,2 keys \ntriggers event for appropriate buttons. When button state changes, mqtt message is generated. Scenario decorators are\nnot used in this example.\n\"\"\"\n\n\ndef on_press(key):\n if hasattr(key, 'char') and key.char in ['0', '1', '2']:\n print('alphanumeric key {0} pressed'.format(key.char))\n buttons[int(key.char)].set_state_v(ButtonState.ON)\n elif key == keyboard.Key.esc:\n return False\n else:\n print('special key {0} pressed'.format(key))\n\n\ndef on_release(key):\n print('{0} released'.format(key))\n if hasattr(key, 'char') and key.char in ['0', '1', '2']:\n print('alphanumeric key {0} pressed'.format(key.char))\n buttons[int(key.char)].set_state_v(ButtonState.OFF)\n\n elif key == keyboard.Key.esc:\n return False\n\n\n# Collect events until released\nwith keyboard.Listener(\n on_press=on_press,\n on_release=on_release) as listener:\n listener.join()\n","repo_name":"tszydlo/emulator","sub_path":"examples/use_cases/use_case_3.py","file_name":"use_case_3.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"14602822548","text":"from time import time\n\nimport cv2\n\n\nclass RealtimeCapture:\n def __init__(self, params):\n self.capture = cv2.VideoCapture(params)\n self.video_frame_time = 0\n self.start_time = None\n\n def get_time(self):\n return self.early_fetch_time\n\n def read(self):\n if self.start_time is None:\n self.start_time = time()\n\n process_time = time() - self.start_time\n\n ret, frame = self.capture.read()\n while self.video_frame_time + process_time > self.capture.get(cv2.CAP_PROP_POS_MSEC) / 1000:\n ret, frame = self.capture.read()\n\n self.start_time = time()\n self.video_frame_time = self.capture.get(cv2.CAP_PROP_POS_MSEC) / 1000\n\n return ret, frame\n\n\nif __name__ == \"__main__\":\n rc = RealtimeCapture((\"\",))\n\n start_time = time.time()\n while True:\n r, frame = rc.read()\n current_time = time.time()\n frame_time = rc.get_time()\n\n if r:\n cv2.putText(frame, \"Video Time: \" + str(frame_time), (30, 30), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 255, 0))\n cv2.putText(frame, \"Wall Time: \" + str(current_time - start_time), (30, 55), cv2.FONT_HERSHEY_COMPLEX, 0.5,\n (255, 255, 0))\n cv2.imshow(\"Preview\", frame)\n\n k = cv2.waitKey(1)\n if k == ord(\"q\"):\n break\n","repo_name":"eduze/PersonDetectors","sub_path":"RealtimeCapture.py","file_name":"RealtimeCapture.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"4325914395","text":"#\n# persist_counters App\n\nimport appdaemon.plugins.hass.hassapi as hass\nimport os\nimport datetime\nimport pickle\nimport sqlite3\nfrom contextlib import closing\n\n_counter_filename_ = '/home/homeassistant/.homeassistant/apps/counters.pkl'\n_db_filename_ = '/home/homeassistant/.homeassistant/apps/autolight.db'\n\nclass AutoLight_Global(hass.Hass):\n\tcounter_dict = {}\n\tdecision_log = []\n\tautolight_bd = None\n\n\tdef initialize(self):\n\t\tself.log(\"Hello from AutoLight_Global\")\n\n\t\t# Register hourly callback to save everything\n\t\tself.daily_handle = self.run_hourly(self.hourly_save, start=datetime.time(0, 0, 0))\n\n\t\t# Register callback to save counters on hass stop\n\t\thandle = self.listen_event(self.hass_stopped, event='plugin_stopped')\n\n\t\t# Register callback to load counters on hass start\n\t\t# handle = self.listen_event(self.hass_started, event='plugin_started')\n\n\t\t# Register callback on app terminate\n\t\thandle = self.listen_event(self.hourly_save, event='terminate')\n\n\t\t# Restore counters\n\t\tself.load_counters()\n\n\t\t# Check if DB exists\n\t\tif not os.path.isfile(_db_filename_):\n\t\t\tself.log(\"AutoLight_Global creating new DB\")\n\t\t\ttmpconn = sqlite3.connect(_db_filename_)\n\t\t\twith closing(tmpconn.cursor()) as c:\n\t\t\t\t# ['fake', 4, 10, 'off,off,on,off,off,off,off,on,off,off,off,off,+25.5,33.0', 15, 0]\n\t\t\t\tc.execute('''CREATE TABLE decisions(\n\t\t\t\t\t\t\tentity text,\n\t\t\t\t\t\t\tweekday integer,\n\t\t\t\t\t\t\thour integer,\n\t\t\t\t\t\t\tcontext text,\n\t\t\t\t\t\t\tturned_on_interval integer,\n\t\t\t\t\t\t\tresult integer)''')\n\n\t\t# Test\n\t\t# self.log(\"***Saving test fake data\")\n\t\t# self.book_decision_data('fake1')\n\t\t# self.book_decision_result(15, 0)\n\t\t# self.save_decision_data()\n\n\tdef hourly_save(self, event_name, data, kwargs):\n\t\tself.log(\"****saving\")\n\t\tself.save_counters('dummy arg')\n\t\tself.save_decision_data()\n\n\tdef hass_stopped(self, event_name, data, kwargs):\n\t\tself.save_counters('dummy arg')\n\n\t# def hass_started(self, event_name, data, kwargs):\n\t# \tself.load_counters()\n\n\tdef load_counters(self):\n\t\tself.log(\"Loading persistent counters\")\n\t\tif os.path.isfile(_counter_filename_):\n\t\t\tself.counter_dict = pickle.load(open(_counter_filename_, 'rb'))\n\t\t\t# Set data\n\t\t\tfor counter_name in self.counter_dict.keys():\n\t\t\t\tself.log(\"Restoring counter: %s: %s\" % (counter_name, self.counter_dict[counter_name]))\n\t\t\t\tself.set_state(counter_name, state=str(self.counter_dict[counter_name]))\n\t\t\t\tself.log(\"done\")\n\n\tdef save_counters(self, kwargs):\n\t\tself.log(\"Saving persistent counters\")\n\t\t# Save data\n\t\tpickle.dump(self.counter_dict, open(_counter_filename_, 'wb'))\n\n\tdef increment_counter(self, counter_name):\n\t\tself.log(\"AutoLight_Global incrementing counter %s\" % counter_name)\n\t\t# Increment counter from current state\n\t\tself.call_service(\"counter/increment\", entity_id=counter_name)\n\t\t# Save in counter_dict\n\t\tself.counter_dict[counter_name] = self.get_state(counter_name)\n\n\n\tdef book_decision_result(self, variables_data, turned_on_interval, result):\n\t\tself.log(\"book_decision_result: %s / %d / %d\" % (variables_data, turned_on_interval, result))\n\t\tvariables_data.append(turned_on_interval)\n\t\tvariables_data.append(result)\n\t\tself.decision_log.append(variables_data.copy())\n\n\t\tself.log(\"book_decision_result done 1: %s\" % self.decision_log)\n\t\t# Clear variables_data\n\t\tdel variables_data[:]\n\t\tself.log(\"book_decision_result done 2: %s\" % self.decision_log)\n\n\tdef save_decision_data(self):\n\t\tif len(self.decision_log) > 0:\n\t\t\tself.log(\"Saving decision data: %s\" % self.decision_log)\n\t\t\tself.log(\"DB: %s\" % _db_filename_)\n\t\t\tcon = sqlite3.connect(_db_filename_)\n\t\t\t# Save data\n\t\t\twith con:\n\t\t\t\tcur = con.cursor()\n\t\t\t\tcur.executemany(\"\"\"INSERT INTO decisions VALUES(?,?,?,?,?,?)\"\"\", self.decision_log)\n\t\t\t\t# for d in self.decision_log:\n\t\t\t\t\t# self.log(\"Saving data: %s\" % d)\n\t\t\t\t\t# ['fake', 4, 10, 'off,off,on,off,off,off,off,on,off,off,off,off,+25.5,33.0', 15, 0]\n\t\t\t\t# cur.execute(\"INSERT INTO decisions VALUES(?,?,?,?,?,?)\" % (d[0],d[1],d[2],d[3],d[4],d[5]))\n\t\t\t# pickle.dump(self.decision_log, open(filename, 'wb'))\n\t\t\tprint(\"%s\" % self.decision_log)\n\t\t\t# Clear data\n\t\t\tself.decision_log = []\n\t\telse:\n\t\t\tself.log(\"No decision data to save\")\n","repo_name":"randomstash/hassconfig","sub_path":"apps/autolight_global.py","file_name":"autolight_global.py","file_ext":"py","file_size_in_byte":4102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"18568789076","text":"import discord\nfrom discord.ext import commands\nimport random\n\nclass Fun(commands.Cog):\n\n def __init__(self,client):\n self.client = client\n \n # Events\n @commands.Cog.listener()\n async def on_ready(self):\n print('Fun Bot is online.')\n\n @commands.command(help=\"gives a nice compliment!\")\n async def compliment(self, ctx):\n compliments = [ \"You look great today!\" ,\n \"You have really really nice programming skills.\" ,\n \"You make an excellent human.\",\n \"You’re a true gift to the people in your life.\",\n \"You’re amazing!\",\n \"You have a remarkable sense of humor.\",\n \"You are one of a kind.\",\n \"You inspire me to be a better Bot.\",\n \"Simply knowing you has made me a better Bot.\",\n \"All my Bot friends think you're really cool!\"]\n await ctx.send(random.choice(compliments))\n \n @commands.command(aliases=['8ball'], help=\"gives an 8-ball style answer to any question\")\n async def _8ball(self, ctx, *, question: str):\n responses = ['It is Certain.', \n 'It is decidedly so',\n 'Without a doubt.',\n 'Yes definitely.',\n 'You may rely on it.',\n 'As I see it, yes.',\n 'Most likely.',\n 'Ummm I guess...',\n 'Signs point to yes.',\n 'Reply hazy, try again.',\n 'Ask again later.',\n 'Better not tell you now.',\n 'Cannot predict now.',\n 'Concentrate and ask again.',\n \"Don't count on it.\",\n 'My reply is no.',\n 'My sources say no.',\n 'Outlook not so good.',\n 'Very doubtful.']\n await ctx.send(f'Question: {question}\\nAnswer: {random.choice(responses)}')\n \n @commands.command(help=\"replies with Pong!\")\n async def ping(self, ctx):\n await ctx.send(f'Pong!')\n\n @commands.command(help=\"replies with Polo!\")\n async def marco(self, ctx):\n await ctx.send(f'Polo!')\n\ndef setup(client):\n client.add_cog(Fun(client))","repo_name":"anavsingh99/discord-bot","sub_path":"cogs/fun.py","file_name":"fun.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"19099009722","text":"from pytest import fixture\n\nimport os\nimport os.path\n\nfrom autobahn.twisted import WebSocketServerFactory\n\nfrom mudmaker import Exit, Game, Room, Zone, WebSocketConnection, Object\nfrom mudmaker.socials import factory\n\n\n@fixture(name='exit')\ndef get_exit(game, zone):\n \"\"\"Get a new exit linking two rooms.\"\"\"\n location = game.make_object(\n 'Room', (Room,), name='Test Location', zone=zone\n )\n destination = game.make_object(\n 'Room', (Room,), name='Test Destination', zone=zone\n )\n return game.make_object(\n 'Exit', (Exit,), location=location, destination=destination,\n name='Test Exit', direction_name='n'\n )\n\n\n@fixture(name='game')\ndef get_game():\n \"\"\"Get a Game instance.\"\"\"\n g = Game('Test Game')\n g.account_store.filename = 'test-accounts.json'\n yield g\n if os.path.isfile(g.account_store.filename):\n os.remove(g.account_store.filename)\n\n\n@fixture(name='room')\ndef get_room(game, zone):\n return game.make_object('Room', (Room,), name='Test Room', zone=zone)\n\n\n@fixture(name='zone')\ndef get_zone(game):\n return game.make_object('Zone', (Zone,), name='Test Zone')\n\n\nclass PretendPeer:\n host = 'test.example.com'\n port = 1234\n\n\nclass PretendReason:\n def getErrorMessage(self):\n return 'Test conection was disconnected.'\n\n\nclass PretendTransport:\n def setTcpNoDelay(self, value):\n pass\n\n def getPeer(self):\n return PretendPeer()\n\n\nclass PretendConnection(WebSocketConnection):\n \"\"\"A pretend connection.\"\"\"\n\n def __init__(self, *args, **kwargs):\n self.transport = PretendTransport()\n super().__init__(*args, **kwargs)\n self.messages = []\n\n @property\n def last_message(self):\n if self.messages:\n return self.messages[-1]\n return ''\n\n def send(self, *args, **kwargs):\n pass\n\n def message(self, string):\n self.messages.append(string)\n return super().message(string)\n\n\n@fixture(name='connection')\ndef get_connection(game):\n \"\"\"Provides a pretend conection object.\"\"\"\n game.websocket_factory = WebSocketServerFactory()\n game.websocket_factory.game = game\n con = PretendConnection()\n con.factory = game.websocket_factory\n con.onOpen()\n game.connections.append(con)\n yield con\n game.connections.remove(con)\n\n\n@fixture(name='obj')\ndef get_object(game):\n return game.make_object('Object', (Object,), name='Test Object')\n\n\n@fixture(name='accounts')\ndef get_accounts(game):\n \"\"\"Get an AccountStore instance.\"\"\"\n return game.account_store\n\n\n@fixture(name='yaml_filename', scope='session', autouse=True)\ndef get_filename():\n # Will be executed before the first test\n filename = 'test.yaml'\n yield filename\n if os.path.isfile(filename):\n os.remove(filename)\n\n\n@fixture(name='player')\ndef get_player(connection, game, accounts, obj):\n accounts.add_account('test', 'test', obj)\n game.finish_login(connection, obj)\n return obj\n\n\n@fixture(name='socials')\ndef get_socials():\n return factory\n","repo_name":"chrisnorman7/mudmaker","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"71161650436","text":"# Run: pip install tabulate\n\nimport sys # Access command line arguments\nimport csv\nfrom tabulate import tabulate # prints a pretty ASCII format table\n\ndef main():\n check_command_line_args()\n # Read the CSV file and display the table\n display_csv_as_table(sys.argv[1])\n # # Check if the file exists\n try:\n file = open(sys.argv[1], \"r\") # open the file and read it\n pass\n # File doesnt exist\n except FileNotFoundError:\n sys.exit(\"File does not exist\")\n\ndef display_csv_as_table(file_path):\n with open(file_path, \"r\") as file:\n reader = csv.reader(file)\n table = list(reader)\n headers = table[0]\n print(tabulate(table[1:], headers, tablefmt=\"grid\"))\n\ndef check_command_line_args():\n # Check the number of elements given on the command line\n if len(sys.argv) < 2:\n sys.exit(\"Too few command-line arguments\")\n if len(sys.argv) > 2:\n sys.exit(\"Too many command-line arguments\")\n # Check if the file has a .csv extension\n if not sys.argv[1].endswith(\".csv\"):\n sys.exit(\"Not a CSV file\")\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n# Download pizza menu files via:\n# wget https://cs50.harvard.edu/python/2022/psets/6/pizza/sicilian.csv\n# wget https://cs50.harvard.edu/python/2022/psets/6/pizza/regular.csv\n\n# Run program as:\n# python pizza.py sicillian.csv / regular.csv","repo_name":"Stevecmd/CS50_python_2023","sub_path":"week06/pizza/pizza.py","file_name":"pizza.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"21020734834","text":"###############################################################################\r\n# #\r\n# This program is free software: you can redistribute it and/or modify #\r\n# it under the terms of the GNU General Public License as published by #\r\n# the Free Software Foundation, either version 3 of the License, or #\r\n# (at your option) any later version. #\r\n# #\r\n# This program is distributed in the hope that it will be useful, #\r\n# but WITHOUT ANY WARRANTY; without even the implied warranty of #\r\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #\r\n# GNU General Public License for more details. #\r\n# #\r\n# You should have received a copy of the GNU General Public License #\r\n# along with this program. If not, see . #\r\n# #\r\n###############################################################################\r\n\r\n__author__ = 'Donovan Parks'\r\n__copyright__ = 'Copyright 2015'\r\n__credits__ = ['Donovan Parks']\r\n__license__ = 'GPL3'\r\n__maintainer__ = 'Donovan Parks'\r\n__email__ = 'donovan.parks@gmail.com'\r\n\r\nimport hashlib\r\n\r\n\r\ndef sha256(input_file):\r\n \"\"\"Determine SHA256 hash for file.\r\n\r\n Parameters\r\n ----------\r\n input_file : str\r\n Name of file.\r\n\r\n Returns\r\n -------\r\n str\r\n SHA256 hash.\r\n \"\"\"\r\n\r\n BLOCKSIZE = 65536\r\n hasher = hashlib.sha1()\r\n with open(input_file, 'rb') as afile:\r\n buf = afile.read(BLOCKSIZE)\r\n while len(buf) > 0:\r\n hasher.update(buf)\r\n buf = afile.read(BLOCKSIZE)\r\n\r\n return hasher.hexdigest()\r\n","repo_name":"jtamames/SqueezeMeta","sub_path":"lib/biolib/checksum.py","file_name":"checksum.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","stars":295,"dataset":"github-code","pt":"61"}
+{"seq_id":"7858239478","text":"from __future__ import print_function\n\nimport os\nimport uuid\nfrom multiprocessing import Process\nimport time\nfrom bluelens_spawning_pool import spawning_pool\nfrom stylelens_product.products import Products\nfrom stylelens_product.crawls import Crawls\nimport redis\nimport pickle\n\nfrom bluelens_log import Logging\n\nREDIS_SERVER = os.environ['REDIS_SERVER']\nREDIS_PASSWORD = os.environ['REDIS_PASSWORD']\nRELEASE_MODE = os.environ['RELEASE_MODE']\nDB_PRODUCT_HOST = os.environ['DB_PRODUCT_HOST']\nDB_PRODUCT_PORT = os.environ['DB_PRODUCT_PORT']\nDB_PRODUCT_USER = os.environ['DB_PRODUCT_USER']\nDB_PRODUCT_PASSWORD = os.environ['DB_PRODUCT_PASSWORD']\nDB_PRODUCT_NAME = os.environ['DB_PRODUCT_NAME']\nAWS_ACCESS_KEY = os.environ['AWS_ACCESS_KEY'].replace('\"', '')\nAWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'].replace('\"', '')\n\nMAX_PROCESS_NUM = int(os.environ['MAX_PROCESS_NUM'])\n\nREDIS_HOST_CLASSIFY_QUEUE = 'bl:host:classify:queue'\nREDIS_PRODUCT_IMAGE_PROCESS_QUEUE = 'bl:product:image:process:queue'\nREDIS_CRAWL_VERSION = 'bl:crawl:version'\nREDIS_CRAWL_VERSION_LATEST = 'latest'\n\nSPAWNING_CRITERIA = 50\nPROCESSING_TERM = 60\n\noptions = {\n 'REDIS_SERVER': REDIS_SERVER,\n 'REDIS_PASSWORD': REDIS_PASSWORD\n}\nlog = Logging(options, tag='bl-image-process')\nrconn = redis.StrictRedis(REDIS_SERVER, port=6379, password=REDIS_PASSWORD)\n\ndef get_latest_crawl_version(rconn):\n value = rconn.hget(REDIS_CRAWL_VERSION, REDIS_CRAWL_VERSION_LATEST)\n if value is None:\n return None\n\n log.debug(value)\n try:\n version_id = value.decode(\"utf-8\")\n except Exception as e:\n log.error(str(e))\n version_id = None\n return version_id\n\ndef cleanup_products(host_code, version_id):\n global product_api\n try:\n res = product_api.delete_products_by_hostcode_and_version_id(host_code, version_id,\n except_version=True)\n log.debug(res)\n except Exception as e:\n log.error(e)\n\ndef clear_product_queue(rconn):\n rconn.delete(REDIS_PRODUCT_IMAGE_PROCESS_QUEUE)\n\ndef push_product_to_queue(product):\n rconn.lpush(REDIS_PRODUCT_IMAGE_PROCESS_QUEUE, pickle.dumps(product))\n\ndef query(host_code, version_id):\n global product_api\n log.info('start query: ' + host_code)\n\n spawn_counter = 0\n\n q_offset = 0\n q_limit = 500\n\n try:\n while True:\n res = product_api.get_products_by_hostcode_and_version_id(host_code, version_id,\n is_processed=False,\n offset=q_offset, limit=q_limit)\n for p in res:\n push_product_to_queue(p)\n\n if len(res) == 0:\n break\n else:\n q_offset = q_offset + q_limit\n\n except Exception as e:\n log.error(str(e) + ':' + host_code)\n\n\ndef spawn(uuid):\n log.debug('RELEASE_MODE:' + RELEASE_MODE)\n\n pool = spawning_pool.SpawningPool()\n\n project_name = 'bl-image-processor-' + uuid\n log.debug('spawn_image-processor: ' + project_name)\n\n pool.setServerUrl(REDIS_SERVER)\n pool.setServerPassword(REDIS_PASSWORD)\n pool.setApiVersion('v1')\n pool.setKind('Pod')\n pool.setMetadataName(project_name)\n pool.setMetadataNamespace(RELEASE_MODE)\n pool.addMetadataLabel('name', project_name)\n pool.addMetadataLabel('group', 'bl-image-processor')\n pool.addMetadataLabel('SPAWN_ID', uuid)\n container = pool.createContainer()\n pool.setContainerName(container, project_name)\n pool.addContainerEnv(container, 'AWS_ACCESS_KEY', AWS_ACCESS_KEY)\n pool.addContainerEnv(container, 'AWS_SECRET_ACCESS_KEY', AWS_SECRET_ACCESS_KEY)\n pool.addContainerEnv(container, 'REDIS_SERVER', REDIS_SERVER)\n pool.addContainerEnv(container, 'REDIS_PASSWORD', REDIS_PASSWORD)\n pool.addContainerEnv(container, 'SPAWN_ID', uuid)\n pool.addContainerEnv(container, 'MAX_PROCESS_NUM', str(MAX_PROCESS_NUM))\n pool.addContainerEnv(container, 'RELEASE_MODE', RELEASE_MODE)\n pool.addContainerEnv(container, 'DB_PRODUCT_HOST', DB_PRODUCT_HOST)\n pool.addContainerEnv(container, 'DB_PRODUCT_PORT', DB_PRODUCT_PORT)\n pool.addContainerEnv(container, 'DB_PRODUCT_USER', DB_PRODUCT_USER)\n pool.addContainerEnv(container, 'DB_PRODUCT_PASSWORD', DB_PRODUCT_PASSWORD)\n pool.addContainerEnv(container, 'DB_PRODUCT_NAME', DB_PRODUCT_NAME)\n pool.setContainerImage(container, 'bluelens/bl-image-processor:' + RELEASE_MODE)\n pool.setContainerImagePullPolicy(container, 'Always')\n pool.addContainer(container)\n pool.setRestartPolicy('Never')\n pool.spawn()\n\ndef dispatch(rconn, version_id):\n global product_api\n\n size = rconn.llen(REDIS_PRODUCT_IMAGE_PROCESS_QUEUE)\n\n if size > 0 and size < MAX_PROCESS_NUM:\n for i in range(10):\n spawn(str(uuid.uuid4()))\n # time.sleep(60*60*2)\n\n if size >= MAX_PROCESS_NUM and size < MAX_PROCESS_NUM * 10:\n for i in range(100):\n spawn(str(uuid.uuid4()))\n # time.sleep(60*60*5)\n\n elif size >= MAX_PROCESS_NUM * 100:\n for i in range(500):\n spawn(str(uuid.uuid4()))\n # time.sleep(60*60*10)\n\ndef clear_dbs(version_id):\n remove_old_products(version_id)\n\n\ndef remove_old_products(version_id):\n global product_api\n\n try:\n res = product_api.delete_old_products(version_id)\n except Exception as e:\n log.error(str(e))\n\ndef remove_prev_pods():\n pool = spawning_pool.SpawningPool()\n pool.setServerUrl(REDIS_SERVER)\n pool.setServerPassword(REDIS_PASSWORD)\n pool.setMetadataNamespace(RELEASE_MODE)\n data = {}\n data['namespace'] = RELEASE_MODE\n data['key'] = 'group'\n data['value'] = 'bl-image-processor'\n pool.delete(data)\n time.sleep(60)\n\ndef prepare_products(rconn, version_id):\n global product_api\n offset = 0\n limit = 200\n\n clear_product_queue(rconn)\n clear_dbs(version_id)\n remove_prev_pods()\n try:\n log.info('prepare_products')\n while True:\n res = product_api.get_products_by_version_id(version_id=version_id,\n is_processed=False,\n offset=offset,\n limit=limit)\n\n log.debug(\"Got \" + str(len(res)) + ' products')\n for product in res:\n push_product_to_queue(product)\n\n if len(res) == 0:\n break\n else:\n offset = offset + limit\n\n except Exception as e:\n log.error(str(e))\n\ndef check_condition_to_start(version_id):\n global product_api\n\n product_api = Products()\n crawl_api = Crawls()\n\n try:\n log.info(\"check_condition_to_start\")\n\n # Check if image processing queue is empty\n queue_size = rconn.llen(REDIS_PRODUCT_IMAGE_PROCESS_QUEUE)\n if queue_size != 0:\n return False\n\n # Check if crawling process is done\n total_crawl_size = crawl_api.get_size_crawls(version_id)\n crawled_size = crawl_api.get_size_crawls(version_id, status='done')\n if total_crawl_size != crawled_size:\n return False\n\n # Check if all images are processed\n total_product_size = product_api.get_size_products(version_id)\n available_product_size = product_api.get_size_products(version_id, is_available=True)\n unavailable_product_size = product_api.get_size_products(version_id, is_available=False)\n # processed_size = product_api.get_size_products(version_id, is_processed=True)\n\n if (available_product_size + unavailable_product_size) == total_product_size:\n return False\n\n\n except Exception as e:\n log.error(str(e))\n\n return True\n\ndef start(rconn):\n while True:\n version_id = get_latest_crawl_version(rconn)\n if version_id is not None:\n log.info(\"check_condition_to_start\")\n ok = check_condition_to_start(version_id)\n log.info(\"check_condition_to_start: \" + str(ok))\n if ok is True:\n prepare_products(rconn, version_id)\n dispatch(rconn, version_id)\n time.sleep(60*10)\n\nif __name__ == '__main__':\n log.info('Start bl-image-process:3')\n try:\n Process(target=start, args=(rconn,)).start()\n except Exception as e:\n log.error(str(e))\n","repo_name":"BlueLens/bl-image-process","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7921,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32758361533","text":"import string\nfrom enigma.utils import Letter, Pair\n\n\ndef test_letter_from_str():\n tests = []\n for i in range(26):\n character = string.ascii_lowercase[i]\n index = i\n tests.append({\"letter\": character, \"index\": index})\n\n for test in tests:\n letter = Letter(test[\"letter\"])\n assert letter.letter == test[\"letter\"] and letter.index == test[\"index\"]\n\n\ndef test_letter_from_index():\n tests = []\n for i in range(26):\n character = string.ascii_lowercase[i]\n index = i\n tests.append({\"letter\": character, \"index\": index})\n\n for test in tests:\n letter = Letter(test[\"index\"])\n assert letter.letter == test[\"letter\"] and letter.index == test[\"index\"]\n\n\ndef test_pairs():\n tests = [\n {\"pair\": {\"A\": \"x\", \"B\": \"c\"}, \"off\": \"t\"},\n {\"pair\": {\"A\": \"r\", \"B\": \"t\"}, \"off\": \"g\"},\n {\"pair\": {\"A\": \"r\", \"B\": \"t\"}, \"off\": \"l\"},\n ]\n\n for test in tests:\n p = test[\"pair\"]\n pair = Pair(p[\"A\"], p[\"B\"])\n\n a = Letter(p[\"A\"])\n b = Letter(p[\"B\"])\n off = Letter(test[\"off\"])\n\n assert(pair.get(a) == b and pair.get(b) == a and pair.get(off) == None)\n","repo_name":"raymas/enigma-cipher-machine","sub_path":"tests/utils_tests.py","file_name":"utils_tests.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"22584297334","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom bert import modeling\nimport tokenization_ner\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow.contrib import crf\nfrom tensorflow.contrib.layers.python.layers import initializers\n\nDTYPE = tf.float32\nDTYPE_INT = tf.int32\n\n\nclass charBERT(object):\n def __init__(self,\n bert_config, char_config,\n is_training, # is_evaluation,\n input_token_ids, input_char_ids,\n labels, num_labels, use_char_representation=True,\n input_mask=None, segment_ids=None,\n use_one_hot_embeddings=False, # TPU加速则为True\n scope=None):\n \"\"\"\n\n :param bert_config:\n :param char_config:\n :param is_training: 处于estimator模式下的train模式\n :param is_evaluation: 处于estimator模式下的evaluate模式\n :param input_token_ids:\n :param input_char_ids:\n :param labels: 真实标签\n :param num_labels: 标签个数,用于CRF的转移矩阵\n :param input_mask:\n :param segment_ids: 用于Bert,不过这里没啥用处,因为只是处理一个ner的问题,所以bert默认都为0\n :param use_one_hot_embeddings: 是否用tpu\n :param scope:\n \"\"\"\n self.bert_model = modeling.BertModel(config=bert_config,\n is_training=is_training,\n input_ids=input_token_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n self.token_output = self.bert_model.get_sequence_output()\n\n if use_char_representation:\n char_embed_dim = char_config['char_embed_dim']\n filters = char_config['filters']\n alphabet_size = char_config['alphabet_size']\n activations = char_config['activations']\n n_highway = char_config['n_highway']\n projection_dim = char_config['projection_dim']\n char_dropout_rate = char_config['char_dropout_rate'] if is_training else 1.0\n\n self.charcnn_model = CharRepresentation(char_input=input_char_ids,\n alphabet_size=alphabet_size,\n filters=filters,\n projection_dim=projection_dim,\n char_embed_dim=char_embed_dim,\n activations=activations,\n n_highway=n_highway,\n dropout_rate=char_dropout_rate\n )\n self.char_output = self.charcnn_model.get_highway_output()\n\n token_shape = modeling.get_shape_list(self.token_output, expected_rank=3)\n char_shape = modeling.get_shape_list(self.char_output, expected_rank=3)\n\n if token_shape[1] != char_shape[1]:\n raise ValueError(\n \"The time steps of token representation (%d) is not the same as char representation (%d) \"\n % (token_shape[1], char_shape[1]))\n\n self.final_output = tf.concat([self.token_output, self.char_output], axis=-1)\n else:\n tf.logging.info(\"****************BERT representation only***************\")\n self.final_output = self.token_output\n\n sequece_lengths = tf.reduce_sum(input_mask, axis=-1)\n self.crf = CRF(input=self.final_output,\n labels=labels,\n num_labels=num_labels,\n lengths=sequece_lengths,\n is_training=is_training,\n # is_evaluation=is_evaluation # estimator模式下的evaluate模式还是需要返回损失函数的\n )\n\n def get_crf_loss(self):\n return self.crf.crf_loss()\n\n def get_orig_loss(self):\n return self.crf.orig_loss()\n\n def get_crf_preds(self):\n return self.crf.get_crf_decode_tags()\n\n def get_orig_preds(self):\n return self.crf.get_orig_tags()\n\n\nclass CRF(object):\n def __init__(self, input, labels, num_labels,\n lengths, is_training, dropout_rate=0.7):\n \"\"\"\n\n :param input:\n :param labels:\n :param num_labels: label的种类数,因为CRF是状态转移,因此label为一个状态\n :param lengths: batch中每个句子的实际长度\n :param is_training:\n :param dropout_rate:\n \"\"\"\n self.labels = labels\n self.num_labels = num_labels\n\n if is_training:\n input = tf.nn.dropout(input, dropout_rate)\n # project\n self.logits = self._project_layer(input, num_labels)\n if is_training:\n self.logits = tf.nn.dropout(self.logits, dropout_rate)\n # crf\n self.log_likelihood, self.trans = self._crf_log_likelihood(self.labels, self.logits, lengths, num_labels)\n # CRF decode, pred_ids 是一条最大概率的标注路径\n self.pred_ids, _ = crf.crf_decode(potentials=self.logits, transition_params=self.trans, sequence_length=lengths)\n\n def _project_layer(self, input, num_labels, name=None):\n \"\"\"\n :param outputs: [batch_size, num_steps, emb_size]\n :return: [batch_size, num_steps, num_tags]\n \"\"\"\n hidden_state = input.get_shape()[-1]\n seq_length = input.get_shape()[-2]\n with tf.variable_scope(\"project\" if not name else name):\n # project to score of tags\n with tf.variable_scope(\"logits\"):\n W = tf.get_variable(\"W\", shape=[hidden_state, num_labels],\n dtype=tf.float32, initializer=initializers.xavier_initializer())\n\n b = tf.get_variable(\"b\", shape=[num_labels], dtype=tf.float32,\n initializer=tf.zeros_initializer())\n\n hidden_ouput = tf.reshape(input,[-1, hidden_state])\n pred = tf.nn.xw_plus_b(hidden_ouput, W, b)\n return tf.reshape(pred, [-1, seq_length, num_labels])\n\n def _crf_log_likelihood(self, labels, logits, lengths, num_labels):\n \"\"\"\n calculate crf loss\n :param project_logits: [1, num_steps, num_tags]\n :return: scalar loss\n \"\"\"\n with tf.variable_scope(\"crf_loss\"):\n trans = tf.get_variable(\n \"transitions\",\n shape=[num_labels, num_labels],\n initializer=initializers.xavier_initializer())\n log_likelihood, trans = tf.contrib.crf.crf_log_likelihood(\n inputs=logits,\n tag_indices=labels,\n transition_params=trans,\n sequence_lengths=lengths)\n # return tf.reduce_mean(-log_likelihood), trans\n return log_likelihood, trans\n\n def crf_loss(self):\n return tf.reduce_mean(-self.log_likelihood)\n\n def orig_loss(self):\n self.labels = tf.one_hot(indices = self.labels, depth = self.num_labels)\n self.loss_per_loc = tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.labels,\n logits=self.logits,\n dim=-1)\n return tf.reduce_mean(tf.reduce_sum(self.loss_per_loc, axis=-1), # 每个example的每个位置tag的损失,再加起来\n axis=-1)\n\n def get_crf_decode_tags(self):\n return self.pred_ids\n\n def get_orig_tags(self):\n return tf.argmax(self.logits, axis=-1)\n\n\nclass CharRepresentation(object):\n def __init__(self, char_input, alphabet_size, filters,\n char_embed_dim, projection_dim, activations='tanh',\n n_highway=None, dropout_rate=0.7):\n\n char_length = char_input.get_shape().as_list()[2]\n sequence_length = char_input.get_shape().as_list()[1]\n batch_size = char_input.get_shape().as_list()[0]\n\n with tf.name_scope(\"Char_Embedding\"), tf.device('/cpu:0'):\n self.embedding_weights = tf.get_variable( # 为每个字符形成的嵌入表\n \"char_embed\", [alphabet_size, char_embed_dim], dtype=DTYPE,\n initializer=tf.random_uniform_initializer(-1.0, 1.0))\n # shape (batch_size, unroll_steps, max_chars, embed_dim)\n self.char_embedding = tf.nn.embedding_lookup(self.embedding_weights,\n char_input)\n\n # for first model, this is False, for others it's True\n n_filters = sum(f[1] for f in filters)\n reuse = tf.get_variable_scope().reuse\n self.sequence_output = add_char_convolution(self.char_embedding, filters, activations, reuse)\n\n use_highway = n_highway is not None and n_highway > 0\n use_proj = n_filters != projection_dim\n if use_highway or use_proj:\n self.sequence_output = tf.reshape(self.sequence_output, [-1, n_filters])\n\n if use_highway:\n self.sequence_output = highway(self.sequence_output, n_highway)\n\n # set up weights for projection\n if use_proj:\n assert n_filters > projection_dim\n with tf.variable_scope('CNN_proj') as scope:\n W_proj_cnn = tf.get_variable(\n \"W_proj\", [n_filters, projection_dim],\n initializer=tf.random_normal_initializer(\n mean=0.0, stddev=np.sqrt(1.0 / n_filters)),\n dtype=DTYPE)\n b_proj_cnn = tf.get_variable(\n \"b_proj\", [projection_dim],\n initializer=tf.constant_initializer(0.0),\n dtype=DTYPE)\n self.sequence_output = tf.matmul(self.sequence_output, W_proj_cnn) + b_proj_cnn\n\n if use_highway or use_proj:\n orig_shape = [-1, sequence_length, projection_dim]\n self.sequence_output = tf.reshape(self.sequence_output, orig_shape)\n self.sequence_output = tf.nn.dropout(self.sequence_output, dropout_rate)\n\n def get_embedding_output(self):\n return self.char_embedding\n\n def get_highway_output(self):\n return self.sequence_output\n\n\ndef add_char_convolution(input, filters, activations, reuse):\n # input shape (batch_size, unroll_steps, max_chars, embed_dim)\n char_embed_dim = input.get_shape().as_list()[-1]\n char_length = input.get_shape().as_list()[-2]\n with tf.variable_scope(\"CNN\", reuse=reuse):\n convolutions = []\n for i, (width, num_filters) in enumerate(filters):\n if activations == 'relu':\n # He initialization for ReLU activation\n # with char embeddings init between -1 and 1\n # w_init = tf.random_normal_initializer(\n # mean=0.0,\n # stddev=np.sqrt(2.0 / (width * char_embed_dim))\n # )\n\n # Kim et al 2015, +/- 0.05\n w_init = tf.random_uniform_initializer(\n minval=-0.05, maxval=0.05)\n activation = tf.nn.relu\n elif activations == 'tanh':\n # glorot init\n w_init = tf.random_normal_initializer(\n mean=0.0,\n stddev=np.sqrt(1.0 / (width * char_embed_dim))\n )\n activation = tf.nn.tanh\n w = tf.get_variable( # 一个一维的卷积\n \"W_cnn_%s\" % i,\n # height, width, in_channel, out_channel, 这里的height设为1,因为只考虑一个单词内的字母排列,width为每次考虑width个字母\n # 后续卷积后的shape为(batch_size, sequence_length, char_length - width + 1, num_filters)\n [1, width, char_embed_dim, num_filters],\n initializer=w_init,\n dtype=DTYPE)\n b = tf.get_variable( # out_channel\n \"b_cnn_%s\" % i, [num_filters], dtype=DTYPE,\n initializer=tf.constant_initializer(0.0))\n\n conv = tf.nn.conv2d( # 卷积,从左到右\n input, w,\n strides=[1, 1, 1, 1],\n padding=\"VALID\") + b\n # now max pool\n # 使用一个max pool,每一行进行pooling\n # 取这些字母卷积后,最耀眼的一个位置,因此max_pool以后shape为(batch_size, sequence_length, 1, num_filters)\n # 这里可否把max_pool换成一个层叠卷积呢?\n conv = tf.nn.max_pool(\n conv, [1, 1, char_length - width + 1, 1],\n [1, 1, 1, 1], 'VALID')\n\n # activation\n conv = activation(conv)\n conv = tf.squeeze(conv, squeeze_dims=[2])\n\n convolutions.append(conv)\n\n return tf.concat(convolutions, 2)\n\ndef add_char_recurrent(input, filters, activations, reuse, bidirectional):\n pass\n\n\n# 参考highway网络的定义\ndef highway(input, n_highway):\n highway_dim = input.get_shape().as_list()[-1]\n sequence_length = input.get_shape().as_list()[-2]\n for i in range(n_highway):\n with tf.variable_scope('high_%s' % i) as scope:\n W_carry = tf.get_variable( # 这些都是get_variable\n 'W_carry', [highway_dim, highway_dim],\n # glorit init\n initializer=tf.random_normal_initializer(\n mean=0.0, stddev=np.sqrt(1.0 / highway_dim)),\n dtype=DTYPE)\n b_carry = tf.get_variable(\n 'b_carry', [highway_dim],\n initializer=tf.constant_initializer(-2.0),\n dtype=DTYPE)\n W_transform = tf.get_variable(\n 'W_transform', [highway_dim, highway_dim],\n initializer=tf.random_normal_initializer(\n mean=0.0, stddev=np.sqrt(1.0 / highway_dim)),\n dtype=DTYPE)\n b_transform = tf.get_variable(\n 'b_transform', [highway_dim],\n initializer=tf.constant_initializer(0.0),\n dtype=DTYPE)\n input = tf.reshape(input, [-1, highway_dim])\n\n carry = tf.matmul(input, W_carry) + b_carry\n carry_gate = tf.nn.sigmoid(carry)\n\n transform = tf.matmul(input, W_transform) + b_transform\n transform_gate = tf.nn.relu(transform)\n\n return carry_gate * transform_gate + (1.0 - carry_gate) * input\n\n\n\n\n\n","repo_name":"Zhengxuru/charCNN-BERT-CRF","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":14668,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"61"}
+{"seq_id":"15650830407","text":"# Description: 主要是获取redis中AQP的DFS node, 然后调用两层sent2vec模型, 最后求vector之间的欧式距离\nimport os\nimport redis\nimport numpy as np\nfrom dictfile.read_dict import get_AQP_node_dict\nfrom dictfile.read_dict import read_rule_file\nfrom sent2vec import Word\nfrom sent2vec import Sentence\nfrom sent2vec import sentence_to_vec\nfrom sklearn import preprocessing\nimport collections\nimport time\n\n\nclass AQP:\n def __init__(self, id, key, statement, vector):\n self.id = id # AQP的自增ID\n self.key = key # Id\n self.statement = statement # 由sent2vec中的Word实例(node index:vector)序列够成\n self.vector = vector # 初始为空,后续补充为该method对应的sentence vector\n self.distance = -1.0 # AQP与QEP之间的向量距离\n self.distance_norm = -1.0 # 归一化后的距离\n\n\ndef getAQPWords(nodes):\n \"\"\"\n 对于给定method的每个node,根据node index在node-vec字典中找到其对应的vector,调用sent2vec中的Word构造函数,并将Word实例加入到该method对应的Word序列method_vec_list\n :param nodes:\n :return:\n \"\"\"\n AQP_node_vec_list = []\n for index in nodes:\n if index in AQP_node_dict.keys():\n word_list.append(index)\n word = Word(index, AQP_node_dict[index])\n AQP_node_vec_list.append(word)\n return AQP_node_vec_list\n\n\ndef getRedisAQPs():\n \"\"\"\n 为redis数据库中收集的每个method(key:value),以method的id、key、line、Word序列构建Method实例,并得到Method实例序列\n :return:\n \"\"\"\n AQPs = []\n for i in range(data_size):\n key = keys[i].decode()\n # 将redis中的一个AQP分解为多个node,分隔符为`,`\n node_seq = jedis.get(keys[i]).decode().split(\",\")\n AQP_nodes = list(node_seq)\n vector = []\n # 调用sent2vec,得到该method_i对应的Word序列,组成statement\n statement = getAQPWords(AQP_nodes)\n # 构建Method实例\n aqp = AQP(i, key, statement, vector)\n AQPs.append(aqp)\n return AQPs\n\n\ndef get_word_counts(word_list):\n word_counts = collections.Counter(word_list)\n return word_counts\n\n\ndef get_word_frequency(word_text, word_counts, word_list_len):\n word_count = word_counts.get(word_text)\n if (word_count != None):\n # print(word_text, word_count, word_list_len)\n return (word_counts.get(word_text) * 1.0 / (word_list_len * 1.0))\n else:\n return 1.0\n\n\ndef getWordFrequencyDict(word_list):\n \"\"\"\n 根据\n :param word_list:\n :return:\n \"\"\"\n word_counts = get_word_counts(word_list)\n word_list_len = len(word_list)\n rule_indexs = read_rule_file(AQP_node_index_path)\n\n # 清空fre_dict\n f_dict = open(AQP_node_fre_path, 'w')\n f_dict.truncate(0)\n\n for word_text in rule_indexs:\n word_frequency = get_word_frequency(word_text, word_counts, word_list_len)\n # a_value = a / (a + word_frequency)\n with open(AQP_node_fre_path, 'a+') as fw:\n s = str(word_text) + \" \" + str(word_frequency) + '\\n'\n fw.write(s)\n\n\ndef getAvalueDict():\n \"\"\"\n 根据fredict.txt文件中的index-value序列,创建以index为索引,值为value的一维数组avaluedict\n :return:\n \"\"\"\n getWordFrequencyDict(word_list)\n avaluedict = {}\n for line in open(AQP_node_fre_path):\n kv = line.split(\" \")\n avaluedict[kv[0]] = kv[1].replace(\"\\n\", \"\")\n return avaluedict\n\n\ndef getVectorAQPs():\n \"\"\"\n 对于AQP实例序列,补充每个AQP实例的sentence vector\n :return:\n \"\"\"\n AQPs = getRedisAQPs() # AQP 实例序列\n avaluedict = getAvalueDict() # 根据fredict.txt,构建以node index为索引,单词频率为值的一维数组\n sentence_list = [] # Sentence实例(AQP节点序列)的序列\n # 将每个AQP对应的Word实例序列,作为参数创建一个Sentence实例\n for i in range(len(AQPs)):\n sentence_list.append(Sentence(AQPs[i].statement))\n # 将每个method对应的Sentence实例转换为vector\n sentence_vectors = sentence_to_vec(sentence_list, embedding_size, avaluedict)\n # 将sentence_vectors赋值给method中对应的成员变量\n for i in range(len(AQPs)):\n AQPs[i].vector = sentence_vectors[i]\n return AQPs\n\n\ndef cal_l2_dist(vec1, vec2):\n return np.sqrt(np.sum(np.square(vec1 - vec2)))\n\n\ndef cal_distance(vec1, vec2):\n dist = np.linalg.norm(vec1 - vec2)\n return dist\n\n\ndef min_max_normalization(distance_list):\n min_max_scaler = preprocessing.MinMaxScaler()\n distance_list_norm = min_max_scaler.fit_transform(np.array(distance_list).reshape(-1, 1))\n return distance_list_norm\n\n\ndef method_compare():\n \"\"\"\n 对于redis中的每个method(由Word实例序列够成),通过sent2vec,\n 利用单词频次和权重,处理得到每个method的sentence vector,\n 接着,两两计算得到sentence vector间的欧氏距离\n :return: 返回欧氏距离矩阵\n \"\"\"\n # 得到redis中每个AQP对应的AQP class实例:包含sentence vector\n AQPs = getVectorAQPs()\n\n # 输出AQP个数\n print(\"the number of AQPs:\", len(AQPs))\n\n # 得到每个AQP与QEP的向量距离\n distance_list = [0]\n for i in range(len(AQPs)):\n if i == 0:\n continue\n distance_list.append(cal_l2_dist(AQPs[0].vector, AQPs[i].vector))\n\n # 得到归一化的向量距离\n distance_list_norm = min_max_normalization(distance_list)\n for i in range(len(AQPs)):\n AQPs[i].distance_norm = distance_list_norm[i][0]\n AQPs[i].distance = distance_list[i]\n\n # 按照向量距离从大到小对AQPs排序\n AQPs_sorted = sorted(AQPs, key=lambda aqp: aqp.distance, reverse=True)\n\n print(\"farthest AQP from QEP: \", AQPs_sorted[0].id, AQPs_sorted[0].distance_norm)\n print(\"closet AQP from QEP: \", AQPs_sorted[len(AQPs) - 1].id, AQPs_sorted[len(AQPs) - 1].distance_norm)\n return AQPs_sorted\n\n\ndef i_tips(cnt):\n return AQPs_sorted[cnt]\n\n\ndef b_tips(k):\n return AQPs_sorted[:k]\n\n\ndef calculate_interestingness(selected_AQPs):\n \"\"\"\n 对\n :param selected_AQPs:\n :return:\n \"\"\"\n\n interestingness = 0\n\n return interestingness\n\n\nif __name__ == '__main__':\n # 输入查询name\n print('input the name of query')\n query_name = input()\n\n # 得到被检测源码中每个method的key\n jedis = redis.Redis(host='127.0.0.1', port=6379, db=0)\n keys = jedis.keys()\n\n data_size = len(keys) # redis中method的个数/记录的条数\n word_list = [] # 存储redis中存在于node-vec字典中的node index\n embedding_size = 128 # 记录node vector的维度\n\n # 得到node-vec字典训练数据\n dict_path = os.path.abspath(os.path.dirname(os.getcwd())) + '/GenerateTreeVector/dictfile/new/'\n AQP_node_index_path = dict_path + 'AQPNodeIndex.txt'\n AQP_node_vector_path = dict_path + 'AQPNodeVector.txt'\n AQP_node_fre_path = dict_path + 'AQPNodeFreDict.txt'\n\n # 得到skip gram模型训练得到的node-vec字典\n AQP_node_dict = get_AQP_node_dict(AQP_node_index_path, AQP_node_vector_path)\n\n time_start = time.time()\n print(\"开始时间:\", time.time())\n print(\"data_size: \", data_size)\n\n # 比较得到QEP与每个AQP vector间的欧氏距离\n AQPs_sorted = method_compare()\n time_end = time.time()\n print(\"结束时间:\", time.time())\n print('time cost', time_end - time_start, 's')\n\n # 记录消耗时间\n print('time cost', time_end - time_start, 's')\n fout_time = open(\n os.getcwd() + '/output/' + query_name[0:4] + '/' + query_name[5:] + '/generate_aqp_vector_time.txt',\n 'w+')\n fout_time.write(str(time_end - time_start))\n fout_time.close()\n\n # choose TIPS\n print(\"i(i-tips) / b(b-tips?\")\n\n choose = input()\n\n if choose == 'i':\n cnt = 0\n while choose == 'i':\n t = i_tips(cnt)\n print(cnt, t.id, t.distance_norm)\n cnt += 1\n choose = input()\n elif choose == 'b':\n # get k\n print(\"input the number of AQPs to be selected(q to quit)\")\n k = input()\n\n # get name & id\n db_name = query_name[0:4]\n query_id = query_name[5:]\n\n # 将selected AQP序号写入到相应文件中\n output_file_path = (os.path.abspath(\n os.path.dirname(os.getcwd())) + '/GenerateTreeVector/output/' + db_name + '/' + query_id + '/' + str(k) + '_selected_aqps.txt')\n\n # get selected AQPs\n aqps = b_tips(int(k))\n\n # convert to string\n selected_query = ''\n for i in range(int(k)):\n print(i, aqps[i].id, aqps[i].distance_norm)\n selected_query += str(aqps[i].id)+'\\n'\n selected_query = selected_query.rstrip('\\n')\n\n # storage\n output_file = open(output_file_path, 'w')\n output_file.write(selected_query)\n output_file.close()\n\n else:\n print(\"wrong char\")\n","repo_name":"ZiHao256/InfoPlan","sub_path":"EmbeddingMethod/src/GenerateTreeVector/generate_and_compare.py","file_name":"generate_and_compare.py","file_ext":"py","file_size_in_byte":8983,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"36012075244","text":"'''\r\nSamuel Howell \r\nCS330\r\nProject 5\r\n\r\n\r\nNote: you need to install pkgs from the cmd line outside of the vs code application\r\n'''\r\n\r\nfrom Robot import Robot\r\nimport time\r\n\r\n\r\n\r\nbyteList = []\r\nflag = False\r\nrobot = Robot('COM3')\r\ndirection = \"n\"\r\n\r\n#! MAKE SURE THE CORD IS PLUGGED ALL THE WAY IN\r\ndef initRobot():\r\n robot.reset() \r\n time.sleep(1)\r\n robot.start()\r\n time.sleep(1)\r\n robot.safe()\r\n time.sleep(1)\r\n print(\"ready to run\")\r\n robot.clearBuffer()\r\n\r\n \r\n\r\ninitRobot()\r\n\r\n# move forward until bump\r\nwhile(flag == False):\r\n robot.driveDirect(0,150,0,150)\r\n\r\n robot.sendCommand(b'\\x8E\\x07') # bump detected\r\n readList = robot.read(1)\r\n \r\n\r\n bumpDetected =(int(readList[0], 2) & 1 == 1 or int(readList[0], 2) & 2 == 2) # use bitmasking to isolate and check each status bit to determine if left or right bump have been triggered\r\n \r\n if(bumpDetected):\r\n flag = True\r\n print(\"bump detected\")\r\n robot.driveDirect(254,150,254,150) # drive backward to create some space for the turn\r\n time.sleep(.2)\r\n robot.driveDirect(0, 150, 255, 106) #rotate 90 degrees in a west direction to get the wall to the right of the wall sensor. #! make sure robot is rotating enought to get a good inital read from the side\r\n time.sleep(1.5) \r\n robot.driveDirect(0,0,0,0)\r\n \r\n\r\n\r\nwhile(flag == True):\r\n #robot.driveDirect(0,50,0,50)\r\n #robot.sendCommand(b'\\x8E\\x07') # bump detected\r\n \r\n robot.queryLight()\r\n byteList.append(robot.readTwo()) #! make sure that you come in from the side more so than you think\r\n \r\n\r\n\r\n currentByte = int(str(byteList[len(byteList)-1]).lstrip('[').rstrip(']')) # this takes \"[x]\" and makes is \"x\" so it can be converted to an int.\r\n print(\"current: \" + str(currentByte))\r\n \r\n error = 150 - currentByte # desired distance - actual distance\r\n ref = 40\r\n prop = robot.pController(error)\r\n\r\n print(\"prop: \", str(prop), \" error: \" + str(error), \" distance: \", str(currentByte))\r\n \r\n\r\n # wait for serial comm to stop sending before you run program again\r\n # current byte is measurement from the wall. we want to keep it at around 40\r\n\r\n if (currentByte > 150):\r\n currentByte = 150\r\n if (currentByte == 0): # ifthe robot is too far away from the wall, set current byte to ref - 1 to send the robot right.\r\n currentByte == ref - 1\r\n if (currentByte < ref): # move closer to the wall, turning right #!can change 10 to 0 for even tighter turns if necessary depending on complexity of the obstacle\r\n robot.driveDirect(0, 50 - prop, 0, 50 + prop)\r\n print(\"R\")\r\n if (currentByte > ref): # move away from the wall, turning left\r\n robot.driveDirect(0, 50 + prop, 0, 50 - prop)\r\n print(\"L\")\r\n if (currentByte == ref): # go straight\r\n robot.driveDirect(0, 70, 0, 70)\r\n\r\n \r\n #check for a bump\r\n robot.sendCommand(b'\\x8E\\x07') # bump detected\r\n readList = robot.read(1)\r\n bumpDetected =(int(readList[0], 2) & 1 == 1 or int(readList[0], 2) & 2 == 2)\r\n \r\n if(bumpDetected):\r\n robot.driveDirect(0, 150, 255, 106) #rotate 90 degrees in a west direction to get the wall to the right of the wall sensor. #! make sure robot is rotating enought to get a good inital read from the side\r\n time.sleep(.3)\r\n robot.driveDirect(0, 0, 0, 0)\r\n \r\n \r\n if(len(byteList) > 5): # don't let the list grow large\r\n byteList.pop(0)\r\n\r\n\r\n\r\n\r\n'''\r\n*65% of the grade:*\r\nUSE P-CONTROLLER ONLY: Write a program that commands the iRobot Create to respond in the following ways:\r\n1. Start the robot driving. It should drive until it contacts a wall – you may ensure there is nothing else in its path. At the wall, it should rotate and align itself parallel to the surface.\r\n2. Once the robot is parallel to the surface of the wall, it should begin translating again keeping a set distance from the surface (you decide distance).\r\n3. While following the wall, it should pay attention to its bump sensors and using those along with its wall range sensor and should attempt to circumnavigate anything–imagine a shoe–it finds in its way.\r\n4. Points will be awarded for how well the robot stabilizes following the wall, how well it corners and how well it circumnavigates obstacles along the wall.\r\n\r\n*10% of the grade:*\r\n5. Upload a video of your robot driving along the wall with the same obstacles to YouTube. The video should be named the following way:FMU CS330 Robotics Fall 2022, Lab Project #5, [first, last names of all the students in the team]: Kp=[your Kp].\r\n\r\n*15% of your grade:*\r\n6. Create a report where you explain how you choose a period of quering sensor data, reference, Kp, Ki, Kd, transition function, draw a control system you use in your project.\r\n\r\n*10% of your grade:*\r\n7. Slack usage:\r\n7.1 Learn how to share files on Slack using Googe Drive. Share a file with your partner (team).\r\n7.2 Learn how to incorporate the Trello app in a slack. Learn how to add a card, make a comment, assign a teammate to a card.\r\n7.3 Send a private video message to your partner with some meaningful content.using /voice command.\r\n7.4 Set up a zoom conference via slack (using /zoom).\r\n7.5 Also, using the https://lunchtrain.builtbyslack.com/ schedule a lunch with your partner (yourself), and make him join you, show me the reminders from the slack bot\r\n'''\r\n","repo_name":"samuel-howell/CS330","sub_path":"project5.py","file_name":"project5.py","file_ext":"py","file_size_in_byte":5417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"1560917068","text":"from .reduce_html import reduce_html\nfrom .send_email import send_email\n\n\nasync def get_html(url, browser):\n # browser = await launch(headless=True)\n\n page = await browser.newPage()\n\n try:\n await page.goto(url, timeout=30000)\n html = await page.evaluate(\n \"() => document.body.innerText\"\n )\n # html = await page.content()\n await page.close()\n return html\n except Exception as err:\n send_email(\n 'Ocorreu um erro no Radar da Inovação',\n body=f\"\"\"\n Erro no MSS SCAN EDITAIS
\n Tentativa de acesso na URL: {url}
\n Erro do console: {err}
\n \"\"\"\n )\n\n return 'PÁGINA COM ERRO'\n\n\nasync def get_html_async(url, browser):\n html = await get_html(url, browser)\n html = reduce_html(html)\n print(f'TAMANHO DO TEXTO: {len(html)}')\n return html\n","repo_name":"caiogtoledo/mss_scan_editais","sub_path":"helpers/get_html_async.py","file_name":"get_html_async.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"27615226800","text":"\"\"\"\nThis package contains the necessary structures to use the implemented methods of the zia_client.session.ZIAConnector class\nthrough the command line script ziaclient.py.\n\nAs of now, only the functionality for locations and users has been translated.\n\nSee the submodules for detailed functionality.\n\"\"\"\nimport argparse as ap\nimport ast\nimport datetime as dt\nimport json\n\nfrom api_parser._locations import create_location_subparser\nfrom api_parser._traffic import create_traffic_subparser\nfrom api_parser._users import create_user_subparser\n\n\ndef create_parser():\n \"\"\"\n Creates the parser. It calls the necessary functions to build the subparsers.\n\n Returns:\n Returns the built parser.\n \"\"\"\n parser = ap.ArgumentParser(\n description=\"\"\"**ZIA API command line script.**\n \n Python script that communicates with the Zscaler Internet Access API.\n It's composed of various subparsers, each one representing the configured modules in the `zia_client` module.\n \n The keyword arguments listed below can be always specified before the desired subparser.\"\"\"\n )\n\n # Main parser commands\n parser.add_argument('--pending', help=\"Lists pending changes.\", action='store_true')\n parser.add_argument(\n '--apply_after',\n help='Forces application of changes before logging out after several requests.',\n type=int,\n default=0\n )\n parser.add_argument('--conf', help='Specifies config file.', default='config/config.json')\n parser.add_argument('--creds', help='Specifies config file.', type=_json_obj_file, default=None)\n parser.add_argument('--output', '-o', help='Custom path where the output JSON will be stored.',\n default=_output_name())\n parser.add_argument('--no_verbosity', help='Disables detailed verbosity.', action='store_true')\n parser.add_argument('--print_results', '-p', help='Prints results.', action='store_true')\n\n # Create subparsers\n subparsers = parser.add_subparsers(required=True, dest='Any of the subcommands')\n\n # Create user parser\n create_user_subparser(subparsers)\n\n # Create location parser\n create_location_subparser(subparsers)\n\n # Create traffic parser\n create_traffic_subparser(subparsers)\n\n return parser\n\n\ndef _output_name():\n \"\"\"\n Creates a name for the output file where the search or operation results will be stored if no custom name is \\\n provided.\n\n Returns:\n str: A string with the format `search_%Y-%m-%d_%H-%M-%S.json`.\n ``Example: search_2021-01-01_14-13-12.json``\n\n\n \"\"\"\n today = dt.datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S\")\n return f'query_{today}.json'\n\n\ndef _boolstring(arg):\n \"\"\"\n Checks api_parser that are not required and have default values on the server. Argument is a string but mus be\n converted to True, False or ''.\n\n Args:\n arg (str): Parsed argument.\n\n Returns:\n bool or empty string:\n \"True\" -> `True`\n\n \"False\" -> `False`\n\n Anything else -> `''`\n\n \"\"\"\n if arg == 'True':\n return True\n elif arg == 'False':\n return False\n else:\n return ''\n\n\ndef _json_obj_file(arg: str):\n if arg.endswith('.json'):\n with open(arg) as f:\n return json.load(f)\n else:\n data = ast.literal_eval(arg)\n try:\n return json.dumps(data)\n except json.JSONDecodeError:\n raise ap.ArgumentTypeError('Input should be a JSON object.')\n","repo_name":"javiruizs/ZIA-API-Connector","sub_path":"api_parser/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23617141791","text":"import sys, math, re\r\n\r\n \r\n\r\n\r\n\r\ndef main():\r\n# inFile = sys.__stdin__\r\n# outFile = sys.__stdout__\r\n inFile = open('B-large.in', 'rt')\r\n outFile = open(inFile.name.replace('.in', '.out'), 'wt')\r\n T = int(inFile.readline())\r\n for t in xrange(1,T+1):\r\n tt = inFile.readline().strip().split(' ')\r\n# print '------------------', tt\r\n tt.reverse()\r\n C = int(tt.pop())\r\n c = [tt.pop() for _ in xrange(C)]\r\n D = int(tt.pop())\r\n d = [tt.pop() for _ in xrange(D)]\r\n N = int(tt.pop())\r\n seq = list(tt.pop())\r\n out = ''\r\n cc = []\r\n for s in c:\r\n a,b,c = s\r\n expr = re.compile('(%s%s|%s%s)$' % (a,b,b,a))\r\n cc.append((expr, c))\r\n dd = []\r\n for s in d:\r\n a,b = s\r\n expr = re.compile('(%s.*?%s)|(%s.*?%s)' % (a,b,b,a))\r\n dd.append(expr)\r\n for s in seq:\r\n out += s\r\n for e, s in cc:\r\n out, n = e.subn(s, out, 1)\r\n for e in dd:\r\n if e.search(out):\r\n out = ''\r\n break\r\n \r\n outFile.write('Case #%d: [%s]\\n' % (t, ', '.join(out)))\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_75/217.py","file_name":"217.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"30935967298","text":"def read_input():\n inputs = []\n\n input_file = open(\"input\")\n for line in input_file:\n inputs.append(line.strip('\\n'))\n\n return inputs\n\ndef gamma_rate(inputs):\n new_code = []\n\n for i in range(WORD_LENGTH):\n total_0s = 0\n total_1s = 0\n for _, value in enumerate(inputs):\n if int(value[i]) == 0:\n total_0s += 1\n else:\n total_1s += 1\n if total_0s > total_1s:\n new_code.append(0)\n else:\n new_code.append(1)\n\n return new_code\n\ndef epsilon_rate(inputs):\n new_code = []\n\n for i in range(WORD_LENGTH):\n total_0s = 0\n total_1s = 0\n for _, value in enumerate(inputs):\n if int(value[i]) == 0:\n total_0s += 1\n else:\n total_1s += 1\n if total_0s < total_1s:\n new_code.append(0)\n else:\n new_code.append(1)\n\n return new_code\n\ndef convert_to_dec(binary_num):\n dec_value = 0\n for i in range(WORD_LENGTH-1, -1, -1):\n if binary_num[WORD_LENGTH-1-i] == 1:\n dec_value += (2**i)\n return dec_value\n\ndef find_o2_rating(inputs, position, current_size):\n total_0s = 0\n total_1s = 0\n\n if current_size == 1:\n return inputs\n\n for i in range(current_size):\n if int(inputs[i][position]) == 0:\n total_0s += 1\n else:\n total_1s += 1\n\n keep_value = 1\n keep_inputs = []\n if total_0s > total_1s:\n keep_value = 0\n\n for i in range(current_size):\n if int(inputs[i][position]) == keep_value:\n keep_inputs.append(inputs[i])\n else:\n current_size -= 1\n\n return find_o2_rating(keep_inputs, position+1, current_size)\n\ndef find_co2_rating(inputs, position, current_size):\n total_0s = 0\n total_1s = 0\n\n if current_size == 1:\n return inputs\n\n for i in range(current_size):\n if int(inputs[i][position]) == 0:\n total_0s += 1\n else:\n total_1s += 1\n\n keep_value = 0\n keep_inputs = []\n if total_0s > total_1s:\n keep_value = 1\n\n for i in range(current_size):\n if int(inputs[i][position]) == keep_value:\n keep_inputs.append(inputs[i])\n else:\n current_size -= 1\n\n return find_co2_rating(keep_inputs, position+1, current_size)\n\n\nif __name__ == \"__main__\":\n values = read_input()\n global WORD_LENGTH\n WORD_LENGTH = len(values[0])\n\n # part 1\n gamma = gamma_rate(values)\n epsilon = epsilon_rate(values)\n\n dec_gamma = convert_to_dec(gamma)\n dec_epsilon = convert_to_dec(epsilon)\n print(dec_gamma*dec_epsilon)\n\n # part 2\n o2_rating = find_o2_rating(values, 0, len(values))\n co2_rating = find_co2_rating(values, 0, len(values))\n\n dec_o2_rating = int(o2_rating[0],2)\n dec_co2_rating = int(co2_rating[0],2)\n print(dec_o2_rating*dec_co2_rating)\n","repo_name":"jramdass/advent-of-code","sub_path":"2021/day-03/binary_diagnostic.py","file_name":"binary_diagnostic.py","file_ext":"py","file_size_in_byte":2929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"21053168233","text":"from flask import Flask\nimport requests\nfrom bs4 import BeautifulSoup\nimport os\nimport sqlite3\nimport logging\n\nlogging.basicConfig(filename='example.log', level=logging.DEBUG)\n\nURL = os.environ['SOURCE_URL']\nAGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'\n\napp = Flask(__name__)\n\n\ndef send_simple_message(title, message):\n return requests.post(\n os.environ['MAIL_URL'],\n auth=(\"api\", os.environ['MAILGUN_API_KEY']),\n data={\"from\": \"Embevent App \",\n \"to\": os.environ['MAIL_LIST'].split(\";\"),\n \"subject\": title,\n \"text\": message})\n\ndef processUpdates(cards):\n connection = sqlite3.connect(\"database.db\")\n cursor = connection.execute(\"Select * from CARDS\")\n old_cards = len(cursor.fetchall())\n\n if len(cards) > old_cards:\n logging.info(\"New updates. Processing\")\n \n card = cards[0]\n title = card.find_all('h2', class_='h3')[0].text\n date = card.find_all('h3', class_='h5')[0].text\n content = card.find_all([\"p\", \"div\"])[0]\n\n command2 = \"INSERT INTO CARDS (title, date, content) VALUES ('{0}', '{1}', '{2}')\".format(title,date,content)\n \n connection.execute(command2)\n connection.commit()\n connection.close()\n\n logging.info(\"Update stored in DB\")\n\n send_simple_message(title=title, message=card)\n\n logging.info(\"Mail sent\")\n return card.text\n else:\n logging.info(\"No updates generated\")\n f = cards[0]\n the_date, = f.find_all('h3', class_='h5')\n return \"No news. Last update: {0}. articles available: {1}\".format(the_date.text, old_cards)\n\n@app.route('/')\ndef news():\n if not URL:\n return \"No URL added\"\n response = requests.get(URL, headers={'User-Agent': AGENT })\n soup = BeautifulSoup(response.content, 'html.parser')\n cards = soup.find_all('div', class_='card')\n return processUpdates(cards)","repo_name":"mleger45/embevent","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23608375081","text":"import sys\r\n\r\nfp = open('large.in', 'r')\r\nout = open('output', 'w')\r\n\r\n#fp = open('input', 'r')\r\n#out = sys.stdout\r\n\r\ncases = int(fp.readline())\r\n\r\nfor case in range(cases):\r\n existe = set()\r\n \r\n parms = [int(x) for x in fp.readline().split()]\r\n\r\n for x in range(parms[0]):\r\n row = fp.readline().strip()\r\n path = '/'\r\n for dir in row[1:].split('/'):\r\n# print path + dir\r\n existe.add(path + dir)\r\n path = path + dir + '/'\r\n \r\n result = 0\r\n for y in range(parms[1]):\r\n row = fp.readline().strip()\r\n path = '/'\r\n for dir in row[1:].split('/'):\r\n# print path + dir\r\n if path+dir not in existe:\r\n result += 1\r\n existe.add(path+dir)\r\n path = path + dir + '/'\r\n \r\n out.write('Case #' + str(case + 1) + ': ' + str(result) + '\\n')\r\n case += 1\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_59/332.py","file_name":"332.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12098841429","text":"# coding: utf-8\n# In[ ]:\n\n# 本實驗延續blockh3_with_bdwith.py\n# 模擬:\n# 假設 host3 被判定為可疑來源並 增加entry來block h3 後,管理員願意在50個單位時間後,重新開放權限給host3來送資料\n# 測試:\n# mininet端輸入 h1 ping h3 -s 3000\n# 以及mininet端輸入 h1 ping h3 -s 5000兩種情形\n# 觀察:\n# 1. mininet: 當被Block住 ping 即會失敗,過了一段時間後h3又可以繼續送資料\n# 2. ryu: 當被Block住後,port1 的rx, tx 均不會再增加\n# 而port3 的rx 會持續增加(因為惡意攻擊還是送得進來), 但tx則不會再增加\n# (過了一段時間後)\n# 解除Block ,port1 rx, tx, tx-flow/time 會重新開始增加\n# port 3 的 tx, tx-flow/time 也會重新開始增加\n# 則表示我們成功解除h3的Block了\n# (直到tx-flow/time超過5000,又會被block住 如此循環)\n# 方法:\n# 當Block entry被建立的同時,會將Block_flag set\n# 系統即會進入計數的階段,\n# 當一數到50則將舊的BlockEntry刪除,並會觸發一次新的Packet-In事件\n# 未來:\n# OFPMatch()的判斷條件要再更彈性一點,即(不再單單只是監測host3,而是整個網路)\n# 以限定流量大小,取代原有的直接Block住\n# Note:\n# 新增del_flow()這個函式去實踐刪除Entry的動作\n#-----\n# 07.02更新:加入物件導向編程, 新增class Host.py\n#\nimport Host\nfrom ryu.base import app_manager\nfrom ryu.controller import ofp_event\nfrom ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER, DEAD_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.ofproto import ofproto_v1_3\nfrom ryu.lib.packet import packet\nfrom ryu.lib.packet import ethernet\nfrom operator import attrgetter \nfrom ryu.lib import hub\nfrom ryu.lib.packet import ether_types\nimport os\n\nmonitor_time = 1\n#monitor_time為單位時間,每過 X 秒,monitor就更新一次,並統計每個port在該秒跟五秒前的流量差異\n\nhost = [0 for n in range(0,100)]\n\nfor i in range (0,100):\n host[i] = Host.port_information(i)\n\nclass SimpleSwitch13(app_manager.RyuApp):\n \n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n def __init__(self, *args, **kwargs):\n super(SimpleSwitch13, self).__init__(*args, **kwargs)\n self.mac_to_port = {}\n self.datapaths = {}\n self.monitor_thread = hub.spawn(self._monitor)\n #============================monitor============================#\n\n @set_ev_cls(ofp_event.EventOFPStateChange,\n [MAIN_DISPATCHER, DEAD_DISPATCHER])\n def _state_change_handler(self, ev):\n datapath = ev.datapath\n if ev.state == MAIN_DISPATCHER:\n if not datapath.id in self.datapaths:\n self.logger.debug('register datapath: %016x', datapath.id)\n self.datapaths[datapath.id] = datapath\n elif ev.state == DEAD_DISPATCHER:\n if datapath.id in self.datapaths:\n self.logger.debug('unregister datapath: %016x', datapath.id)\n del self.datapaths[datapath.id]\n\n def _monitor(self):\n while True:\n for dp in self.datapaths.values():\n self._request_stats(dp)\n global monitor_time\n hub.sleep(monitor_time)\n# monitor每��monitor time秒,便更新一次,此monitor_time值設定在code最前面,以global方式宣告\n\t\n def _request_stats(self, datapath):\n self.logger.debug('send stats request: %016x', datapath.id)\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n req = parser.OFPFlowStatsRequest(datapath)\n datapath.send_msg(req)\n\n req = parser.OFPPortStatsRequest(datapath, 0, ofproto.OFPP_ANY)\n datapath.send_msg(req)\n\n @set_ev_cls(ofp_event.EventOFPFlowStatsReply, MAIN_DISPATCHER)\n def _flow_stats_reply_handler(self, ev):\n body = ev.msg.body\n\n self.logger.info('datapath '\n 'in-port eth-dst '\n 'out-port packets bytes')\n self.logger.info('---------------- '\n '-------- ----------------- '\n '-------- -------- --------')\n for stat in sorted([flow for flow in body if flow.priority == 1],\n key=lambda flow:(flow.match['in_port'],\n flow.match['eth_dst'])):\n self.logger.info('%016x %8x %17s %8x %8d %8d',\n ev.msg.datapath.id,\n stat.match['in_port'], stat.match['eth_dst'],\n stat.instructions[0].actions[0].port,\n stat.packet_count, stat.byte_count)\n \n \n @set_ev_cls(ofp_event.EventOFPPortStatsReply, MAIN_DISPATCHER)\n def _port_stats_reply_handler(self, ev):\n body = ev.msg.body\n msg = ev.msg\n datapath = msg.datapath\n parser = datapath.ofproto_parser\n ofproto = datapath.ofproto\n global monitor_time\n self.logger.info('datapath port '\n 'rx-pkts rx-bytes rx-error '\n 'tx-pkts tx-bytes tx-error tx-flow/time')\n self.logger.info('---------------- -------- '\n '-------- -------- -------- '\n '-------- -------- -------- -----------')\n for stat in sorted(body, key=attrgetter('port_no')):\n num = 0\n if stat.port_no <= 10:\n num = stat.port_no\n host[num].set_now(stat.tx_bytes)\n host[num].set_flow(host[num].now - host[num].last)\n host[num].set_flow(host[num].flow / monitor_time)\n host[num].set_last(host[num].now)\n #self.change_now(num,stat.tx_bytes)\n #self.change_flow(num,now[num]-last[num])\n #self.change_flow(num,flow[num]/monitor_time)\n #self.change_last(num,now[num])\n self.logger.info('%016x %8x %8d %8d %8d %8d %8d %8d %8d', \n ev.msg.datapath.id, stat.port_no,\n stat.rx_packets, stat.rx_bytes, stat.rx_errors,\n stat.tx_packets, stat.tx_bytes, stat.tx_errors, host[num].flow )\n if (stat.port_no == 3) and (host[num].flow >= 5000):\n host[num].set_blocked_flag(True)\n instruction = [parser.OFPInstructionActions(ofproto.OFPIT_CLEAR_ACTIONS, []) ]\n self.logger.info(\"Blocked host 3's entry adding\")\n match = parser.OFPMatch(eth_src = '00:00:00:00:00:03')\n blockflow = parser.OFPFlowMod(datapath,\n priority = 2,\n command = ofproto.OFPFC_ADD,\n match = match,\n instructions = instruction\n )\n self.logger.info(\"Block entry: %s\" % str(blockflow));\n datapath.send_msg(blockflow)\n if(host[num].blocked_flag):\n self.logger.info(\"Host%d's Block Timer: %d\" % (num,host[num].blocked_timer));\n host[num].blocked_timer_add()\n if(host[num].blocked_timer == 50+monitor_time): #Re-Open the blocked host\n host[num].blocked_init()\n empty_match = parser.OFPMatch(eth_src = '00:00:00:00:00:03')\n instructions = []\n flow_mod = self.del_flow(datapath, empty_match,instructions)\n self.logger.info(\"Delete the Blocked entry(Re-Open Success!)\")\n num = 0\n\n #============================monitor============================#\n\n #============================SWITCH============================#\n\n\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_features_handler(self, ev):\n datapath = ev.msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n match = parser.OFPMatch()\n actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,\n ofproto.OFPCML_NO_BUFFER)]\n self.add_flow(datapath, 0, match, actions)\n\n def add_flow(self, datapath, priority, match, actions, buffer_id=None):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,\n actions)]\n if buffer_id:\n mod = parser.OFPFlowMod(datapath=datapath, buffer_id=buffer_id,\n priority=priority, match=match,\n instructions=inst)\n else:\n mod = parser.OFPFlowMod(datapath=datapath, priority=priority,\n match=match, instructions=inst)\n datapath.send_msg(mod)\n\n def del_flow(self, datapath, match,instructions):\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n\n mod = parser.OFPFlowMod(datapath=datapath,\n command=ofproto.OFPFC_DELETE,\n out_port=ofproto.OFPP_ANY,\n out_group=ofproto.OFPG_ANY,\n\t\t\t\tinstructions=instructions,\n match=match)\n datapath.send_msg(mod)\n\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\n def _packet_in_handler(self, ev):\n if ev.msg.msg_len < ev.msg.total_len:\n self.logger.debug(\"packet truncated: only %s of %s bytes\",\n ev.msg.msg_len, ev.msg.total_len)\n msg = ev.msg\n datapath = msg.datapath\n ofproto = datapath.ofproto\n parser = datapath.ofproto_parser\n in_port = msg.match['in_port']\n\n pkt = packet.Packet(msg.data)\n eth = pkt.get_protocols(ethernet.ethernet)[0]\n\n if eth.ethertype == ether_types.ETH_TYPE_LLDP:\n # ignore lldp packet\n return\n dst = eth.dst\n src = eth.src\n\n dpid = datapath.id\n self.mac_to_port.setdefault(dpid, {})\n\n self.logger.info(\"packet in %s %s %s %s\", dpid, src, dst, in_port)\n\n # learn a mac address to avoid FLOOD next time.\n self.mac_to_port[dpid][src] = in_port\n\n if dst in self.mac_to_port[dpid]:\n out_port = self.mac_to_port[dpid][dst]\n else:\n out_port = ofproto.OFPP_FLOOD\n\n actions = [parser.OFPActionOutput(out_port)]\n # install a flow to avoid packet_in next time\n \n if out_port != ofproto.OFPP_FLOOD:\n match = parser.OFPMatch(in_port=in_port, eth_dst=dst)\n self.add_flow(datapath, 1, match, actions)\n # verify if we have a valid buffer_id, if yes avoid to send both\n # flow_mod & packet_out\n \n # Packet-out\n data = None\n if msg.buffer_id == ofproto.OFP_NO_BUFFER:\n data = msg.data\n out = parser.OFPPacketOut(datapath=datapath, buffer_id=msg.buffer_id,\n in_port=in_port, actions=actions, data=data)\n datapath.send_msg(out)\n \n","repo_name":"HsiangTseng/workspaceryu","sub_path":"reopenh3.py","file_name":"reopenh3.py","file_ext":"py","file_size_in_byte":11368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"415386013","text":"from django.urls import path\n\nfrom . import views\n\n\nurlpatterns = [\n # ex: /polls/\n path('', views.index, name='index'),\n\n path('categories/', views.CategoryView.as_view(), name='categories'),\n path('BookingCategories/', views.CategoryDetailView.as_view(), name='category-detail')\n]\n","repo_name":"abidkhan03/django_Photographery","sub_path":"Photographery/Learn/polls/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15530654657","text":"# Imports\r\nimport streamlit as st\r\nfrom streamlit_chat import message\r\nimport requests\r\n\r\nimport regex as re\r\n\r\nst.title(\"Chippy FastAPI\")\r\n\r\n# Streamlit input field\r\ninput_prompt = st.text_input(\"Enter a prompt\", \"What is a Large Language Model?\")\r\n\r\ndata = {\r\n \"input_prompt\": input_prompt,\r\n}\r\n\r\nplaceholder = st.empty() # placeholder for latest message\r\nmessage_history = []\r\nmessage_history.append(input_prompt)\r\n\r\nfor j, message_ in enumerate(message_history):\r\n if j % 2 == 0:\r\n message(message_, is_user=True) # display all the previous message\r\n\r\n#with placeholder.container():\r\n# message(message_history[-1]) # display the latest message\r\n\r\nres = requests.post(\"http://localhost:8000/predict/\", json=data)\r\ncleaned_answer = re.sub(\"User:.+\\n+Chip: \", \"\", res.json())\r\nmessage(cleaned_answer)\r\n\r\n## Generate output\r\n#if st.button(\"Chip it!\"):\r\n# res = requests.post(\"http://localhost:8000/predict/\", json=data)\r\n# st.markdown(res.json())","repo_name":"xaiguy/chippy","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"61"}
+{"seq_id":"2031594438","text":"\nimport json\n\n# import simplejson as json\n\nimport boto3\n\nfrom boto3.dynamodb.conditions import Key, Attr\n\n\n\ndynamodb = boto3.resource('dynamodb')\n\ntable = dynamodb.Table('basicinfo')\n\ndef lambda_handler(event, context):\n\n name = event['firstname']\n\n response = table.scan(\n FilterExpression = Attr('First name').eq(name)\n )\n response1 = table.scan(\n FilterExpression = Attr('last name').eq(name)\n )\n\n if len(response['Items']) == 0:\n if len(response1['Items']) == 0:\n return {\n 'status': 0\n }\n else:\n \n return {\n 'status': 1,\n 'body': json.dumps(response1['Items'])\n }\n else:\n \n return {\n 'status': 1,\n 'body': json.dumps(response['Items'])\n }\n","repo_name":"aryanjain1/INE-Api","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5700060416","text":"def solution(s):\n answer = 987654321\n length = len(s)\n # 1개 이상 절반까지 갯수 표현가능 / 문자열의 두번째 부터 비교 시작한다.\n # 첫번째 값을 가지고 그다음부터 비교함\n for i in range(1, length//2+1):\n check = s[:i]\n tmp = ''\n cnt = 1\n # 인덱스 슬라이싱 개념으로 접근\n for j in range(i, length+i, i):\n if check == s[j:i+j]:\n cnt += 1\n else:\n # 같은 문자열 개수에 따라 정답될 수 있는 tmp 문자열붙인다.\n if cnt != 1:\n tmp += str(cnt) + check\n else:\n tmp += check\n # 현재와 다음 문자열이 다를 경우 초기화\n check = s[j:i+j]\n cnt = 1\n if answer > len(tmp):\n answer = len(tmp)\n # 길이가 1인 경우 (문자가 1개만 주어진 경우) 최소 1 임\n if answer == 987654321:\n answer = 1\n return answer","repo_name":"wnstj-yang/Algorithm","sub_path":"Programmers/programmers_문자열 압축.py","file_name":"programmers_문자열 압축.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72938743233","text":"\"\"\"usercntroller\"\"\"\r\nimport logging.config\r\nfrom http import HTTPStatus\r\n\r\nfrom flask import Blueprint, request, make_response\r\nfrom flask.json import jsonify\r\nfrom flask.views import MethodView\r\n\r\nfrom server.rest.controller.decorators import validate_request\r\nfrom server.rest.service.user import UserService\r\n\r\nUSER_BLUEPRINT = Blueprint('user', __name__)\r\n# Preparing log configuration\r\nlogging.config.fileConfig(fname='configuration/logging.config',\r\n disable_existing_loggers=True)\r\nlogger = logging.getLogger('pyweb')\r\n\r\n\r\nclass User(MethodView):\r\n \"\"\"User view\"\"\"\r\n\r\n @staticmethod\r\n def create_user():\r\n \"\"\"POST method to create user\"\"\"\r\n logger.info(\"User post method called...\")\r\n data = request.get_json(force=True)\r\n if 'username' not in data or data['username'] == '':\r\n return make_response(jsonify({\r\n 'status': 'NOT_ACCEPTABLE',\r\n 'message': 'Username must not be empty'\r\n })), HTTPStatus.NOT_ACCEPTABLE\r\n retval, message = UserService.create_user(data)\r\n if retval == 0:\r\n return make_response(jsonify({\r\n 'status': 'OK',\r\n 'message': message\r\n })), HTTPStatus.OK\r\n else:\r\n return make_response(jsonify({\r\n 'status': 'INTERNAL_SERVER_ERROR',\r\n 'message': message\r\n })), HTTPStatus.INTERNAL_SERVER_ERROR\r\n\r\n @staticmethod\r\n def get_user():\r\n \"\"\"GET method to get user\"\"\"\r\n retval, message = UserService.get_user()\r\n if retval == 0:\r\n return make_response(jsonify(message)), HTTPStatus.OK\r\n else:\r\n return make_response(jsonify({\r\n 'status': 'INTERNAL_SERVER_ERROR',\r\n 'message': message\r\n })), HTTPStatus.INTERNAL_SERVER_ERROR\r\n\r\n @staticmethod\r\n def update_user():\r\n \"\"\"PUT method to update user by name\"\"\"\r\n logger.info(\"User PUT method called...\")\r\n data = request.get_json(force=True)\r\n if 'username' not in data or data['username'] == '':\r\n return make_response(jsonify({\r\n 'status': 'NOT_ACCEPTABLE',\r\n 'message': 'Username must not be empty'\r\n })), HTTPStatus.NOT_ACCEPTABLE\r\n retval, message = UserService.update_user(data)\r\n if retval == 0:\r\n return make_response(jsonify({\r\n 'status': 'OK',\r\n 'message': message\r\n })), HTTPStatus.OK\r\n elif retval == 1:\r\n return make_response(jsonify({\r\n 'status': 'NOT_FOUND',\r\n 'message': message\r\n })), HTTPStatus.NOT_FOUND\r\n else:\r\n return make_response(jsonify({\r\n 'status': 'INTERNAL_SERVER_ERROR',\r\n 'message': message\r\n })), HTTPStatus.INTERNAL_SERVER_ERROR\r\n\r\n @staticmethod\r\n def delete_user():\r\n \"\"\"DELETE method to update user by name\"\"\"\r\n logger.info(\"User delete method called...\")\r\n data = request.get_json(force=True)\r\n if 'username' not in data or data['username'] == '':\r\n return make_response(jsonify({\r\n 'status': 'NOT_ACCEPTABLE',\r\n 'message': 'Username must not be empty'\r\n })), HTTPStatus.NOT_ACCEPTABLE\r\n retval, message = UserService.delete_user(data)\r\n if retval == 0:\r\n return make_response(jsonify({\r\n 'status': 'OK',\r\n 'message': message\r\n })), HTTPStatus.OK\r\n elif retval == 1:\r\n return make_response(jsonify({\r\n 'status': 'NOT_FOUND',\r\n 'message': message\r\n })), HTTPStatus.NOT_FOUND\r\n else:\r\n return make_response(jsonify({\r\n 'status': 'INTERNAL_SERVER_ERROR',\r\n 'message': message\r\n })), HTTPStatus.INTERNAL_SERVER_ERROR\r\n\r\n\r\n@USER_BLUEPRINT.route(\"/api/user\", methods=['POST'])\r\n@validate_request\r\ndef createuser():\r\n \"\"\"create user end point\"\"\"\r\n return User.create_user()\r\n\r\n\r\n@USER_BLUEPRINT.route(\"/api/user\", methods=['GET'])\r\ndef getuser():\r\n \"\"\"get user end point\"\"\"\r\n return User.get_user()\r\n\r\n\r\n@USER_BLUEPRINT.route(\"/api/user\", methods=['PUT'])\r\n@validate_request\r\ndef updateuser():\r\n \"\"\"update user end point\"\"\"\r\n return User.update_user()\r\n\r\n\r\n@USER_BLUEPRINT.route(\"/api/user\", methods=['DELETE'])\r\n@validate_request\r\ndef deleteuser():\r\n \"\"\"delete user end point\"\"\"\r\n return User.delete_user()\r\n","repo_name":"Laxminarsaiah/python_flask_RESTful","sub_path":"server/rest/controller/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":4603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11225086518","text":"from model.product import Product\nfrom db.product_db import ProductDB\n\nclass ProductController:\n\n def __init__(self):\n self.__product_db = ProductDB()\n\n def create_product(self, id, name, price):\n product = Product(id, name, price)\n product = product.serialize()\n self.__product_db.insert(product)\n\n return product\n\n def update_product(self, product_id, name, price):\n data = self.__product_db.get()\n list_index = 0\n\n for index, item in enumerate(data):\n if item['id'] == product_id:\n list_index = index\n\n product = Product(product_id, name, price)\n product = product.serialize()\n\n self.__product_db.update(list_index, product)\n return product\n\n def read_product(self, product_id):\n data = self.__product_db.get()\n for item in data:\n if item['id'] == product_id:\n return item\n\n def delete_product(self, product_id):\n data = self.__product_db.get()\n list_index = 0\n\n for index, item in enumerate(data):\n if item['id'] == product_id:\n list_index = index\n\n self.__product_db.delete(list_index)\n return product_id\n\n","repo_name":"matheusreis0/crud-products","sub_path":"controller/product_controller.py","file_name":"product_controller.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5136860629","text":"from tkinter import *\r\njanela = Tk()\r\njanela.title(\"Programa 1\")\r\ntexto = Label(janela, text='Primeira Interface Gráfica')\r\ntexto.grid(column=0, row=0, padx=30, pady=30)\r\n\r\nbotao = Button(janela, text='Olá Mundo')\r\nbotao.grid(column=0, row=1, padx=10, pady=10)\r\n\r\ntexto_resposta = Label(janela, text='')\r\ntexto_resposta.grid(column=0, row=2, padx=10, pady=10)\r\n\r\n\r\n\r\n\r\njanela.mainloop()","repo_name":"M4theus1/Primeira-Interface-Grafica","sub_path":"estudo.py","file_name":"estudo.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"6067363775","text":"import copy\n\nwith open(\"C:\\\\Users\\\\nicoh\\\\advent_of_code_2022\\\\day_13\\\\input.txt\") as f: \n lines = f.readlines()\n\ndef compare(left, right):\n\n if not (isinstance(left, list) or isinstance(right, list)):\n if left == right:\n return \"equals\"\n elif left < right:\n return \"left\"\n else:\n return \"right\"\n elif isinstance(left, list) and isinstance(right, list):\n result = \"equals\"\n while result == \"equals\":\n if len(left) == 0 and len(right) > 0:\n return \"left\"\n elif len(right) == 0 and len(left) > 0:\n return \"right\"\n elif len(left) == 0 and len(right) == 0:\n return \"equals\"\n result = compare(left.pop(0), right.pop(0))\n return result\n else:\n if not isinstance(left, list):\n left = [left]\n else:\n right = [right]\n return compare(left, right)\n\npackets = []\nfor line in lines:\n line = line.rstrip()\n if line == '':\n pass\n else:\n packets.append(eval(line))\npackets.append([[2]])\npackets.append([[6]])\n\n# bubble sort!\nfor i in range(len(packets) - 1):\n for j in range(len(packets) - 1):\n result = compare(copy.deepcopy(packets[j]), copy.deepcopy(packets[j+1]))\n if result == \"right\":\n # we need to swap\n temp = packets[j]\n packets[j] = packets[j+1]\n packets[j+1] = temp\n\nfor i in range(len(packets)):\n if packets[i] == [[2]]:\n idx_2 = i + 1\n elif packets[i] == [[6]]:\n idx_6 = i + 1\nprint(idx_2 * idx_6)","repo_name":"nicohiggs/advent_of_code_2022","sub_path":"day_13/problem_2.py","file_name":"problem_2.py","file_ext":"py","file_size_in_byte":1617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"18074100827","text":"#문제1.\n# 다음 세 개의 리스트가 있을 때,\n# subs = ['I', 'You']\n# verbs = ['Play', 'Love']\n# objs = ['Hockey', 'Football']\n#\n# 3형식 문장을 모두 출력해 보세요. 반드시 comprehension을 사용합니다.\n\nsubs = ['I', 'You']\nverbs = ['Play', 'Love']\nobjs = ['Hockey', 'Football']\n\nresult=[(a,b,c) for a in subs for b in verbs for c in objs]\nresult.append(('I',\"Love\",'You'))\nfor i in result :\n print(i[0],' ',i[1],' ',i[2])","repo_name":"asd1025/practice03","sub_path":"problem01.py","file_name":"problem01.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"1385948704","text":"\"\"\"\nThis file contains the functions responsible for creating the\ntraining and testing datasets in the folder.\n\nThis file also contains a function that visualizes all grasp\ncandidates of an image.\n\"\"\"\n\nimport glob\nimport os\nimport shutil\nimport cv2\nimport random\nimport numpy as np\n\nfrom data_loader import DataLoader\nfrom parameters import Params\nfrom grasp_utils import grasps_to_bboxes\n\nparams = Params()\n\n# Statistics of each class of data\n\"\"\"{'Clothes_hanger': 5, 'walkman': 11, 'fish': 15, 'usb_drive': 24,\n 'violin': 28, 'toy_car': 31, 'insect': 35, 'fork': 37, 'bed': 42,\n 'Photo_Frame': 44, 'table': 59, 'laptop': 64, 'can': 65, 'cup': 68,\n 'cell_phone': 72, 'sword': 79, 'knife': 84, 'sofa': 86, 'vase': 107,\n 'stool': 114, 'computer_monitor': 142, 'gun': 143, 'toy_plane': 155,\n 'guitar': 175, 'bottle': 178, 'pen+pencil': 190, 'plants': 204,\n 'figurines': 219, 'Lamp': 267, 'Chair': 389}\"\"\"\n\nDATA_PATH = 'data'\n\ntop_5 = ['Chair', 'Lamp', 'figurines', 'plants', 'pen+pencil'] # cls instances -- 190\ntop_10 = ['gun', 'computer_monitor', 'toy_plane', 'guitar',\n 'bottle', 'pen+pencil', 'plants', 'figurines', 'Lamp', 'Chair'] # cls instances -- 143\n\ndef create_test(top_n_list, top_n_str, n_test_per_class):\n for cls in top_n_list:\n move_count = 0\n for img_path in glob.iglob('%s/%s/train/%s/*/*' % (DATA_PATH, top_n_str, cls)):\n if not img_path.endswith('RGB.png'):\n continue\n if move_count >= n_test_per_class:\n continue\n\n move_count += 1\n # E.g. '__.png'\n img_name = img_path.split('\\\\')[-1]\n img_var = img_name.split('_')[0]\n img_id = img_name.split('_')[1]\n\n if cls not in os.listdir(os.path.join(DATA_PATH, top_n_str, 'test')):\n os.mkdir(os.path.join(DATA_PATH, top_n_str, 'test', cls))\n if img_id not in os.listdir(os.path.join(DATA_PATH, top_n_str, 'test', cls)):\n os.mkdir(os.path.join(DATA_PATH, top_n_str, 'test', cls, img_id))\n\n for file in glob.glob('%s/%s/train/%s/%s/%s_%s*' % (DATA_PATH, top_n_str, cls, img_id, img_var, img_id)):\n name = file.split('\\\\')[-1]\n shutil.move(file, '%s/%s/test/%s/%s/%s' % (DATA_PATH, top_n_str, cls, img_id, name))\n\ndef create_top_n(top_n_list, top_n_str, n_img_per_class):\n if top_n_str not in os.listdir(DATA_PATH):\n os.mkdir(os.path.join(DATA_PATH, top_n_str))\n os.mkdir(os.path.join(DATA_PATH, top_n_str, 'train'))\n os.mkdir(os.path.join(DATA_PATH, top_n_str, 'test'))\n \n for cls in top_n_list:\n n_img = 0\n if cls not in os.listdir(os.path.join(DATA_PATH, top_n_str, 'train')):\n os.mkdir(os.path.join(DATA_PATH, top_n_str, 'train', cls))\n if cls not in os.listdir(os.path.join(DATA_PATH, top_n_str, 'test')):\n os.mkdir(os.path.join(DATA_PATH, top_n_str, 'test', cls))\n img_list = []\n for img_path in glob.iglob('%s/*/%s/*/*' % (DATA_PATH, cls)):\n img_cls = img_path.split('\\\\')[-3]\n # E.g. '__.png'\n img_name = img_path.split('\\\\')[-1]\n img_var = img_name.split('_')[0]\n img_id = img_name.split('_')[1]\n\n if img_var + '_' + img_id not in img_list:\n img_list.append(img_var + '_' + img_id)\n n_img += 1\n if n_img >= n_img_per_class:\n continue\n\n if img_id not in os.listdir(os.path.join(DATA_PATH, top_n_str, 'train', cls)):\n os.mkdir(os.path.join(DATA_PATH, top_n_str, 'train', cls, img_id))\n \n shutil.copyfile(img_path, os.path.join(DATA_PATH, top_n_str, 'train', cls, img_id, img_name))\n\n\ndef count():\n cls_list = []\n with open(os.path.join('data', 'cls.txt'), 'r') as f:\n file = f.readlines()\n for cls in file:\n # remove '\\n' from string\n cls = cls[:-1]\n cls_list.append(cls)\n\n img_id_dict = {}\n for img_path in glob.iglob('%s/*/*/*/*' % 'data'):\n if not img_path.endswith('RGB.png'):\n continue\n \n img_cls = img_path.split('\\\\')[-3]\n # E.g. '__.png'\n img_name = img_path.split('\\\\')[-1]\n img_var = img_name.split('_')[0]\n img_id = img_name.split('_')[1]\n img_id_with_var = img_var + '_' + img_id\n img_id_dict[img_id_with_var] = img_cls\n\n cls = list(img_id_dict.values())\n cls_dict = {}\n for i in range(30):\n cls_dict[cls_list[i]] = cls.count(cls_list[i])\n\n ordered_cls_dict = {k: v for k, v in sorted(cls_dict.items(), key=lambda item: item[1])}\n print(ordered_cls_dict)\n\n\ndef create_cls_txt(cls_list, file_path):\n with open(file_path, 'w') as f:\n for cls in cls_list:\n f.write(cls)\n f.write('\\n')\n f.close()\n\n\ndef find_grasp_file():\n \"\"\"\n Missing grasp files:\n Chair 1_4f4ce917619e3d8e3227163156e32e3c_grasps.txt\n Chair 3_4f4ce917619e3d8e3227163156e32e3c_grasps.txt\n Chair 0_5d60590d192c52553a23b8cb1a985a11_grasps.txt\n Chair 1_5d60590d192c52553a23b8cb1a985a11_grasps.txt\n Chair 2_5d60590d192c52553a23b8cb1a985a11_grasps.txt\n Chair 3_5d60590d192c52553a23b8cb1a985a11_grasps.txt\n Chair 4_5d60590d192c52553a23b8cb1a985a11_grasps.txt\n deleted from top_5/train alr\n \"\"\"\n ls = glob.glob('%s/*/*/*.txt' % 'data/item-grasp')\n file_ls = [path.split('\\\\')[-1] for path in ls]\n print(len(file_ls))\n input()\n total = 0\n no_match = 0\n for img_path in glob.iglob('%s/*/*/*/*' % 'data/top_5'):\n if not img_path.endswith('RGB.png'):\n continue\n \n img_cls = img_path.split('\\\\')[-3]\n # E.g. '__grasps.txt'\n img_name = img_path.split('\\\\')[-1]\n img_var = img_name.split('_')[0]\n img_id = img_name.split('_')[1]\n img_grasp_name = img_var + '_' + img_id + '_grasps.txt'\n\n total += 1\n if img_grasp_name not in file_ls:\n print(img_cls, img_grasp_name)\n no_match += 1\n\n return no_match, total\n\n\ndef get_grasp_files():\n train_ls = glob.glob('%s/*/*/*RGB.png' % 'data/top_5/train')\n train_file_ls = [path.split('\\\\')[-1] for path in train_ls]\n test_ls = glob.glob('%s/*/*/*RGB.png' % 'data/top_5/test')\n test_file_ls = [path.split('\\\\')[-1] for path in test_ls]\n for img_path in glob.iglob('%s/*/*/*.txt' % 'data/item-grasp'):\n img_cls = img_path.split('\\\\')[-3]\n # E.g. '__grasps.txt'\n img_name = img_path.split('\\\\')[-1]\n img_var = img_name.split('_')[0]\n img_id = img_name.split('_')[1]\n img_rgb_name = img_var + '_' + img_id + '_RGB.png'\n\n if img_rgb_name in test_file_ls:\n shutil.copyfile(img_path, 'data/top_5/test/%s/%s/%s' % (img_cls, img_id, img_name))\n elif img_rgb_name in train_file_ls:\n shutil.copyfile(img_path, 'data/top_5/train/%s/%s/%s' % (img_cls, img_id, img_name))\n else:\n print(img_cls, img_name)\n\n\ndef test_data_loader():\n \"\"\"Identical dataloader process as written in data_loader.py.\"\"\"\n data_loader = DataLoader(params.TRAIN_PATH, 2, params.TRAIN_VAL_SPLIT)\n for img, label, candidates in data_loader.load_grasp():\n target_bbox = grasps_to_bboxes(label)\n target_bboxes = grasps_to_bboxes(candidates)\n\n img_vis = np.array(img.cpu())\n img_r = np.clip((img_vis[:, 0, :, :] * 0.229 + 0.485) * 255, 0, 255)\n img_g = np.clip((img_vis[:, 1, :, :] * 0.224 + 0.456) * 255, 0, 255)\n img_d = img_vis[:, 2, :, :][0]\n \n img_bgr = np.concatenate((img_g, img_g, img_r), axis=0)\n img_bgr = np.moveaxis(img_bgr, 0, -1)\n img_bgr = np.ascontiguousarray(img_bgr, dtype=np.uint8)\n \n draw_bbox(img_bgr, target_bbox[0], (255, 0, 0))\n for bbox in target_bboxes:\n # Choose some random bboxes to show:\n if random.randint(0, 5) == 0:\n draw_bbox(img_bgr, bbox, (0, 255, 0))\n\n cv2.imshow('img', img_bgr)\n cv2.waitKey(0)\n\n\ndef draw_bbox(img, bbox, color):\n x1 = int(bbox[0] / 1024 * params.OUTPUT_SIZE)\n y1 = int(bbox[1] / 1024 * params.OUTPUT_SIZE)\n x2 = int(bbox[2] / 1024 * params.OUTPUT_SIZE)\n y2 = int(bbox[3] / 1024 * params.OUTPUT_SIZE)\n x3 = int(bbox[4] / 1024 * params.OUTPUT_SIZE)\n y3 = int(bbox[5] / 1024 * params.OUTPUT_SIZE)\n x4 = int(bbox[6] / 1024 * params.OUTPUT_SIZE)\n y4 = int(bbox[7] / 1024 * params.OUTPUT_SIZE)\n cv2.line(img, (x1, y1), (x2, y2), color, 1)\n cv2.line(img, (x2, y2), (x3, y3), (0, 0, 255), 1)\n cv2.line(img, (x3, y3), (x4, y4), color, 1)\n cv2.line(img, (x4, y4), (x1, y1), (0, 0, 255), 1)\n\n\nif __name__ == '__main__':\n # Get dataset statistics\n #count()\n # Separate and create train/test dataset folders for CLS training\n #create_cls_txt(top_10, '%s/cls_top_10.txt' % DATA_PATH)\n #create_top_n(top_10, 'top_10', 143)\n #create_test(top_10, 'top_10', 15)\n # Add grasping .txt files to the train/test dataset folders\n #no_match, total = find_grasp_file()\n #print(no_match, total)\n #get_grasp_files()\n # Visualize Grasp training data to make sure it all makes sens\n test_data_loader()","repo_name":"stevolopolis/GrTrainer","sub_path":"scratch.py","file_name":"scratch.py","file_ext":"py","file_size_in_byte":9359,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"23371937531","text":"import sys\r\nimport logging\r\n\r\ndef saving_the_universe(engines, queries, level=0):\r\n visited = set()\r\n count = 0\r\n for q in queries:\r\n if q not in visited:\r\n visited.add(q)\r\n else:\r\n log.debug('')\r\n \r\n if len(visited) == len(engines):\r\n visited.clear()\r\n visited.add(q)\r\n count += 1\r\n return count\r\n\r\n\r\n# log initialization\r\nlogging.basicConfig()\r\nlog = logging.getLogger(__name__)\r\n#log.setLevel(logging.DEBUG)\r\nlog.setLevel(logging.INFO)\r\n\r\n# open files\r\ninput = open(sys.argv[1], 'r')\r\noutput = open('saving_the_universe.out', 'w')\r\n\r\n# read input\r\nlines = input.readlines()\r\n\r\n# N - number of cases\r\nN = int(lines[0])\r\ndel lines[0]\r\n\r\nfor case in range(N):\r\n engines = []\r\n queries = []\r\n\r\n #S - the number of search engines\r\n S = int(lines[0])\r\n del lines[0]\r\n\r\n for engine in range(S):\r\n engines.append(lines[0].strip())\r\n del lines[0]\r\n\r\n #Q - the number of incoming queries\r\n Q = int(lines[0])\r\n del lines[0]\r\n\r\n for query in range(Q):\r\n queries.append(lines[0].strip())\r\n del lines[0]\r\n\r\n log.info('Case #' + str(case+1) + ': ' + str(saving_the_universe(engines, queries)) + '\\n')\r\n output.write('Case #' + str(case+1) + ': ' + str(saving_the_universe(engines, queries)) + '\\n')\r\n\r\ninput.close()\r\noutput.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_1/350.py","file_name":"350.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32313656242","text":"import torch\nfrom unittest import TestCase\n\nfrom src.modules.masked_linear import MaskedLinear, add_masks_to_module\n\n\nINPUTS = (torch.arange(0, 10).unsqueeze(0).unsqueeze(0).float() + 1) / 10.0\n\n\nclass _MockModel(torch.nn.Module):\n def __init__(self):\n super().__init__()\n self.linear1 = torch.nn.Linear(10, 10)\n self.linear2 = torch.nn.Linear(3, 3)\n self.other = torch.nn.BatchNorm1d(10)\n\n\nclass MaskedLinearTest(TestCase):\n\n \"\"\"Test cases for pruning unsaturated activations.\n \n Most of these test cases utilize the RnnNorm, i.e. assume close to zero == unsaturated.\n \"\"\"\n\n def test_masked_linear(self):\n torch.random.manual_seed(1066)\n inputs = torch.randn(10)\n linear = torch.nn.Linear(10, 10)\n masked_linear = MaskedLinear.convert(linear)\n\n torch.testing.assert_allclose(masked_linear(inputs), linear(inputs))\n masked_linear.mask.data.fill_(0.)\n torch.testing.assert_allclose(masked_linear(inputs), linear.bias)\n\n def test_add_masks_to_model_sequential(self):\n torch.random.manual_seed(37)\n model = torch.nn.Sequential(\n torch.nn.Linear(10, 10),\n torch.nn.ReLU(),\n torch.nn.Linear(10, 10),\n torch.nn.Softmax(dim=-1),\n )\n add_masks_to_module(model)\n\n modules = list(model.children())\n assert isinstance(modules[0], MaskedLinear)\n assert isinstance(modules[1], torch.nn.ReLU)\n assert isinstance(modules[2], MaskedLinear)\n assert isinstance(modules[3], torch.nn.Softmax)\n \n def test_add_masks_to_model_update_attr_refs(self):\n model = _MockModel()\n add_masks_to_module(model)\n self.assertIsInstance(model.linear1, MaskedLinear)\n self.assertIsInstance(model.linear2, MaskedLinear)\n self.assertIsInstance(model.other, torch.nn.BatchNorm1d)\n","repo_name":"viking-sudo-rm/saturated-sgd","sub_path":"src/tests/modules/test_masked_linear.py","file_name":"test_masked_linear.py","file_ext":"py","file_size_in_byte":1886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72196975875","text":"from pip._vendor import requests\n\nfrom functions.functions import CircleAreaFunction\n\n\ndef get_random_circle_area():\n url = 'https://www.random.org/integers/'\n params = {\n 'num': 1,\n 'min': 1,\n 'max': 10,\n 'col': 1,\n 'base': 10,\n 'format': 'plain',\n 'rnd': 'new',\n }\n try:\n response = requests.get(url=url, params=params)\n except ConnectionError:\n return 'Error', 'Error'\n\n radius = int(response.content)\n circle_function = CircleAreaFunction(radius)\n circle_function.solve()\n answer = circle_function.answer[0]\n return radius, answer\n","repo_name":"Ingwar121/workshop","sub_path":"functions/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"11975155287","text":"import os\n\nfrom client import MyClient\n\nif __name__ == '__main__':\n bot = 'staria'\n print('start', bot)\n # this is a application token\n token = os.environ.get(bot)\n\n # pass unique str\n client = MyClient(bot)\n client.post_works.start(19, 30)\n client.post_sleep.start(21, 30)\n print('end', bot)\n client.run(token)","repo_name":"s0ngkran/discord-bot","sub_path":"c1.py","file_name":"c1.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23943194004","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Jun 9 10:11:38 2022\r\n\r\n@author: Rephayah\r\n\"\"\"\r\nimport numpy as np\r\n\r\nv=1\r\ngridcols = 8\r\ngridrows = 7\r\nn = gridcols\r\nb = gridrows\r\n\r\ncoords = []\r\nfor i in range(1,b+1):\r\n for j in range(1, n+1):\r\n coords.append([i,j])\r\n \r\nprint(coords)\r\ncoords = [str(x) for x in coords]\r\nc = []\r\nfor p in range(len(coords)):\r\n q= coords[p].split(\"[\") #Remove closing parenthese\r\n c.append(q)\r\nf = []\r\nfor a in range(len(c)):\r\n g = c[a][1]\r\n f.append(g)\r\n \r\nd = []\r\nfor l in range(len(f)):\r\n t = f[l].split(\"]\")\r\n d.append(t)\r\n \r\ne = []\r\nfor l in range(len(f)):\r\n h = d[l][0]\r\n e.append(h)\r\n\r\nz = []\r\nfor l in range(len(f)):\r\n ahhh = e[l].replace(\", \", \"_\")\r\n z.append(ahhh)\r\n\r\n\r\n# z = z[gridcols+2:]\r\n# print(z)\r\n# with open('Pilot.txt') as f:\r\n# lines = f.readlines()\r\n \r\n# MainDirectory = lines[0][16:-1]\r\n# MainDirectory = MainDirectory.replace(\"\\\\\",\"/\")\r\n# n = lines[1][-2]\r\n# ImageJMacrosDirectory = lines[2][25:-1]\r\n# ImageJMacrosDirectory = ImageJMacrosDirectory.replace(\"\\\\\",\"/\")\r\n# BatchFileMacrosDirectory = lines[3][23:-1]\r\n# BatchFileMacrosDirectory = BatchFileMacrosDirectory.replace(\"\\\\\",\"/\")\r\n# PathtoFiji = lines[4][14:-1]\r\n# SendToEmail = lines[5][12:-1]\r\n# WorkStationEmail = lines[6][23:-1]\r\n# Password = lines[7][10:-1]\r\n# ProjectName = lines[8][14:-1]\r\n# # gridsize = lines[9][10:]\r\n\r\n# directory = MainDirectory\r\n# path = ImageJMacrosDirectory\r\n# print(z)\r\n# n = gridsize #Number of regions\r\nimport pandas as pd\r\nimport csv\r\n# for j in range(1,n+1):\r\n# PreprocessedMacroLine = 'run(\"Grid/Collection stitching\", \"type=[Filename defined position] order=[Defined by filename ] grid_size_x=3 grid_size_y=3 tile_overlap=10 first_file_index_x=0 first_file_index_y=0 directory=['+'{}'.format(MainDirectory)+'/tif'+ '] file_names=step0_{y}_{x}.tif output_textfile_name=TileConfiguration_Preprocessed.txt fusion_method=[Linear Blending] regression_threshold=0.30 max/avg_displacement_threshold=2.50 absolute_displacement_threshold=3.50 compute_overlap computation_parameters=[Save memory (but be slower)] image_output=[Fuse and display]\");'\r\n \r\nL2 = []\r\nfor j in range(1,v+1):\r\n for i in range(len(z)):\r\n L1 = '''open(\"/BlN/step{}_{}.BlN_crop.tif\");'\r\n 'selectWindow(\"step{}_{}.BlN_crop.tif\");'''.format(j,z[i],j,z[i])\r\n L2.append(L1)\r\n\r\n# path = r'C:\\Users\\repha\\Documents\\Grad School\\Research\\Scripts\\SEM-DIC\\Works on Marshawn'\r\nL19 = 'run(\"Images to Stack\", \"name=Stack title=[] use\");' #Giving Error in Batch\r\n\r\nL20 = '//run(\"Brightness/Contrast...\");'\r\nL2.append(L19)\r\nL2.append(L20)\r\nSad = np.array(L2, dtype=object)\r\nHappy = pd.Series(Sad)\r\nConfused = pd.DataFrame(Happy).replace(' ',' ')\r\n# Confused.to_csv(path+'/Test.ijm', float_format=None, index=False, mode ='w', header=False, sep='\\t', quoting=csv.QUOTE_NONE, escapechar = '\\t')\r\n","repo_name":"AlloyinIllinoisan/DIC-SEM","sub_path":"Automation_at_its_finest/Good to Go/Creates_Grid.py","file_name":"Creates_Grid.py","file_ext":"py","file_size_in_byte":2898,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"11108781611","text":"import pytest\n\nfrom werkzeug.datastructures import FileStorage\nfrom lib.py3rumcajs.helpers.file_processing import (validate_file,\n validate_extension,\n validate_by_1stline,\n parse_to_dict,\n )\n\n\ndef test_validate_file(testfile, test_stuff_path):\n filepath = test_stuff_path + testfile\n with open(filepath, 'r') as fp:\n file = FileStorage(fp)\n assert validate_file(file) == True\n\n\ndef test_validate_file_extension(testfile, test_stuff_path):\n filepath = test_stuff_path + testfile\n with open(filepath, 'r') as fp:\n file = FileStorage(fp)\n assert validate_extension(file) == True\n\n\ndef test_validate_by1stline(testfile, test_stuff_path):\n filepath = test_stuff_path + testfile\n with open(filepath, 'r') as fp:\n file = FileStorage(fp)\n assert validate_by_1stline(file) == True\n\n\ndef test_validate_file_by_regex_fail(fail_testfile, test_stuff_path):\n filepath = test_stuff_path + fail_testfile\n with open(filepath, 'r') as fp:\n file = FileStorage(fp)\n assert validate_file(file) == False\n\n\ndef test_parse(testfile, test_stuff_path):\n data = parse_to_dict(testfile)\n assert data['data'] != []\n assert data['name'] == testfile\n assert type(data['y_prefix']) == str\n assert type(data['x_prefix']) == str\n\n\n@pytest.mark.skip(reason=\"no implemented feture yet\")\ndef test_rescale_data():\n raise\n","repo_name":"n0npax/turbo-rumcajs","sub_path":"lib/py3rumcajs/tests/helpers/test_file_processing.py","file_name":"test_file_processing.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72396135873","text":"#\n# Plugin load tests for eggs\n#\n\nimport os\nimport sys\nfrom os.path import abspath, dirname\ncurrdir = dirname(abspath(__file__)) + os.sep\n\nimport pyutilib.th as unittest\nimport pyutilib.subprocess\n\ntry:\n import pkg_resources\n pkg_resources_avail = True\nexcept ImportError:\n pkg_resources_avail = False\ntry:\n import yaml\n yaml_available = True\nexcept ImportError:\n yaml_available = False\n\n\n@unittest.skipIf(not pkg_resources_avail, \"Cannot import 'pkg_resources'\")\nclass Test(pyutilib.th.TestCase):\n\n def test_egg1(self):\n #\n # Load an egg for the 'project1' project.\n # Eggs are loaded in the 'eggs1' directory, but only the Project1 stuff is actually imported.\n #\n pyutilib.subprocess.run(\n [sys.executable, currdir + os.sep + \"egg1.py\", currdir, \"json\"])\n self.assertMatchesJsonBaseline(currdir + \"egg1.out\",\n currdir + \"egg1.jsn\")\n if yaml_available:\n pyutilib.subprocess.run(\n [sys.executable, currdir + os.sep + \"egg1.py\", currdir, \"yaml\"])\n self.assertMatchesYamlBaseline(currdir + \"egg1.out\",\n currdir + \"egg1.yml\")\n\n def test_egg2(self):\n #\n # Load an egg for the 'project1' project.\n # Eggs are loaded in the 'eggs1' and 'eggs2' directories, but only the \n # Project1 and Project 3 stuff is actually imported.\n #\n pyutilib.subprocess.run(\n [sys.executable, currdir + os.sep + \"egg2.py\", currdir, \"json\"])\n self.assertMatchesJsonBaseline(currdir + \"egg2.out\",\n currdir + \"egg2.jsn\")\n if yaml_available:\n pyutilib.subprocess.run(\n [sys.executable, currdir + os.sep + \"egg2.py\", currdir, \"yaml\"])\n self.assertMatchesYamlBaseline(currdir + \"egg2.out\",\n currdir + \"egg2.yml\")\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"PyUtilib/pyutilib","sub_path":"pyutilib/component/loader/tests/test_egg.py","file_name":"test_egg.py","file_ext":"py","file_size_in_byte":2013,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"61"}
+{"seq_id":"6970889050","text":"import csv\n\n\ndef main():\n INUMBER_INDEX = 0\n students_dict = read_dict(\"students.csv\", INUMBER_INDEX)\n print(students_dict)\n search = str(input(\"Please enter an I-Number (xxxxxxxxx): \"))\n print (students_dict.get(search,'No such student.'))\n\n\ndef read_dict(filename, key_column_index):\n \"\"\"Read the contents of a CSV file into a compound\n dictionary and return the dictionary.\n\n Parameters\n filename: the name of the CSV file to read.\n key_column_index: the index of the column\n to use as the keys in the dictionary.\n Return: a compound dictionary that contains\n the contents of the CSV file.\n \"\"\"\n dictionary = {}\n with open(filename, \"rt\") as csv_file:\n reader = csv.reader(csv_file)\n next(reader)\n for row_list in reader:\n if len(row_list) != 0:\n key = row_list[key_column_index]\n dictionary[key] = row_list[1]\n return dictionary\n\nif __name__ == \"__main__\":\n main()","repo_name":"emfernandezv/BYU-Idaho-School-Work","sub_path":"CSE111 Programming with Functions/students.py","file_name":"students.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32216703265","text":"import torch\nimport torch.nn as nn\nfrom torchcrf import CRF\nfrom transformers import BertTokenizer, AlbertModel, AlbertConfig\nimport sys\n\nsys.path.append('/home/sy/project/albert_srl/')\n\nfrom utils.log import logger\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\ndef load_tokenizer(model_path, special_token):\n logger.info('loading tokenizer {}'.format(model_path))\n tokenizer = BertTokenizer.from_pretrained(model_path)\n if special_token:\n tokenizer.add_special_tokens(special_token)\n return tokenizer\n\ndef load_config(pretrained_model_path, tokenizer):\n albertConfig = AlbertConfig.from_pretrained(pretrained_model_path,\n cls_token_id=tokenizer.cls_token_id,\n sep_token_id=tokenizer.sep_token_id,\n pad_token_id=tokenizer.pad_token_id,\n unk_token_id=tokenizer.unk_token_id,\n output_attentions=False, # whether or not return [attentions weights]\n output_hidden_states=False) # whether or not return [hidden states]\n return albertConfig\n\ndef load_pretrained_model(pretrained_model_path, tokenizer, special_token):\n logger.info('loading pretrained model {}'.format(pretrained_model_path))\n albertConfig = load_config(pretrained_model_path, tokenizer)\n model = AlbertModel.from_pretrained(pretrained_model_path, config=albertConfig)\n\n if special_token:\n # resize special token\n model.resize_token_embeddings(len(tokenizer))\n\n return model, albertConfig\n\ndef build_model(albertConfig):\n logger.info('build albertmodel!')\n model = AlbertModel(config=albertConfig)\n return model\n\nclass AlbertCrf(nn.Module):\n def __init__(self, config, pretrained_model, tag_num):\n super(AlbertCrf, self).__init__()\n self.config = config\n self.model = pretrained_model\n self.dropout = nn.Dropout(self.config.hidden_dropout_prob)\n self.classifier = nn.Linear(self.config.hidden_size + 1, tag_num) # add predicates indicator\n self.crf = CRF(num_tags=tag_num, batch_first=True)\n\n def loss(self, input_idx, token_type_ids=None, attention_mask=None, predicates=None, labels=None, label_mask=None):\n outputs = self.model(input_ids=input_idx, attention_mask=attention_mask, token_type_ids=token_type_ids)\n sequence_output = outputs[0]\n sequence_output = torch.cat((sequence_output, predicates.unsqueeze(-1)), -1)\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n # outputs = (logits,)s\n loss = self.crf(emissions=logits, tags=labels, mask=label_mask.byte())\n # outputs = (-1 * loss,) + outputs\n # return outputs # (loss), scores\n return loss\n\n def forward(self, input_idx, token_type_ids=None, attention_mask=None, predicates=None, label_mask=None):\n outputs = self.model(input_ids=input_idx, attention_mask=attention_mask, token_type_ids=token_type_ids)\n sequence_output = outputs[0]\n sequence_output = torch.cat((sequence_output, predicates.unsqueeze(-1)), -1)\n sequence_output = self.dropout(sequence_output)\n logits = self.classifier(sequence_output)\n tags = self.crf.decode(emissions=logits, mask=label_mask.byte())\n return tags\n\n","repo_name":"jiangnanboy/albert_srl","sub_path":"srl/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"61"}
+{"seq_id":"70929860035","text":"class Retangulo:\n def __init__(self, ladoA, ladoB):\n self.ladoA = ladoA\n self.ladoB = ladoB\n self.area = self.ladoA*self.ladoB\n self.perimetro = 2*self.ladoA + 2*self.ladoB\n\n def mudaLados(self, ladoA, ladoB):\n self.ladoA = ladoA\n self.ladoB = ladoB\n self.area = ladoA*ladoB\n self.perimetro = 2*ladoA + 2*ladoB\n \n def retornaLadoA(self):\n return self.ladoA\n \n def retornaLadoB(self):\n return self.ladoB\n \n def calculaArea(self):\n self.area = self.ladoA*self.ladoB\n return self.area\n \n def calculaPerimetro(self):\n self.perimetro = 2*self.ladoA + 2*self.ladoB\n return self.perimetro\n\na = float(input(print(\"Digite o primeiro lado:\")))\nb = float(input(print(\"Digite o segundo lado:\")))\nobjeto = Retangulo(a, b)\nif (objeto.area % 2 == 0):\n pisos = objeto.area//2 #pisos de 2 m²\nelse:\n pisos = objeto.area//2 + 1\nif (objeto.perimetro % 4 == 0):\n rodapes = objeto.perimetro//4 #rodapés de 4 m\nelse:\n rodapes = objeto.perimetro//4 + 1\nprint(\"Quantidade de pisos: %d\"%(pisos))\nprint(\"Quantidade de rodapés: %d\"%(rodapes))","repo_name":"leotanaka4/LP-21.2","sub_path":"Classes/Classes03.py","file_name":"Classes03.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"33701736591","text":"from flask import Flask, send_file, render_template, jsonify, request\nfrom flask_cors import CORS\nimport pandas as pd\nimport os\nimport psycopg2\nimport sqlalchemy as sa\nfrom db_setup import setup\n\nengine = sa.create_engine('postgresql://docker:docker@postgres:5432/default')\napp = Flask(__name__, template_folder='templates')\nCORS(app)\n\n@app.route('/')\ndef home():\n rows = pd.read_sql(\"select count(*) from bus\", engine).iloc[0]['count']\n return render_template('index.html', rows = rows)\n\n@app.route('/speed')\ndef getSpeed():\n route_id = request.args.get('route_id')\n if not route_id:\n route_id = 'B41'\n\n date = request.args.get('date')\n start_time = request.args.get('start')\n end_time = request.args.get('end')\n\n bus_positions_B41 = pd.read_sql(f\"\"\"\n select timestamp, trip_id, longitude, latitude from bus \n where route_id = '{route_id}' \n \"\"\", engine)\n\n bus_positions_B41['timestamp'] = pd.to_datetime(bus_positions_B41['timestamp'])\n\n\n return jsonify(bus_positions_B41.to_dict(orient = 'records'))\n\nif __name__ == '__main__':\n setup(engine)\n port = int(os.environ.get('PORT', 5000))\n app.run(debug=True, host='0.0.0.0', port=port)","repo_name":"zhik/flask_sample","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"71125141635","text":"from views import RegressionWidget,RegressionConfWidget,PredictionWidget\r\nfrom model.infrastructure.observer import Observer\r\nfrom .PredictionController import PredictionController\r\nfrom .RegressionConfController import RegressionConfController\r\nfrom .ClassifierWorker import ClassifierWorker\r\nfrom model.Classifier import Classifier\r\nclass RegressionController(Observer):\r\n def __init__(self,model,view):\r\n super().__init__(model)\r\n self.model=model\r\n self.view=view\r\n self.classifier=Classifier(self.model)\r\n #Agregando widget de configuración\r\n self.conf=RegressionConfWidget(self.view)\r\n self.ctl_conf=RegressionConfController(self.model,self.conf,self.classifier)\r\n self.view.widget_list.addWidget(self.conf)\r\n #Agregando widget de predicción\r\n self.prediction=PredictionWidget(self.view)\r\n self.ctl_prediction=PredictionController(self.model,self.prediction,self.classifier)\r\n self.view.widget_list.addWidget(self.prediction)\r\n\r\n self.view.widget_list.setCurrentIndex(0)\r\n self.bind_signals()\r\n\r\n def bind_signals(self):\r\n self.conf.btn_calcular.pressed.connect(self.show_prediction)\r\n self.conf.btn_calcular.pressed.connect(self.ctl_prediction.set_dependiente)\r\n self.prediction.btn_conf.pressed.connect(self.show_conf)\r\n\r\n def show_conf(self):\r\n self.view.widget_list.setCurrentIndex(0)\r\n self.conf.scroll.verticalScrollBar().setValue(0)\r\n\r\n def show_prediction(self):\r\n self.view.widget_list.setCurrentIndex(1)\r\n self.prediction.scroll.verticalScrollBar().setValue(0)\r\n\r\n def end_loading(self,int):\r\n self.view.loaded.emit(40)\r\n\r\n def notify(self,model,*args,**kwargs):\r\n self.view.widget_list.setCurrentIndex(0) #Se debe recalcular el modelo\r\n if len(self.model.num_cols)>1 and len(self.model.objects)>0:\r\n self.ctl_conf.set_model()\r\n self.ctl_prediction.set_model()\r\n self.view.scrollArea.show()\r\n else:\r\n print(\"No tiene datos númericos\")\r\n self.view.scrollArea.hide()\r\n self.end_loading(100)\r\n","repo_name":"elagabalus01/myner","sub_path":"src/controllers/Regression/RegressionController.py","file_name":"RegressionController.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"27590430436","text":"import os\nfrom cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes\nimport PySimpleGUI as sg\nfrom cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305\nfrom cryptography.fernet import Fernet, InvalidToken\nfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM\n\n\ndef fernetDecrypt(input_file, key, output_file):\n with open(input_file, 'rb') as f:\n data = f.read()\n\n actualdata = data[16:]\n fernet = Fernet(key)\n\n # output_file = f\"Dec-{input_file}\"\n\n try:\n\n decrypted = fernet.decrypt(actualdata)\n\n with open(output_file, 'wb') as f:\n f.write(decrypted)\n\n except:\n print(\"Invalid Key\")\n sg.popup('INVALID KEY')\n\n\ndef aesDecrypt(data, key, output_file):\n print(\"AES-CBC DECRYPTION\")\n actualdata = data[16:-16]\n iv = data[-16:]\n cipher = Cipher(algorithms.AES(key), modes.CBC(iv))\n decryptor = cipher.decryptor()\n try:\n decrypted = decryptor.update(actualdata) + decryptor.finalize()\n with open(output_file, 'wb') as f:\n f.write(decrypted)\n print(\"AES-CBC DECRYPTION SUCCESSFUL\")\n except:\n print(\"INVALID KEY\")\n sg.popup('INVALID KEY')\n\n\ndef chacha20poly1305Decrypt(data, key, aad, output_file):\n print(\"Chacha Decrypt\")\n nonce = data[-12:]\n actualdata = data[16:-12]\n chacha = ChaCha20Poly1305(key)\n try:\n decrypted = chacha.decrypt(nonce, actualdata, aad)\n with open(output_file, 'wb') as f:\n f.write(decrypted)\n print(\"Chacha Decryption Successful\")\n except:\n print(\"EITHER INVALID KEY OR INVALID ASSOCIATED DATA\")\n sg.popup('EITHER INVALID KEY OR INVALID ASSOCIATED DATA')\n\n\ndef aesgcmDecrypt(data, key, aad, output_file):\n print(\"AES-GCM DECRYPTION\")\n aesgcm = AESGCM(key)\n nonce = data[-12:]\n actualdata = data[16:-12]\n try:\n decrypted = aesgcm.decrypt(nonce, actualdata, aad)\n with open(output_file, 'wb') as f:\n f.write(decrypted)\n print(\"AES-GCM DECRYPTION SUCCESSFUL\")\n except:\n print(\"EITHER INVALID KEY OR INVALID ASSOCIATED DATA\")\n sg.popup('EITHER INVALID KEY OR INVALID ASSOCIATED DATA')\n\n\ndef tdesDecrypt(data, key, output_file):\n print(\"Triple DES DECRYPTION\")\n actualdata = data[16:-8]\n iv = data[-8:]\n cipher = Cipher(algorithms.TripleDES(key), modes.CBC(iv))\n decryptor = cipher.decryptor()\n try:\n decrypted = decryptor.update(actualdata) + decryptor.finalize()\n with open(output_file, 'wb') as f:\n f.write(decrypted)\n print(\"Triple DES DECRYPTION SUCCESSFUL\")\n except:\n print(\"INVALID KEY\")\n sg.popup('INVALID KEY')\n","repo_name":"ayaachi-jha/encrypty","sub_path":"utils/SymmetricDecryption.py","file_name":"SymmetricDecryption.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"39539805874","text":"import re\nfrom typing import Callable\nimport streamlit as st\nimport sys\nfrom streamlit import cli as stcli\n\n\ninterface_input = Callable[[], str]\ninterface_output = Callable[[str], None]\n\n\ndef CLI_input() -> str:\n \"\"\"Implement Command Line Interface Input\"\"\"\n url = input(\"Enter the youtube video URL:\")\n while not re.search(r\"^https:.+=.{3,}$\", url):\n url = input(\"Enter the youtube video URL:\")\n return url\n\n\ndef CLI_output(filename: str) -> None:\n \"\"\"Implement Command Line Interface Output\"\"\"\n print(f\"Wordcloud saved as {filename}\")\n\n\ndef streamlit_input() -> str:\n \"\"\"Implement Streamlit Interface Input\"\"\"\n if st._is_running_with_streamlit:\n st.title(\"Generate a Wordcloud from a youtube video\")\n url = st.text_input(\"Enter the youtube video URL\")\n if not re.search(r\"^https:.+=.{3,}$\", url):\n st.write(\"Enter a youtube video URL\")\n else:\n st.write(\"Processing\")\n return url\n else:\n sys.argv = [\"streamlit\", \"run\", sys.argv[0]]\n sys.exit(stcli.main())\n\n\ndef streamlit_output(filename: str) -> None:\n \"\"\"Implement Streamlit Interface Output\"\"\"\n st.write(f\"Done. Wordcloud saved as {filename}\")\n st.image(filename)\n","repo_name":"Guillaume-Fgt/Wordcloud_Youtube","sub_path":"wordcloud_youtube/interface.py","file_name":"interface.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"26588375788","text":"#Arithmetic operators\nx = 5\ny = 2\nprint ( \"x ** y = {0}\".format( x ** y) )\nprint ( \"x / y = {0}\".format( x / y) )\nprint ( \"x // y = {0}\".format( x // y) )\n#ceil\n\n\n#Assignment operators\nx = 4\ny = 3\nprint ('4 & 3 = {0}'.format(4 & 3))\n\nx = 5\ny = 3\nprint ('5 & 3 = {0}'.format(5 & 3))\n\n\n\nprint ( \"x ^ y = {0}\".format( x ^ y) ) # exclusive OR\n\n#logical operators\nx= 5\ny=10\nz=15\n\nif x y):\n print(\"NOT succeeded...\")\n\nx ='a'\ny='b'\nz='a'\n\nif x is z:\n print(\"x and z are same\")\n\nif x is not y:\n print(\"x is not y\")\n\nx = 10\nx+=10 # x = x+ 10\n\nx = 13\nprint(\"x = 13, value = {0}\".format(x))\nx >>=1\nprint(\"x >>=1, value = {0}\".format(x))\nx >>=1\nprint(\"x >>=1, value = {0}\".format(x))\n","repo_name":"hencilpeter/DataEngineering","sub_path":"BigData/PythonSamples/10_Operators.py","file_name":"10_Operators.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70054833155","text":"from compas_cem.optimization.parameters import NodeParameter\n\n\n__all__ = [\"OriginNodeXParameter\",\n \"OriginNodeYParameter\",\n \"OriginNodeZParameter\"]\n\n# ------------------------------------------------------------------------------\n# Origin Node Parameter on X\n# ------------------------------------------------------------------------------\n\n\nclass OriginNodeXParameter(NodeParameter):\n \"\"\"\n Sets the X coordinate of an origin node as an optimization parameter.\n \"\"\"\n def __init__(self, key=None, bound_low=None, bound_up=None):\n super(OriginNodeXParameter, self).__init__(key, bound_low, bound_up)\n self._attr_name = \"x\"\n\n# ------------------------------------------------------------------------------\n# Origin Node Parameter on Y\n# ------------------------------------------------------------------------------\n\n\nclass OriginNodeYParameter(NodeParameter):\n \"\"\"\n Sets the Y coordinate of an origin node as an optimization parameter.\n \"\"\"\n def __init__(self, key=None, bound_low=None, bound_up=None):\n super(OriginNodeYParameter, self).__init__(key, bound_low, bound_up)\n self._attr_name = \"y\"\n\n# ------------------------------------------------------------------------------\n# Origin Node Parameter on Z\n# ------------------------------------------------------------------------------\n\n\nclass OriginNodeZParameter(NodeParameter):\n \"\"\"\n Sets the Z coordinate of an origin node as an optimization parameter.\n \"\"\"\n def __init__(self, key=None, bound_low=None, bound_up=None):\n super(OriginNodeZParameter, self).__init__(key, bound_low, bound_up)\n self._attr_name = \"z\"\n\n# ------------------------------------------------------------------------------\n# Main function\n# ------------------------------------------------------------------------------\n\n\nif __name__ == \"__main__\":\n\n from compas.geometry import Point\n\n from compas_cem.diagrams import TopologyDiagram\n\n from compas_cem.elements import Node\n from compas_cem.elements import TrailEdge\n from compas_cem.elements import DeviationEdge\n\n from compas_cem.loads import NodeLoad\n\n from compas_cem.supports import NodeSupport\n\n from compas_cem.equilibrium import static_equilibrium\n\n from compas_cem.optimization import Optimizer\n from compas_cem.optimization import DeviationEdgeParameter\n from compas_cem.optimization import TrailEdgeParameter\n\n from compas_cem.optimization import PointConstraint\n\n from compas_cem.plotters import Plotter\n\n # create a topology diagram\n topology = TopologyDiagram()\n\n # add nodes\n topology.add_node(Node(0, [0.0, 0.0, 0.0]))\n topology.add_node(Node(1, [1.0, 0.0, 0.0]))\n topology.add_node(Node(2, [2.0, 0.0, 0.0]))\n topology.add_node(Node(3, [3.0, 0.0, 0.0]))\n\n # add edges with negative values for a compression-only structure\n topology.add_edge(TrailEdge(0, 1, length=-1.0))\n topology.add_edge(DeviationEdge(1, 2, force=-1.0))\n topology.add_edge(TrailEdge(2, 3, length=-1.0))\n\n # add supports\n topology.add_support(NodeSupport(0))\n topology.add_support(NodeSupport(3))\n\n # add loads\n topology.add_load(NodeLoad(1, [0.0, -1.0, 0.0]))\n topology.add_load(NodeLoad(2, [0.0, -1.0, 0.0]))\n\n # calculate equilibrium\n topology.build_trails()\n form = static_equilibrium(topology)\n\n # optimization\n optimizer = Optimizer()\n\n optimizer.add_parameter(OriginNodeYParameter(1, 1.0, 1.0))\n optimizer.add_parameter(DeviationEdgeParameter((1, 2), 1.0, 1.0))\n optimizer.add_parameter(TrailEdgeParameter((2, 3), 1.0, 1.0))\n\n point_a = Point(1.0, -0.5, 0.0)\n optimizer.add_constraint((PointConstraint(1, point_a)))\n\n point_b = Point(3.0, -0.707, 0.0)\n optimizer.add_constraint((PointConstraint(3, point_b)))\n\n # optimize\n eps = 1e-6\n cform = optimizer.solve(topology, \"LBFGS\", eps=eps, verbose=True)\n assert optimizer.penalty <= eps\n\n # plot\n plotter = Plotter()\n\n plotter.add(form)\n plotter.add(point_b, facecolor=(0, 1, 0))\n plotter.add(point_a, facecolor=(1, 0, 0))\n plotter.add(cform, show_edgetext=True, edgetext=\"forcelength\")\n\n plotter.zoom_extents()\n plotter.show()\n","repo_name":"arpastrana/compas_cem","sub_path":"src/compas_cem/optimization/parameters/origin.py","file_name":"origin.py","file_ext":"py","file_size_in_byte":4202,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"61"}
+{"seq_id":"33006247723","text":"\"\"\"\nMost functions in here when used in vim, expect vim functions to have argument named args\n\"\"\"\n\nimport rpgdieroller.dierolls as rpgroller\nimport rpgdieroller.oracles as oracles\nimport vim\nimport sys\n\n\ndef _helper():\n args = vim.eval(\"a:args\")\n print(args)\n rpgroller.disable_term_formatting()\n cur_col = vim.current.window.cursor[0]\n return args, cur_col\n\n\ndef _update_cursor(shift):\n pos = vim.current.window.cursor\n pos = (pos[0] + shift, pos[1])\n vim.current.window.cursor = pos\n\n\ndef roll():\n args, cur_col = _helper()\n lines = []\n lines.append(\"# Dice Roll:\")\n lines.append(\"# \" + rpgroller.dierollexpr(args))\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef rollcountsuccess():\n args, cur_col = _helper()\n arglist = args.split(\" \")\n if len(arglist) != 3:\n print(\n f\"Error: must use 3 int arguments: \",\n file=sys.stderr,\n )\n return\n n_dice = arglist[0]\n n_sides = arglist[1]\n n_for_success = arglist[2]\n try:\n n_dice = int(n_dice)\n except ValueError:\n print(\n f\"Error: 1st arg n_dice must be convertable to int, not '{n_dice}'\",\n file=sys.stderr,\n )\n return\n try:\n n_sides = int(n_sides)\n except ValueError:\n print(\n f\"Error: 1st arg n_sides must be convertable to int, not '{n_sides}'\",\n file=sys.stderr,\n )\n return\n try:\n n_for_success = int(n_for_success)\n except ValueError:\n print(\n f\"Error: 1st arg n_for_success must be convertable to int, not '{n_for_success}'\",\n file=sys.stderr,\n )\n return\n rpgroller.disable_term_formatting()\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Count Successful Die Rolls:\")\n lines.append(\"# \" + rpgroller.rollcountsuccess(n_dice, n_sides, n_for_success))\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef rollfate():\n args, cur_col = _helper()\n lines = []\n lines.append(\"# Fate Dice Roll:\")\n lines.append(\"# \" + rpgroller.fateroll(args))\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef ironswornaction():\n args, cur_col = _helper()\n lines = []\n lines.append(\"# Ironsworn Action Roll:\")\n lines.append(\"# \" + rpgroller.ironswornaction(args))\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef ironswornprogress():\n n_progress = vim.eval(\"a:args\")\n print(n_progress)\n try:\n n_progress = int(n_progress)\n except ValueError:\n print(\n f\"Error: argument must be convertable to a single int not '{n_progress}'\",\n file=sys.stderr,\n )\n return\n rpgroller.disable_term_formatting()\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn Progress Roll:\")\n lines.append(\"# \" + rpgroller.ironswornprogress(n_progress))\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef OracleYesNo():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Simple oracle roll:\")\n lines.append(\"# \" + oracles.OracleYesNo())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornPayThePrice():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn pay the price:\")\n lines.append(\"# \" + oracles.IronswornPayThePrice())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornCharacterOracle():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn character oracle:\")\n lines.append(\"# \" + oracles.IronswornCharacter())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornActionThemeOracle():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn action-theme oracle:\")\n lines.append(\"# \" + oracles.IronswornActionTheme())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornLocationOracle():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn location oracle:\")\n lines.append(\"# \" + oracles.IronswornLocation())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornSettlementOracle():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn settlement oracle:\")\n lines.append(\"# \" + oracles.IronswornSettlement())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornCombatActionOracle():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn combat action oracle:\")\n lines.append(\"# \" + oracles.IronswornCombatAction())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornChallengeRankOracle():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn challenge rank oracle:\")\n lines.append(\"# \" + oracles.IronswornChallengeRank())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornMysticBacklashOracle():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn mystic backlash oracle:\")\n lines.append(\"# \" + oracles.IronswornMysticBacklash())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n\n\ndef IronswornMajorPlotTwistOracle():\n cur_col = vim.current.window.cursor[0]\n lines = []\n lines.append(\"# Ironsworn major plot twist oracle:\")\n lines.append(\"# \" + oracles.IronswornMajorPlotTwist())\n vim.current.buffer.append(lines, cur_col)\n _update_cursor(len(lines))\n","repo_name":"jhugon/rpgdieroller","sub_path":"rpgdieroller/vim.py","file_name":"vim.py","file_ext":"py","file_size_in_byte":5884,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"1655328122","text":"# 画像処理編\n# 6. アフィン変換により、画像を拡大縮小するプログラム\n\nimport cv2\nimport numpy as np\n\nimg = cv2.cvtColor(cv2.imread(\"../../data/Lenna.jpg\"), cv2.COLOR_BGR2GRAY)\n\nheight, width = img.shape[:2]\nratio = 2.0 # 画像を2倍に拡大する\n\n# アフィン変換を計算\n# src: Coordinates of triangle vertices in the source image.\n# dst: Coordinates of the corresponding triangle verices in the destination image.\nsrc = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0]], np.float32)\naffine = cv2.getAffineTransform(src = src, dst = src * ratio)\n\n# アフィン変換を画像に適用\n# dsize: size of the output image.\n# flags で補間方法を指定できる\nresized_img = cv2.warpAffine(src = img, M = affine, dsize = (int(ratio) * height, int(ratio) * width), flags = cv2.INTER_LANCZOS4)\n\ncv2.imwrite(\"../../data/image-processing-chap/ip_6.jpg\", resized_img)\n","repo_name":"Kobamiyannnn/image-processing-with-opencv","sub_path":"src/image-processing-chap/6_img_scaling_by_affine_transformation.py","file_name":"6_img_scaling_by_affine_transformation.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"28097274859","text":"class Solution:\n # @param A : tuple of integers\n # @return an integer\n def lis(self, A):\n n = len(A)\n dp = [0] * n\n dp[0] = 1\n # dp[1] = 1\n print(dp)\n print()\n\n for i in range(1, n):\n dp[i] = 1\n\n for j in range(i):\n if A[j] < A[i] and dp[j]+1 > dp[i]:\n dp[i] = dp[j] + 1\n print(dp)\n\n return max(dp)\n\n\nif __name__ == '__main__':\n a = [0, 8, 4, 12, 2, 10] # 6, 14, 1, 9, 5, 13, 3, 11, 7, 15]\n obj = Solution()\n ans = obj.lis(a)\n print(f'ans is {ans}')\n","repo_name":"navkant/ds_algo_practice","sub_path":"scaler/dynamic_programming/llis.py","file_name":"llis.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23449912561","text":"fp = r\"C:\\Yam\\input.txt\"\r\nofp = r\"C:\\Yam\\output.txt\"\r\nwith open(fp, 'rb') as reader:\r\n content = reader.read().splitlines()\r\nwriter = open(ofp, 'wb')\r\n\r\ntests = int(content[0])\r\nreader = 1\r\nwhile reader <= tests:\r\n line = content[reader]\r\n ##################\r\n line = line.split()\r\n length, crowd = int(line[0]), line[1]\r\n crowd = crowd[:length+1]\r\n shy = 0\r\n standing = 0\r\n attending = 0\r\n while shy < len(crowd):\r\n if int(crowd[shy]) > 0:\r\n attending += max(0, shy-(standing+attending))\r\n standing += int(crowd[shy])\r\n print(crowd, shy, standing, attending)\r\n shy += 1\r\n ##################\r\n writer.write(\"Case #{x}: {y}\\n\".format(x=reader, y=attending))\r\n reader += 1\r\n \r\nwriter.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_155/1723.py","file_name":"1723.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25072254252","text":"import logging\nimport os\nfrom typing import List, Optional, Union\nfrom transformers.data import DataProcessor, InputExample, InputFeatures, SingleSentenceClassificationProcessor\nfrom sklearn.metrics import f1_score, accuracy_score\nfrom transformers import (\n PreTrainedTokenizer,\n glue_compute_metrics,\n glue_output_modes,\n glue_processors\n)\nlogger = logging.getLogger(__name__)\n\ndef convert_examples_to_features(\n examples: List[InputExample],\n tokenizer: PreTrainedTokenizer,\n max_length: Optional[int] = None,\n task=None,\n label_list=None,\n output_mode=None,\n):\n if max_length is None:\n max_length = tokenizer.max_len\n\n if task is not None:\n processor = processors[task]()\n if label_list is None:\n label_list = processor.get_labels()\n logger.info(\"Using label list %s for task %s\" % (label_list, task))\n if output_mode is None:\n output_mode = output_modes[task]\n logger.info(\"Using output mode %s for task %s\" % (output_mode, task))\n\n label_map = {label: i for i, label in enumerate(label_list)}\n\n def label_from_example(example: InputExample) -> Union[int, float]:\n if output_mode == \"classification\":\n return label_map[example.label]\n elif output_mode == \"regression\":\n return float(example.label)\n raise KeyError(output_mode)\n\n labels = [label_from_example(example) for example in examples]\n\n batch_encoding = tokenizer.batch_encode_plus(\n [(example.text_a, example.text_b) for example in examples],\n max_length=max_length, padding=True, truncation=True, return_token_type_ids=True\n )\n\n features = []\n print(range(len(examples)))\n\n for i in range(len(examples)):\n inputs = {k: batch_encoding[k][i] for k in batch_encoding}\n feature = InputFeatures(**inputs, label=labels[i])\n features.append(feature)\n\n for i, example in enumerate(examples[:2]):\n logger.info(\"*** Example ***\")\n logger.info(\"guid: %s\" % (example.guid))\n logger.info(\"features: %s\" % features[i])\n\n return features\n\nclass SentenceDataProcessor(DataProcessor):\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\"\"\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\"\"\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"dev.tsv\")), \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\"\"\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n return NotImplementedError\n\n def _create_examples(self, lines, set_type):\n examples = []\n for (i, line) in enumerate(lines):\n guid = \"%s-%s\" % (set_type, i)\n text_a = line[0]\n label = line[1]\n examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label))\n return examples\n\n# monkey-patch all glue classes to have test examples\ndef get_test_examples(self, data_dir):\n return self._create_examples(self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\nfor task in glue_processors:\n\n processor = glue_processors[task]\n processor.get_test_examples = get_test_examples\n\n\nclass flProcessor(SentenceDataProcessor):\n def get_labels(self):\n labels = ['RS', 'S', 'Q', 'A', 'PF', 'ACK', 'RF', 'NF', 'C', 'H', 'DIR', 'RC', 'LF']\n # labels = ['A', 'ACK', 'C', 'DIR', 'H', 'LF', 'NF', 'PF', 'Q', 'RC', 'RF', 'S']\n\n return labels\n\nclass slProcessor(SentenceDataProcessor):\n def get_labels(self):\n labels = ['ACK', 'AEX', 'AR', 'AWH', 'AYN', 'C', 'DIR', 'E', 'FNU', 'FU',\n 'GRE', 'HI', 'I', 'LF', 'NF', 'O', 'OEX', 'PF', 'QD', 'QEX', 'QF',\n 'QI', 'QO', 'QP', 'QQ', 'QR', 'R', 'RC', 'RF', 'RFI']\n\n return labels\n\nprocessors = glue_processors.copy()\nprocessors.update(\n {\"firstlevel\":flProcessor, \"secondlevel\": slProcessor}\n)\nprint(processors)\noutput_modes = glue_output_modes\noutput_modes.update(\n {\"firstlevel\":\"classification\", \"secondlevel\":\"classification\"}\n)\n\ndef compute_metrics(task_name, preds, labels):\n assert len(preds) == len(labels)\n if task_name in [\"firstlevel\", \"secondlevel\"]:\n return {\"f1\":f1_score(y_true=labels, y_pred=preds, average=\"weighted\"), \"acc\": accuracy_score(y_true=labels, y_pred=preds)}\n elif task_name in glue_processors:\n return glue_compute_metrics(task_name, preds, labels)\n else:\n raise NotImplementedError\n\n","repo_name":"bertDA/BertDA","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4669,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"18685002582","text":"import math\nfrom os import curdir\nimport yfinance as yf\nimport time\nimport datetime\nimport matplotlib.pyplot as plt\n\nEPSILON = 0.000000001\nclass Strategy:\n\n\tdef __init__(self, stockData, budget, splitCount, profitRate, buyOnRiseRatio, delayTrade = 0, buyMoreUnderLossRatio = 0.00, logTrade = True, minimumLosscutRate = 1.0, name = ''):\n\t\tself.days_buy_lock = 0\n\t\tself.name = name\n\t\tself.budget = budget\n\t\tself.lastBalance = budget \n\t\tself.snapshotBalance = budget\n\t\tself.splitCount = splitCount\n\t\tself.profitRate = profitRate\n\t\tself.buyOnRiseRatio = buyOnRiseRatio\n\t\tself.stockData = stockData\n\t\tself.openPrices = stockData['Open']\n\t\tself.closePrices = stockData['Close']\n\t\tself.highPrices = stockData['High']\n\t\tself.lowPrices = stockData['Low']\n\t\tself.stockData['Date'] = stockData.index\n\t\tself.logTrade = logTrade\n\t\tself.minimumLosscutRate = minimumLosscutRate\n\t\tself.profitSellAmountRateAtOnce = 1\n\t\tself.lossSellAmountRateAtOnce = 1\n\n\t\tself.stockCount = 0\n\t\tself.breakEvenPrice = 0\n\t\tself.balanceHistory = []\n\t\tself.assetValueHistory = []\n\t\tself.delayTrade = delayTrade\n\t\tself.sellFee = 0.25/100\n\t\tself.buyFee = 0.25/100\n\t\tself.buyMoreUnderLossRatio = buyMoreUnderLossRatio\n\t\tself.score = 0\n\t\tself.recentScoreWeight = 1.0\n\t\tself.lastScore = 0\n\t\tself.scoreHistory = []\n\t\tself.trade_locked = False\n\t\tself.curBuyProgress = 0\n\t\tself.buyAmountUnit = self.budget / self.splitCount\n\t\tself.on_buy = 0 # fn(dayIndex, price, count)\n\t\tself.on_sell = 0 # fn(dayIndex, price, count)\n\n\tdef set_on_buy_fn(self, func):\n\t\tself.on_buy = func # fn(dayIndex, price, count)\n\n\tdef set_on_sell_fn(self, func):\n\t\tself.on_sell = func # fn(dayIndex, price, count)\n\t\n\n\tdef _buy_close(self, dayIndex, money) :\n\t\t#print(money)\n\t\tif(self.budget <= EPSILON):\n\t\t\treturn False\n\n\t\tif(self.budget - money < EPSILON):\n\t\t\treturn False\n\n\t\trecentPrice = self.closePrices[dayIndex - 1]\n\t\tcostPerStock = (recentPrice * (1.0 + self.buyFee))\n\t\tcount = (money / costPerStock)\n\t\tif count <= EPSILON:\n\t\t\treturn False\n\n\n\t\tprice = self.closePrices[dayIndex]\n\t\tself.breakEvenPrice = ( ( self.stockCount * self.breakEvenPrice ) + (count * price ) ) / (self.stockCount + count)\n\t\tself.stockCount += count\n\n\t\tif( count > 0):\n\t\t\tself.on_buy(dayIndex, price, count)\n\n\t\tif(self.budget == 0.):\n\t\t\tassert(0)\n\n\t\tself.budget -= (price * count) \n\n\t\tif(math.fabs(self.budget) < EPSILON):\n\t\t\tself.budget = 0\n\n\n\n\t\t#print(\"[BUY ] self.budget(%d) Count(%d) Mean(%f) BUY(%f)\" % (self.budget, self.stockCount, self.breakEvenPrice, close_value))\n\n\t\treturn True\n\t\n\tdef is_tradable(self, dayIndex):\n\t\tif(dayIndex < self.delayTrade):\n\t\t\treturn False\n\n\t\tsize = self.closePrices.size\n\t\tif dayIndex >= size:\n\t\t\treturn False\n\t\t\n\t\treturn True\n\n\t\n\tdef is_take_profit_condition(self, dayIndex, profitRate):\n\t\treturn self.breakEvenPrice * profitRate < float(self.highPrices[dayIndex])\n\n\tdef calc_balance(self, dayIndex):\n\t\treturn self.closePrices[dayIndex] * self.stockCount + self.budget\n\n\tdef sell_all_when_done(self, dayIndex ):\n\t\tprice_and_count = (0, 0)\n\t\tsold = 0\n\t\tsoldCount = 0\n\t\tif self.is_tradable(dayIndex) == False: return price_and_count\n\n\t\tif( self.stockCount == 0 ):\n\t\t\treturn price_and_count\n\n\t\tif(math.fabs(self.splitCount - self.curBuyProgress) <= EPSILON):\n\t\t\tself.curBuyProgress = self.splitCount\n\n\t\tassert(self.splitCount - self.curBuyProgress >= 0 )\n\n\t\tprogressRatio = self.curBuyProgress / self.splitCount\n\t\t#progressRatio = 1\n\t\tsellAmountRate = 0\n\n\t\tif(self.budget - self.buyAmountUnit <= 0):\n\t\t\t#if self.is_take_profit_condition(dayIndex, self.minimumLosscutRate) : # losscut\n\t\t\t\tprice = self.closePrices[dayIndex] \n\t\t\t\tsellAmountRate = self.lossSellAmountRateAtOnce\n\t\t\t\tsoldCount = self.stockCount * sellAmountRate\n\t\t\t\tsold = (soldCount * price)\n\t\t\t\tprice_and_count = (price, soldCount)\n\n\t\telif self.is_take_profit_condition(dayIndex, self.profitRate) : # take profit\n\t\t\tprice = self.breakEvenPrice * self.profitRate\n\t\t\t#sellAmountRate = self.profitSellAmountRateAtOnce * (0.5 + (progressRatio * progressRatio)*0.5)\n\t\t\tsellAmountRate = self.profitSellAmountRateAtOnce\n\t\t\tsoldCount = self.stockCount * sellAmountRate \n\t\t\tsold = soldCount * price\n\t\t\tprice_and_count = (price, soldCount)\n\n\t\tif sold > 0:\n\t\t\tself.budget += sold * (1.0 - self.sellFee)\n\t\t\tself.curBuyProgress *= (1.0 - sellAmountRate)\n\t\t\tself.stockCount -= soldCount\n\t\t\tself.lastBalance = self.calc_balance(dayIndex)\n\t\t\tself.buyAmountUnit = self.lastBalance / self.splitCount\n\t\t\t\n\t\t\tself.on_sell(dayIndex, price_and_count[0], price_and_count[1])\n\t\t\n\n\t\treturn price_and_count\n\t\n\t\n\t\n\tdef lock_trade(self):\n\t\tself.trade_locked = True\n\n\tdef is_trade_locked(self):\n\t\treturn self.trade_locked\n\n\tdef unlock_trade(self):\n\t\tself.trade_locked = False \n\n\tdef fill_budget(self, money):\n\t\tassetValue = self.lastBalance - self.budget\n\t\tself.budget += money\n\t\tself.lastBalance += money\n\t\tself.curBuyProgress = self.splitCount * assetValue / self.lastBalance\n\t\tself.buyAmountUnit = self.lastBalance / self.splitCount\n\n\tdef transfer_budget(self, desiredMoney):\n\t\ttransfered = 0\n\t\tif(self.budget > desiredMoney):\n\t\t\ttransfered = desiredMoney\n\t\telse:\n\t\t\ttransfered = self.budget\n\n\t\tself.budget -= transfered\n\t\tself.lastBalance -= transfered\n\t\tif(self.budget < 0):\n\t\t\tassert(0)\n\n\t\treturn transfered\n\n\tdef reserve_budget_at_close(self, dayIndex, desiredReserve):\n\n\t\tif(dayIndex == 0):\n\t\t\treturn 0\n\n\t\tif(desiredReserve <= self.budget): # already reserved\n\t\t\treturn desiredReserve\n\n#--------------------------------------------------------------------------------\n#\tcalc count by recentPrice\n#--------------------------------------------------------------------------------\n\t\trecentPrice = self.closePrices[dayIndex-1]\n\t\tcount = desiredReserve / recentPrice\n\t\tif(self.stockCount < count):\n\t\t\tcount = self.stockCount\n#--------------------------------------------------------------------------------\n\n\t\tself.stockCount -= count\n\t\tself.budget += count * self.closePrices[dayIndex] * (1.0 - self.sellFee);\n\t\tif( count > 0):\n\t\t\tself.on_sell(dayIndex, self.closePrices[dayIndex], count)\n\n\t\tif(desiredReserve <= self.budget): # finally reserved\n\t\t\treturn desiredReserve\n\t\treturn self.budget\n\n\n\tdef post_trade(self, dayIndex):\n\t\tself.assetValueHistory.append(self.stockCount * self.closePrices[dayIndex])\n\t\tself.balanceHistory.append(self.calc_balance(dayIndex))\n\n\tdef buy(self, dayIndex):\n\t\tif(dayIndex == 0):\n\t\t\tself.lastBalance = self.calc_balance(dayIndex)\n\t\t\treturn\n\t\tif( self.budget <= 0):\n\t\t\tself.lastBalance = self.calc_balance(dayIndex)\n\t\t\treturn\n\n\t\tbuyRatio = self.buyOnRiseRatio\n\n\t\topenPrice = float(self.closePrices[dayIndex-1])\n\t\tif self.breakEvenPrice < openPrice * 0.97 :\n\t\t\tif((self.curBuyProgress + buyRatio) >= self.splitCount):\n\t\t\t\tself.lastBalance = self.calc_balance(dayIndex)\n\t\t\t\treturn\n\n\t\t\tsuccess = self._buy_close(dayIndex, self.buyAmountUnit * buyRatio)\n\t\t\tif success == True:\n\t\t\t\tself.curBuyProgress += buyRatio\n\n\t\tbuyRatio = 1.0 - self.buyOnRiseRatio\n\t\tif((self.curBuyProgress + buyRatio) >= self.splitCount):\n\t\t\tself.lastBalance = self.calc_balance(dayIndex)\n\t\t\treturn\n\n\t\tsuccess = self._buy_close(dayIndex, self.buyAmountUnit * buyRatio)\n\t\tif success == True:\n\t\t\tself.curBuyProgress += buyRatio\n\n\n\t\tself.lastBalance = self.calc_balance(dayIndex)\n","repo_name":"quakenroll/infinite_buy","sub_path":"startegy2.py","file_name":"startegy2.py","file_ext":"py","file_size_in_byte":7159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"22180991020","text":"import os\nimport numpy as np\nimport time\nimport astropy.units as u\nfrom galpy.potential import evaluatePotentials, KeplerPotential, HernquistPotential, PlummerPotential\nfrom galpy.util import conversion\nfrom binary_evolution import KeplerRing, PointMass\nfrom binary_evolution.tools import ecc_to_vel\n# from flybys3body import scattering_hybrid, scattering_SA\nfrom fortran.flybys3body_fortran import scattering_hybrid, scattering_SA\nfrom amuse.lab import *\nfrom numpy.random import default_rng\n\nimport matplotlib\nfrom matplotlib import pyplot\nfrom matplotlib.ticker import (MultipleLocator, AutoMinorLocator)\n\nG = constants.G\nc = constants.c\nHubbleTime = 1.4e10|units.yr\n_pc = 8000\n_kms = 220\n\ndef isfloat(value):\n\ttry:\n\t\tfloat(value)\n\t\treturn True\n\texcept ValueError:\n\t\treturn False\n\nclass inputParameters:\n\tdef __init__(self, t=1e4, a_out=0.5, e_out=0, inc_out=np.pi/6, m1=5, m2=5, a=1, e=0.05, i=1, Omega=1.5, omega=0, output_file='output.txt', output_file_2='', approximation=0, potential=\"Plummer\", m_total=4e6, b=1, rtol=1e-11, tmax=1e20, relativity=True, tidal_effects=True, gw=True, resume=False, includeEncounters=True, includeWeakEncounters=True, Q_max_a=50, Q_min_a=0, n=10, a_max=1000, sameParameters='', disableKicks=False, t0=0, m_per=1):\n\t\tself.t = t # Integration time [yr] \n\t\tself.a_out = a_out # Outer orbit semi-major axis [pc]\n\t\tself.e_out = e_out # Outer orbit eccentricity\n\t\tself.inc_out = inc_out # Outer orbit inclination\n\t\tself.m1 = m1 # Primary mass [MSun]\n\t\tself.m2 = m2 # Secondatu mass [MSun]\n\t\tself.a = a # Inner orbit semimajor axis [AU]\n\t\tself.e = e # Inner orbit eccentricity\n\t\tself.i = i # Inner orbit inclination\n\t\tself.Omega = Omega # Inner orbit longitude of ascending node\n\t\tself.omega = omega # Inner orbit argument of periapsis\n\t\tself.output_file = output_file # Output file name\n\t\tself.output_file_2 = output_file_2 # Additional output file name\n\t\tself.approximation = approximation # 0 - use precise if epsilon_gr<20 and GR-only otherwise; 1 - always precise; 2 - always GR-only\n\t\tself.potential = potential # Cluster potential\n\t\tself.b = b\n\t\tself.m_total = m_total\n\t\tself.rtol = rtol # Inner orbit integration accuracy\n\t\tself.tmax = tmax # Maximum calculation time [s]\n\t\tself.resume = resume # Resume the integration from the last line in self.output_file (ignores the provided initial conditions)\n\t\tself.includeWeakEncounters = includeWeakEncounters \n\t\tself.Q_max_a = Q_max_a # The maximum pericenter of the encounters to include\n\t\tself.Q_min_a = Q_min_a # The minimum pericenter of the encounters to include\n\t\tself.includeEncounters = includeEncounters \n\t\tself.n = n # The number of points per (approximate) outer orbital period used to interpolate the outer orbit \n\t\tself.relativity = relativity #include GR effects\n\t\tself.tidal_effects = tidal_effects #include tidal terms\n\t\tself.gw = gw #include GW emission\n\t\tself.a_max = a_max #Stop the integration if the inner binary semimajor axis exceeds this value in AU\n\t\tself.sameParameters = sameParameters #if not empty, take the initial conditions from that file (overwritten by resume)\n\t\tself.disableKicks = disableKicks #if True, encounters don't change the binary CM velocity \n\t\tself.t0 = t0 \t#initial time\n\t\tself.m_per = m_per \t#Perturber mass in M_Sun\n\ndef m_final(m):\n\tstellar = SSE()\n\tstellar.parameters.metallicity = 0.001\n\tstellar.particles.add_particle(Particle(mass=m))\n\tstellar.evolve_model(5|units.Gyr)\t\n\tresult = stellar.particles.mass.in_(units.MSun)\n\tstellar.stop()\n\treturn result\n\ndef sample_v_icdf (x, sigma_rel, n=10):\n# x = GM/Q_max/sigma_rel^2\n# u = v/sigma_rel\n\trng = default_rng()\n\trandom_number = rng.random()\n\tcdf1 = 0\n\ti = -1\n\twhile cdf1 < random_number:\n\t\ti += 1\n\t\tu1 = (i+1)/n\n\t\tcdf1 = 1-np.exp(-u1**2/2) - u1**2*np.exp(-u1**2/2)/2/(1+x)\n\tu0 = i/n\n\tcdf0 = 1-np.exp(-u0**2/2) - u0**2*np.exp(-u0**2/2)/2/(1+x)\t\n\tu = u0 + (u1-u0)*(random_number-cdf0)/(cdf1-cdf0)\n\treturn u*sigma_rel\n\ndef sample_v_hamers (sigma_rel, v0):\n# v0 = sqrt(GM/Q_max)\n\trng = default_rng()\n\twhile True:\n\t\tvz = np.sqrt(rng.exponential(2*sigma_rel.value_in(units.kms)**2))|units.kms\n\t\tvx = rng.normal(0, sigma_rel.value_in(units.kms))|units.kms\n\t\tvy = rng.normal(0, sigma_rel.value_in(units.kms))|units.kms\n\t\tv2 = vx**2+vy**2+vz**2\n\t\tif (v2 > 2*v0**2): break\n\treturn np.sqrt(v2 - 2*v0**2)\n\n# m_total = 4e+6\n# b=1\n# pot = TwoPowerTriaxialPotential(amp=16*m_bh*u.solMass, a=4*u.pc, alpha=1, beta=4, c=0.7)\n# pot = PlummerPotential(amp=m_total*u.solMass, b=b*u.pc) \n\n# Q_max_a_default = 50\nQ_hybrid_a = 10\n# m_per = 1|units.MSun\n# m_per_max = m_per\n# sigma = 3|units.kms\n# n = 1e6|units.pc**-3\n\ndef sigma (r, type=\"Plummer\", m_total=4e6, b=1):\n\t# sqrt(2) * one-dimensional velocity dispersion\n\tif type==\"Plummer\": return np.sqrt(G*(m_total|units.MSun)/6/np.sqrt(r**2+(b|units.pc)**2))\n\telif type==\"Hernquist\": \n\t\tx = r/(b|units.pc)\n\t\t# print(x, 12*x*(x+1)**3*np.log(1+1/x) - x/(x+1)*(25+52*x+42*x**2+12*x**3))\n\t\treturn np.sqrt(G*(m_total|units.MSun)/12/(b|units.pc) * (12*x*(x+1)**3*np.log(1+1/x) - x/(x+1)*(25+52*x+42*x**2+12*x**3)))\n\telse: \n\t\treturn 0|units.kms\n\ndef rho (r, type=\"Plummer\", m_total=4e6, b=1):\n\tif type==\"Plummer\": return 3*(m_total|units.MSun)/4/np.pi/(b|units.pc)**3*(1+(r/(b|units.pc))**2)**-2.5\n\telif type==\"Hernquist\": return (m_total|units.MSun)/2/np.pi/(b|units.pc)**3/(r/(b|units.pc))*(1+r/(b|units.pc))**-3\n\telse: return 0|units.kg/units.m**3\n\ndef tau_0 (a, m_bin, r, Q_max_a=50, type=\"Plummer\", m_total=4e6, b=1, V=0|units.kms, m_per=1|units.MSun):\n\tQ_max = Q_max_a * a\n\tv0 = np.sqrt(G*(m_bin+m_per)/Q_max)\n\tsigma_rel = np.sqrt(sigma(r, type, m_total, b)**2 + V**2)\n\treturn (2*np.sqrt(2*np.pi)*Q_max**2*sigma_rel*(rho(r, type, m_total, b)/m_per)*(1+(v0/sigma_rel)**2))**-1\n\ndef a_h (m1, m2, r, type=\"Plummer\", m_total=4e6, b=1):\n\treturn (G*(m1*m2/(m1+m2)|units.MSun)/4/sigma(r|units.pc, type, m_total, b)**2).value_in(units.AU)\n\ndef sample_encounter_parameters_old (a, m_bin, r, Q_max_a=50, type=\"Plummer\", m_total=4e6, b=1, m_per=1|units.MSun):\n\tQ_max = Q_max_a * a\n\trng = default_rng()\n\tv0 = np.sqrt(G*(m_bin+m_per)/Q_max)\n\t# time until the encounter\n\t# tau = rng.exponential(tau_0(a,m_bin,n).value_in(units.yr))|units.yr\n\t# perturber mass\n\t# m_per = 1|units.MSun\n\t# perturber orbital parameters\n\t# v = sample_v_hamers (sigma(r), v0)\n\n\t# sigma -> sigma_rel!\n\tx = (v0/sigma(r, type, m_total, b))**2\n\tv = sample_v_icdf (x, sigma(r, type, m_total, b))\n\tp_max2 = Q_max**2*(1+2*(v0/v)**2)\n\tp = np.sqrt(p_max2*rng.random())\n\taStar = -G*(m_bin+m_per)/v**2\n\teStar = np.sqrt(1+p**2/aStar**2)\n\tiStar = np.arccos(rng.random()*2-1)\n\tOmegaStar = rng.random()*2*np.pi\n\tomegaStar = rng.random()*2*np.pi\n\treturn m_per, aStar, eStar, iStar, OmegaStar, omegaStar\n\ndef normalize (vector):\n\treturn vector / np.linalg.norm(vector)\n\ndef sample_encounter_parameters (a, m_bin, r, phi, Q_max_a=50, type=\"Plummer\", m_total=4e6, b=1, v_bin=[0,0,0], m_per=1|units.MSun):\n\t# returns the parameters in physical units\n\t# v_bin is the binary CM velocity [v_R, v_phi, v_z]=[v_x, v_y, v_z] in km/s \n\trng = default_rng()\n\n\tQ_max = Q_max_a * a.value_in(units.m)\n\tmu = (G*(m_bin+m_per)).value_in(units.m**3/units.s**2)\n\tv0 = np.sqrt(mu/Q_max)\n\tx = (v0/sigma(r, type, m_total, b).value_in(units.m/units.s))**2\n\tv = sample_v_icdf (x, sigma(r, type, m_total, b)).value_in(units.m/units.s)\n\n\ttheta_v = np.arccos(rng.random()*2-1)\n\tphi_v = rng.random()*2*np.pi\n\tv_x = v*np.sin(theta_v)*np.cos(phi_v)\n\tv_y = v*np.sin(theta_v)*np.sin(phi_v)\n\tv_z = v*np.cos(theta_v)\n\t#initial velocity vector in the binary reference frame\n\tv1 = [v_x-v_bin[0]*1000, v_y-v_bin[1]*1000, v_z-v_bin[2]*1000]\n\n\tp_max2 = Q_max**2*(1+2*(v0/np.linalg.norm(v1))**2)\n\tp = np.sqrt(p_max2*rng.random())\n\taStar = -mu/np.linalg.norm(v1)**2\n\teStar = np.sqrt(1+p**2/aStar**2)\n\n\t# unit vectors perpendicular to velocity\n\te1 = normalize([v1[1], -v1[0], 0])\n\te2 = normalize(np.cross(v1, e1))\n\tangle = rng.random()*2*np.pi\n\t# angular momentum\n\th = (e1*np.cos(angle) + e2*np.sin(angle)) * np.sqrt(mu*aStar*(1-eStar**2))\n\t# eccentricity vector\n\tecc_vector = np.cross(v1, h)/mu + normalize(v1)\n\n\t# now we convert all the vectors to the cluster reference frame\n\t# the unut vectors for that reference frame in cylindrical coordinates\n\tcluster_x = [np.cos(phi), -np.sin(phi), 0]\n\tcluster_y = [np.sin(phi), np.cos(phi), 0]\n\tcluster_z = [0, 0, 1]\n\trotation_matrix = [cluster_x, cluster_y, cluster_z]\n\t# transforming the vectors to the cluster reference frame\n\th = np.matmul(rotation_matrix, h)\n\tecc_vector = np.matmul(rotation_matrix, ecc_vector)\n\n\t# calculating the orbital angles\n\tiStar = np.arccos(normalize(h)[2])\n\t# vector pointitng towards the ascending node\n\tn = normalize([-h[1], h[0], 0])\n\tif n[0]==0 and n[1]==0:\n\t\tOmegaStar = 0\n\telse:\n\t\tOmegaStar = np.arccos(n[0])\n\t\tif n[1]<0: OmegaStar = 2*np.pi - OmegaStar\n\tif h[0]==0 and h[1]==0:\n\t\tomegaStar = np.arctan2(ecc_vector[1], ecc_vector[0])\n\t\tif h[2]<0: omegaStar = 2*np.pi - omegaStar\n\telse:\n\t\tomegaStar = np.arccos(np.dot(n, normalize(ecc_vector)))\n\t\tif ecc_vector[2]<0: omegaStar = 2*np.pi - omegaStar\n\treturn m_per, aStar|units.m, eStar, iStar, OmegaStar, omegaStar\n\n# Inner binary parameters\na_in = 0.01 # Semi-major axis in AU\necc = 0.05 \t# Eccentricity\ninc = np.pi/3 # Inclination with respect to the z-axis\nlong_asc = 0 # Longitude of the ascending node\narg_peri = np.pi / 2 # Arugment of pericentre\nm1 = 5\nm2 = 5\nm_bin = m1+m2 # Total mass in solar masses\nm_bin_init = m_bin|units.MSun\n# q = 1\n\n# M_max = max(m_bin_init+m_per_max, 3*m_per_max) \n\n# Outer binary parameters\necc_out = 0.0 # Outer orbit eccentricity\ninc_out = np.pi/6 # Outer orbit inclination\na_out = 0.5 # Outer semi-major axis in pc\n\n# Start at pericentre\nr = a_out * (1 - ecc_out) # Spherical radius\nR = r * np.cos(inc_out) # Cylindrical radius\nz = r * np.sin(inc_out) # Cylindrical height\n\n# output_file_name = os.path.dirname(os.path.abspath(__file__))+'/history-rtol7.txt'\n\n# is the binary hard?\n# a_h = G*(m1*m2/(m1+m2)|units.MSun)/4/sigma_rel(r|units.pc)**2\n# # print(a_in/a_h.value_in(units.AU))\n# Q=0.25\n# print(((a_in|units.AU)/(64/5 * Q * G**3 * (k.m()|units.MSun)**3 / c**5 / (a_in|units.AU)**3)).value_in(units.yr))\n# print(tau_0 (a_in|units.AU, m_bin|units.MSun, r|units.pc).value_in(units.yr))\n\n# k = KeplerRing(ecc, inc, long_asc, arg_peri, [R1, z1, phi1], v1, a=a_in, m=m_bin, q=1)\n# ts = np.linspace(0, 2*(t2-t1), 1000)\n# k.integrate(ts, pot=pot, relativity=True, gw=True, tau_0=lambda *args: tau_0(args[0]|units.pc, m_bin|units.MSun, args[1]|units.pc).value_in(units.yr), random_number=1.4, rtol=1e-7, atol=1e-10)\n# R2real, z2real, phi2real = k.r(t2-t1)\n# v2real = k.v(t2-t1)\n\n# E1 = (np.linalg.norm(v1)/_kms)**2/2 + evaluatePotentials(pot, R1/_pc, z1/_pc, phi=phi1, use_physical=False) \n# E2 = (np.linalg.norm(v2)/_kms)**2/2 + evaluatePotentials(pot, R2/_pc, z2/_pc, phi=phi2, use_physical=False) \n# E2real = (np.linalg.norm(v2real)/_kms)**2/2 + evaluatePotentials(pot, R2real/_pc, z2real/_pc, phi=phi2real, use_physical=False) \n\ndef evolve_binary_noenc (input):\n\n\tt = input.t\n\n\t# Outer binary parameters\n\ta_out = input.a_out # Outer semi-major axis in pc\n\tecc_out = input.e_out # Outer orbit eccentricity\n\tinc_out = input.inc_out # Outer orbit inclination\n\n\t# Inner binary parameters\n\tm1 = input.m1\n\tm2 = input.m2\n\ta_in = input.a # Semi-major axis in AU\n\tecc = input.e \t# Eccentricity\n\tinc = input.i # Inclination with respect to the z-axis\n\targ_peri = input.omega # Arugment of pericentre\n\tlong_asc = input.Omega # Longitude of the ascending node\n\tm_bin = m1+m2 # Total mass in solar masses\n\n\t# Start at pericentre\n\tr = a_out * (1 - ecc_out) # Spherical radius\n\tR = r * np.cos(inc_out) # Cylindrical radius\n\tz = r * np.sin(inc_out) # Cylindrical height\n\n\t# Potential\n\tb = input.b\n\tm_total = input.m_total\n\ttype = input.potential\n\tif type==\"Plummer\": pot = PlummerPotential(amp=m_total*u.solMass, b=b*u.pc) \n\telif type==\"Hernquist\": pot = HernquistPotential(amp=2*m_total*u.solMass, a=b*u.pc) \n\telif type=='Kepler': pot = KeplerPotential(amp=m_total*u.solMass)\n\n\t# Compute the correct v_phi at pericentre for the selected eccentricity and potential\n\tv_phi = ecc_to_vel(pot, ecc_out, [R, z, 0])\n\n\t# Define the KeplerRing\n\tk = KeplerRing(ecc, inc, long_asc, arg_peri, [R, z, 0], [0, 0, v_phi], a=a_in, m=m_bin, q=m2/m1)\n\tk1 = KeplerRing(ecc, inc, long_asc, arg_peri, [R, z, 0], [0, 0, v_phi], a=a_in, m=m_bin, q=m2/m1)\n\n\t# output_file = open(input.output_file, 'w+')\n\t# print('t[yr] R[pc] z phi v_R[km/s] v_z v_phi a[AU] m[MSun] q ecc inc long_asc arg_peri, outer_integration_time, tidal_time, inner_integration_time', file=output_file)\n\t# print(0, R, z, 0, 0, 0, v_phi, k.a(), k.m(), k._q, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), file=output_file, flush=True)\n\n\tif type=='Kepler':\n\t\tT = 2*np.pi*np.sqrt((r|units.pc)**3/G/(m_total|units.MSun))\n\telse:\n\t\tT = 2*np.pi*(r|units.pc)/sigma(r|units.pc, type, m_total, b)\t# approximate outer period\n\tn = max(int(input.n*t/(T.value_in(units.yr))), 100)\t#number of points used to approximate the outer orbit\n\t# n=10\n\tts = np.linspace(0, t, n)+input.t0\n\trtol=input.rtol #1e-11\n\tatol= rtol*1e-3 #1e-14\n\t\n\tk.integrate(ts, pot=pot, relativity=input.relativity, gw=input.gw, tau_0=lambda *args: tau_0(args[0]|units.pc, k.m()|units.MSun, args[1]|units.pc, 50, type, m_total, b, m_per=m_per).value_in(units.yr), random_number=1e10, rtol=rtol, atol=atol, approximation=input.approximation, debug_file=input.output_file_2, points_per_period=input.n, ej_method='LSODA')\n\tif k.switch_to_gr:\n\t\tts += k.t_fin\n\t\tk = KeplerRing(k.ecc_fin, k.inc_fin, k.long_asc_fin, k.arg_peri_fin, k.r(k.t_fin), k.v(k.t_fin), a=k.a_fin, m=k._m, q=k._q)\n\t\tk.integrate(ts, pot=pot, relativity=input.relativity, gw=input.gw, tau_0=lambda *args: tau_0(args[0]|units.pc, k.m()|units.MSun, args[1]|units.pc, 50, type, m_total, b, m_per=m_per).value_in(units.yr), random_number=1e10, rtol=rtol, atol=atol, approximation=2, debug_file=input.output_file_2, points_per_period=input.n)\n\n\t# print('da de di dOmega domega', file=output_file)\n\t# if k.merger: print('merger at', k.t_fin, file=output_file, flush=True)\n\t# else: print(k.t_fin, k.a_fin-a_in, k.ecc_fin-ecc, k.inc_fin-inc, k.long_asc_fin-long_asc, k.arg_peri_fin-arg_peri, k.outer_integration_time, k.tidal_time, k.inner_integration_time, file=output_file, flush=True)\n\t# print('epsilon =', k.epsilon_gr, file=output_file, flush=True)\n\ndef evolve_binary (input):\n\t# 0 - binary has survived until t_final\n\t# 1 - binary has merged\n\t# 2 - binary has been destroyed\n\t# 3 - maximum calculation time exceeded\n\t# 4 - maximum semimajor axis exceeded\n\t# 5 - binary has been ejected from the cluster\n\n\tt_final = input.t|units.yr\n\tm_per = input.m_per|units.MSun\n\n\tif input.includeWeakEncounters: Q_max_a = input.Q_max_a\n\telse: Q_max_a = Q_hybrid_a\n\tQ_min_a = input.Q_min_a\n\t\n\t# Potential\n\tb = input.b\n\tm_total = input.m_total\n\ttype = input.potential\n\tif type==\"Plummer\": pot = PlummerPotential(amp=m_total*u.solMass, b=b*u.pc) \n\telif type==\"Hernquist\": pot = HernquistPotential(amp=2*m_total*u.solMass, a=b*u.pc) \n\n\tif os.path.isfile(input.sameParameters):\n\t\twith open(input.sameParameters) as f:\n\t\t\tfor line in f:\n\t\t\t\tdata = line.split()\n\t\t\t\tif isfloat(data[0]): break\n\t\t\tt = float(data[0])|units.yr\n\t\t\tR = float(data[1])\n\t\t\tz = float(data[2])\n\t\t\tphi = float(data[3])\n\t\t\tv_R = float(data[4])\n\t\t\tv_z = float(data[5])\n\t\t\tv_phi = float(data[6])\n\t\t\ta_in = float(data[7])\n\t\t\tm_bin = float(data[8])\n\t\t\tq = float(data[9])\n\t\t\tecc = float(data[10])\n\t\t\tinc = float(data[11])\n\t\t\tlong_asc = float(data[12])\n\t\t\targ_peri = float(data[13])\n\t\tk = KeplerRing(ecc, inc, long_asc, arg_peri, [R, z, phi], [v_R, v_z, v_phi], a=a_in, m=m_bin, q=q)\n\t\toutput_file = open(input.output_file, 'w+')\n\t\tprint('t[yr] R[pc] z phi v_R[km/s] v_z v_phi a[AU] m[MSun] q ecc inc long_asc arg_peri random_number_0 dt[yr] n epsilon_gr t_orbit[s] |de|', file=output_file)\t# |de| is the integral of |de/dt|_tidal\n\t\tprint('perturber: m_per[MSun] Q[AU] eStar iStar OmegaStar omegaStar t_3body[s]', file=output_file)\n\t\tprint(0, R, z, 0, 0, 0, v_phi, k.a(), k.m(), k._q, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), file=output_file)\n\t\toutput_file.flush()\n\telif input.resume and os.path.isfile(input.output_file):\n\t\twith open(input.output_file) as f:\n\t\t\tfor line in f: pass\n\t\t\tdata = line.split()\n\t\t\tif data[1] == 'merger': return 1\n\t\t\tif data[1] == 'destroyed': return 2\n\t\t\tif data[1] == 'maximum' and data[2] == 'calculation': return 3\n\t\t\tif data[1] == 'maximum' and data[2] == 'semimajor': return 4\n\t\t\tif data[1] == 'ejected': return 5\n\t\t\tt = float(data[0])|units.yr\n\t\t\tif t>t_final: return 0\n\t\t\tfor index in range(14):\n\t\t\t\tif not isfloat(data[index]):\n\t\t\t\t\tprint(\"bad file:\", input.output_file)\n\t\t\t\t\tprint(\"bad line:\", line)\n\t\t\t\t\tprint(\"bad segment:\", data[index])\n\t\t\tR = float(data[1])\n\t\t\tz = float(data[2])\n\t\t\tphi = float(data[3])\n\t\t\tv_R = float(data[4])\n\t\t\tv_z = float(data[5])\n\t\t\tv_phi = float(data[6])\n\t\t\ta_in = float(data[7])\n\t\t\tm_bin = float(data[8])\n\t\t\tq = float(data[9])\n\t\t\tecc = float(data[10])\n\t\t\tinc = float(data[11])\n\t\t\tlong_asc = float(data[12])\n\t\t\targ_peri = float(data[13])\n\t\tk = KeplerRing(ecc, inc, long_asc, arg_peri, [R, z, phi], [v_R, v_z, v_phi], a=a_in, m=m_bin, q=q)\n\t\toutput_file = open(input.output_file, 'a')\n\telse:\n\t\tt = 0|units.yr\n\n\t\t# Outer binary parameters\n\t\ta_out = input.a_out # Outer semi-major axis in pc\n\t\tecc_out = input.e_out # Outer orbit eccentricity\n\t\tinc_out = input.inc_out # Outer orbit inclination,\n\n\t\t# Inner binary parameters\n\t\tm1 = input.m1\n\t\tm2 = input.m2\n\t\ta_in = input.a # Semi-major axis in AU\n\t\tecc = input.e \t# Eccentricity\n\t\tinc = input.i # Inclination with respect to the z-axis\n\t\targ_peri = input.omega # Arugment of pericentre\n\t\tlong_asc = input.Omega # Longitude of the ascending node\n\t\tm_bin = m1+m2 # Total mass in solar masses\n\t\tm_bin_init = m_bin|units.MSun\n\n\t\t# Start at pericentre\n\t\tr = a_out * (1 - ecc_out) # Spherical radius\n\t\tR = r * np.cos(inc_out) # Cylindrical radius\n\t\tz = r * np.sin(inc_out) # Cylindrical height\n\n\t\t# Compute the correct v_phi at pericentre for the selected eccentricity and potential\n\t\tv_phi = ecc_to_vel(pot, ecc_out, [R, z, 0])\n\n\t\t# Define the KeplerRing\n\t\tk = KeplerRing(ecc, inc, long_asc, arg_peri, [R, z, 0], [0, 0, v_phi], a=a_in, m=m_bin, q=m2/m1)\n\n\t\toutput_file = open(input.output_file, 'w+')\n\t\tprint('t[yr] R[pc] z phi v_R[km/s] v_z v_phi a[AU] m[MSun] q ecc inc long_asc arg_peri random_number_0 dt[yr] n epsilon_gr t_orbit[s] |de| |di|', file=output_file)\t# |de| is the integral of |de/dt|_tidal\n\t\tprint('perturber: m_per[MSun] Q[AU] eStar iStar OmegaStar omegaStar t_3body[s]', file=output_file)\n\t\tprint(0, R, z, 0, 0, 0, v_phi, k.a(), k.m(), k._q, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), file=output_file)\n\t\toutput_file.flush()\n\n\trtol=input.rtol #1e-11\n\tatol= rtol*1e-3 #1e-14\n\n\ttimeTotal1 = time.time()\n\ttimeClose = 0\n\ttimeDistant = 0\n\ttimeOrbit = 0\n\ttimeLoop = 0\n\twhile t0):\n\t\t\tif switch_to_gr: approximation = 2\n\t\t\tts = np.linspace(0, dt.value_in(units.yr), n+1)#100*n+1) #n is the number of time intervals\n\t\t\tk.integrate(ts, pot=pot, relativity=input.relativity, tidal_effects=input.tidal_effects, gw=input.gw, tau_0=lambda *args: tau_0(args[0]|units.pc, k.m()|units.MSun, args[1]|units.pc, Q_max_a, type, m_total, b, args[2]|units.kms, m_per=m_per).value_in(units.yr), random_number=random_number, rtol=rtol, atol=atol, approximation=approximation, debug_file=input.output_file_2, points_per_period=input.n) #, rtol=1e-3, atol=1e-6)\n\t\t\tt += k.t_fin|units.yr\n\t\t\tif k.merger: break\n\t\t\trandom_number = k.probability\n\t\t\touter_integration_time = k.outer_integration_time\n\t\t\ttidal_time = k.tidal_time\n\t\t\tinner_integration_time = k.inner_integration_time\n\t\t\tepsilon_gr = k.epsilon_gr\n\t\t\tde_abs += k.de_abs\n\t\t\tdi_abs += k.di_abs\n\t\t\tif not switch_to_gr: switch_to_gr = k.switch_to_gr\n\t\t\tk = KeplerRing(k.ecc_fin, k.inc_fin, k.long_asc_fin, k.arg_peri_fin, k.r(k.t_fin), k.v(k.t_fin), a=k.a_fin, m=k._m, q=k._q)\n\t\t\tif t>=t_final: break\n\t\t\tR, z, phi = k.r()\n\t\t\tif np.sqrt(R**2+z**2) > 100: break\n\t\ttimeOrbit2 = time.time()\n\t\ttimeOrbit += timeOrbit2 - timeOrbit1\n\t\tR, z, phi = k.r()\n\t\tv_R, v_z, v_phi = k.v()\n\t\tif k.merger:\n\t\t\tprint(t.value_in(units.yr), \"merger\", file=output_file)\n\t\t\treturn 1\n\t\tprint(t.value_in(units.yr), R, z, phi, v_R, v_z, v_phi, k.a(), k.m(), k._q, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), random_number_0, dt.value_in(units.yr), n, epsilon_gr, time.time()-time0, de_abs, di_abs, file=output_file)\n\t\toutput_file.flush()\n\t\tif t>=t_final: return 0\n\t\tif np.sqrt(R**2+z**2) > 100:\n\t\t\tprint(t.value_in(units.yr), \"ejected\", file=output_file)\n\t\t\treturn 5\n\t\tif input.includeEncounters:\n\t\t\ttime3body = time.time()\n\t\t\t# sample the perturber parameters\n\t\t\tQ = 0|units.m\n\t\t\twhile Q<=Q_min_a*(k.a()|units.AU):\n\t\t\t\tm_per, aStar, eStar, iStar, OmegaStar, omegaStar = sample_encounter_parameters (k.a()|units.AU, k.m()|units.MSun, np.sqrt(R**2+z**2)|units.pc, phi, Q_max_a, type, m_total, b, [v_R, v_phi, v_z], m_per=m_per)\n\t\t\t\tQ = aStar*(1-eStar)\n\n\t\t\t# perform the scattering\n\t\t\tq = k._q\n\t\t\tm1 = k.m()/(1+q)\n\t\t\tm2 = k.m()*q/(1+q)\n\t\t\tif Q<=Q_hybrid_a*(k.a()|units.AU):\n\t\t\t\ttimeClose1 = time.time()\n\t\t\t\tresult, third_body_final, dv_binary, a_fin, e_fin, i_fin, Omega_fin, omega_fin, n_3body = scattering_hybrid (m1|units.MSun, m2|units.MSun, k.a()|units.AU, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), m_per, aStar, eStar, iStar, OmegaStar, omegaStar)\n\t\t\t\ttimeClose2 = time.time()\n\t\t\t\ttimeClose += timeClose2 - timeClose1 \n\t\t\telse:\n\t\t\t\tresult = 0\n\t\t\t\tthird_body_final = 2\n\t\t\t\ttimeDistant1 = time.time()\n\t\t\t\tdv_binary, a_fin, e_fin, i_fin, Omega_fin, omega_fin = scattering_SA (m1|units.MSun, m2|units.MSun, k.a()|units.AU, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), m_per, aStar, eStar, iStar, OmegaStar, omegaStar)\n\t\t\t\ttimeDistant2 = time.time()\n\t\t\t\ttimeDistant += timeDistant2 - timeDistant1\n\t\t\t\t \n\t\t\tprint('perturber: ', m_per.value_in(units.MSun), Q.value_in(units.AU), eStar, iStar, OmegaStar, omegaStar, file=output_file)\n\t\t\toutput_file.flush()\n\t\t\tif result == 2:\n\t\t\t\tprint(t.value_in(units.yr), \"destroyed\", file=output_file)\n\t\t\t\treturn 2 \n\t\t\telif result == 1: \n\t\t\t\tprint(t.value_in(units.yr), \"calculation abandoned after more than n_orbits_max bound orbits\", file=output_file)\n\t\t\t\toutput_file.flush()\n\t\t\telif result == 3: \n\t\t\t\tprint(t.value_in(units.yr), \"calculation abandoned after spending too much time in a 3-body phase\", file=output_file)\n\t\t\t\toutput_file.flush()\n\t\t\telif result == 0:\n\t\t\t\t# assign new orbital parameters to the binary\n\t\t\t\tif third_body_final == 0: m1 = m_per.value_in(units.MSun)\n\t\t\t\tif third_body_final == 1: m2 = m_per.value_in(units.MSun)\n\t\t\t\tv_R, v_z, v_phi = k.v()\t#velocity before the scattering\n\t\t\t\tx = R * np.cos(phi)\n\t\t\t\ty = R * np.sin(phi)\n\t\t\t\tif input.disableKicks:\n\t\t\t\t\tdv_x = 0\n\t\t\t\t\tdv_y = 0\n\t\t\t\t\tdv_z = 0\n\t\t\t\telse:\n\t\t\t\t\tdv_x = dv_binary[0].value_in(units.kms)\t#velocity change during the scattering\n\t\t\t\t\tdv_y = dv_binary[1].value_in(units.kms)\n\t\t\t\t\tdv_z = dv_binary[2].value_in(units.kms)\n\t\t\t\tdv_R = (x*dv_x+y*dv_y)/R\n\t\t\t\tphi_unit_vector = np.cross([0, 0, 1], [x/R, y/R, 0])\n\t\t\t\tdv_phi = np.dot(phi_unit_vector, [dv_x, dv_y, dv_z])\n\t\t\t\tk = KeplerRing(e_fin, i_fin.value_in(units.rad), Omega_fin.value_in(units.rad), omega_fin.value_in(units.rad), [R, z, phi], [v_R+dv_R, v_z+dv_z, v_phi+dv_phi], a=a_fin.value_in(units.AU), m=m1+m2, q=min(m1/m2, m2/m1))\n\t\t\t\tm_bin = m1+m2\n\t\t\t\tprint(t.value_in(units.yr), R, z, phi, v_R+dv_R, v_z+dv_z, v_phi+dv_phi, k.a(), k.m(), k._q, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), time.time()-time3body, file=output_file)\n\t\t\t\toutput_file.flush()\n\t\t\telse:\n\t\t\t\tprint(t.value_in(units.yr), \"something really weird happened: result =\", result, file=output_file)\n\t\t\n\t\ttimeTotal = time.time()-timeTotal1\n\t\tif timeTotal>input.tmax: \n\t\t\tprint(t.value_in(units.yr), 'maximum calculation time (', str(input.tmax), ' s) exceeded', file=output_file)\n\t\t\toutput_file.flush()\n\t\t\treturn 3\n\t\tif k.a() > input.a_max:\n\t\t\tprint(t.value_in(units.yr), 'maximum semimajor axis (', str(input.a_max), ' AU) exceeded', file=output_file)\n\t\t\toutput_file.flush()\n\t\t\treturn 4\n\n\t# timeTotal2 = time.time()\n\t# print(\"total time\", timeTotal2-timeTotal1, \"s\", file=output_file)\n\t# print(\"close interaction time\", timeClose, \"s\", file=output_file)\n\t# print(\"distant interaction time\", timeDistant, \"s\", file=output_file)\n\t# print(\"outer orbit integration time\", timeOrbit, \"s\", file=output_file)\n\toutput_file.close()\n\n\treturn 0\n\ndef evolve_binary_encounters_only (input, n_enc, randomize):\n\n\tif input.includeWeakEncounters: Q_max_a = input.Q_max_a\n\telse: Q_max_a = Q_hybrid_a\n\t\n\t# Potential\n\tb = input.b\n\tm_total = input.m_total\n\ttype = input.potential\n\tif type==\"Plummer\": pot = PlummerPotential(amp=m_total*u.solMass, b=b*u.pc) \n\telif type==\"Hernquist\": pot = HernquistPotential(amp=2*m_total*u.solMass, a=b*u.pc) \n\n\t# Outer binary parameters\n\ta_out = input.a_out # Outer semi-major axis in pc\n\tecc_out = input.e_out # Outer orbit eccentricity\n\tinc_out = input.inc_out # Outer orbit inclination,\n\n\t# Inner binary parameters\n\tm1 = input.m1\n\tm2 = input.m2\n\ta_in = input.a # Semi-major axis in AU\n\tecc = input.e \t# Eccentricity\n\tinc = input.i # Inclination with respect to the z-axis\n\targ_peri = input.omega # Arugment of pericentre\n\tlong_asc = input.Omega # Longitude of the ascending node\n\tm_bin = m1+m2 # Total mass in solar masses\n\tm_bin_init = m_bin|units.MSun\n\n\t# Start at pericentre\n\tr = a_out * (1 - ecc_out) # Spherical radius\n\tR = r * np.cos(inc_out) # Cylindrical radius\n\tz = r * np.sin(inc_out) # Cylindrical height\n\tphi = 0\n\n\t# Compute the correct v_phi at pericentre for the selected eccentricity and potential\n\tv_phi = ecc_to_vel(pot, ecc_out, [R, z, 0])\n\n\t# Define the KeplerRing\n\tk = KeplerRing(ecc, inc, long_asc, arg_peri, [R, z, 0], [0, 0, v_phi], a=a_in, m=m_bin, q=m2/m1)\n\n\toutput_file = open(input.output_file, 'a')\n\tprint('R[pc] z phi v_R[km/s] v_z v_phi a[AU] m[MSun] q ecc inc long_asc arg_peri t_3body[s]', file=output_file)\n\tprint('perturber: m_per[MSun] Q[AU] eStar iStar OmegaStar omegaStar', file=output_file)\n\tprint(R, z, phi, 0, 0, v_phi, k.a(), k.m(), k._q, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), file=output_file)\n\toutput_file.flush()\n\n\trtol=input.rtol #1e-11\n\tatol= rtol*1e-3 #1e-14\n\n\tfor i in range(n_enc):\n\t\tif randomize:\n\t\t\targ_peri = 2*np.pi*np.random.random_sample()\n\t\t\tlong_asc = 2*np.pi*np.random.random_sample()\n\t\t\tinc = np.arccos(2*np.random.random_sample()-1)\n\t\t\tk = KeplerRing(ecc, inc, long_asc, arg_peri, [R, z, 0], [0, 0, v_phi], a=a_in, m=m_bin, q=m2/m1)\n\t\t\tprint(R, z, phi, 0, 0, v_phi, k.a(), k.m(), k._q, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), file=output_file)\n\t\t\toutput_file.flush()\n\t\ttime3body = time.time()\n\t\t# sample the perturber parameters\n\t\tm_per, aStar, eStar, iStar, OmegaStar, omegaStar = sample_encounter_parameters (k.a()|units.AU, k.m()|units.MSun, np.sqrt(R**2+z**2)|units.pc, phi, Q_max_a, type, m_total, b, [0, v_phi, 0], m_per=m_per)\n\t\tQ = aStar*(1-eStar)\n\t\tprint('perturber: ', m_per.value_in(units.MSun), Q.value_in(units.AU), eStar, iStar, OmegaStar, omegaStar, file=output_file)\n\t\toutput_file.flush()\n\n\t\t# perform the scattering\n\t\tq = k._q\n\t\tm1 = k.m()/(1+q)\n\t\tm2 = k.m()*q/(1+q)\n\t\tif Q<=Q_hybrid_a*(k.a()|units.AU):\n\t\t\tresult, third_body_final, dv_binary, a_fin, e_fin, i_fin, Omega_fin, omega_fin, n_3body = scattering_hybrid (m1|units.MSun, m2|units.MSun, k.a()|units.AU, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), m_per, aStar, eStar, iStar, OmegaStar, omegaStar)\n\t\telse:\n\t\t\tresult = 0\n\t\t\tthird_body_final = 2\n\t\t\tdv_binary, a_fin, e_fin, i_fin, Omega_fin, omega_fin = scattering_SA (m1|units.MSun, m2|units.MSun, k.a()|units.AU, k.ecc(), k.inc(), k.long_asc(), k.arg_peri(), m_per, aStar, eStar, iStar, OmegaStar, omegaStar)\n\n\t\tif result == 2:\n\t\t\tprint(t.value_in(units.yr), \"destroyed\", file=output_file)\n\t\t\treturn 2 \n\t\telif result == 1: \n\t\t\tprint(t.value_in(units.yr), \"calculation abandoned after more than n_orbits_max bound orbits\", file=output_file)\n\t\t\toutput_file.flush()\n\t\telif result == 3: \n\t\t\tprint(t.value_in(units.yr), \"calculation abandoned after spending too much time in a 3-body phase\", file=output_file)\n\t\t\toutput_file.flush()\n\t\telif result == 0:\n\t\t\t# assign new orbital parameters to the binary\n\t\t\tif third_body_final == 0: m1 = m_per.value_in(units.MSun)\n\t\t\tif third_body_final == 1: m2 = m_per.value_in(units.MSun)\n\t\t\tv_R, v_z, v_phi = k.v()\t#velocity before the scattering\n\t\t\tx = R * np.cos(phi)\n\t\t\ty = R * np.sin(phi)\n\t\t\tdv_x = dv_binary[0].value_in(units.kms)\t#velocity change during the scattering\n\t\t\tdv_y = dv_binary[1].value_in(units.kms)\n\t\t\tdv_z = dv_binary[2].value_in(units.kms)\n\t\t\tdv_R = (x*dv_x+y*dv_y)/R\n\t\t\tphi_unit_vector = np.cross([0, 0, 1], [x/R, y/R, 0])\n\t\t\tdv_phi = np.dot(phi_unit_vector, [dv_x, dv_y, dv_z])\n\t\t\tk1 = KeplerRing(e_fin, i_fin.value_in(units.rad), Omega_fin.value_in(units.rad), omega_fin.value_in(units.rad), [R, z, phi], [v_R+dv_R, v_z+dv_z, v_phi+dv_phi], a=a_fin.value_in(units.AU), m=m1+m2, q=min(m1/m2, m2/m1))\n\t\t\tm_bin = m1+m2\n\t\t\tprint(R, z, phi, v_R+dv_R, v_z+dv_z, v_phi+dv_phi, k1.a(), k1.m(), k1._q, k1.ecc(), k1.inc(), k1.long_asc(), k1.arg_peri(), time.time()-time3body, file=output_file)\n\t\t\toutput_file.flush()\n\n\toutput_file.close()\n\n\treturn 0","repo_name":"RZCas/binary-evolution-in-a-cluster","sub_path":"binary_evolution_with_flybys.py","file_name":"binary_evolution_with_flybys.py","file_ext":"py","file_size_in_byte":30312,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"18843752867","text":"\"\"\" Broadly applicable NGS processing/analysis functionality \"\"\"\n\nimport errno\nimport os\nimport re\nimport subprocess\n\nfrom attmap import AttMapEcho\nfrom yacman import load_yaml\n\nfrom .exceptions import UnsupportedFiletypeException\nfrom .utils import is_fastq, is_gzipped_fastq, is_sam_or_bam\n\n\nclass NGSTk(AttMapEcho):\n \"\"\"\n Class to hold functions to build command strings used during pipeline runs.\n Object can be instantiated with a string of a path to a yaml `pipeline config file`.\n Since NGSTk inherits from `AttMapEcho`, the passed config file and its elements\n will be accessible through the NGSTk object as attributes under `config` (e.g.\n `NGSTk.tools.java`). In case no `config_file` argument is passed, all commands will\n be returned assuming the tool is in the user's $PATH.\n\n :param str config_file: Path to pipeline yaml config file (optional).\n :param pypiper.PipelineManager pm: A PipelineManager with which to associate this toolkit instance;\n that is, essentially a source from which to grab paths to tools,\n resources, etc.\n\n :Example:\n\n from pypiper.ngstk import NGSTk as tk\n tk = NGSTk()\n tk.samtools_index(\"sample.bam\")\n # returns: samtools index sample.bam\n\n # Using a configuration file (custom executable location):\n from pypiper.ngstk import NGSTk\n tk = NGSTk(\"pipeline_config_file.yaml\")\n tk.samtools_index(\"sample.bam\")\n # returns: /home/.local/samtools/bin/samtools index sample.bam\n\n \"\"\"\n\n def __init__(self, config_file=None, pm=None):\n # parse yaml into the project's attributes\n # self.add_entries(**config)\n super(NGSTk, self).__init__(\n None if config_file is None else load_yaml(config_file)\n )\n\n # Keep a link to the pipeline manager, if one is provided.\n # if None is provided, instantiate \"tools\" and \"parameters\" with empty AttMaps\n # this allows the usage of the same code for a command with and without using a pipeline manager\n if pm is not None:\n self.pm = pm\n if hasattr(pm.config, \"tools\"):\n self.tools = self.pm.config.tools\n else:\n self.tools = AttMapEcho()\n if hasattr(pm.config, \"parameters\"):\n self.parameters = self.pm.config.parameters\n else:\n self.parameters = AttMapEcho()\n else:\n self.tools = AttMapEcho()\n self.parameters = AttMapEcho()\n\n # If pigz is available, use that. Otherwise, default to gzip.\n if (\n hasattr(self.pm, \"cores\")\n and self.pm.cores > 1\n and self.check_command(\"pigz\")\n ):\n self.ziptool_cmd = \"pigz -f -p {}\".format(self.pm.cores)\n else:\n self.ziptool_cmd = \"gzip -f\"\n\n def _ensure_folders(self, *paths):\n \"\"\"\n Ensure that paths to folder(s) exist.\n\n Some command-line tools will not attempt to create folder(s) needed\n for output path to exist. They instead assume that they already are\n present and will fail if that assumption does not hold.\n\n :param Iterable[str] paths: Collection of path for which\n \"\"\"\n for p in paths:\n # Only provide assurance for absolute paths.\n if not p or not os.path.isabs(p):\n continue\n # See if what we're assuring is file- or folder-like.\n fpath, fname = os.path.split(p)\n base, ext = os.path.splitext(fname)\n # If there's no extension, ensure that we have the whole path.\n # Otherwise, just ensure that we have path to file's folder.\n self.make_dir(fpath if ext else p)\n\n @property\n def ziptool(self):\n \"\"\"\n Returns the command to use for compressing/decompressing.\n\n :return str: Either 'gzip' or 'pigz' if installed and multiple cores\n \"\"\"\n return self.ziptool_cmd\n\n def make_dir(self, path):\n \"\"\"\n Forge path to directory, creating intermediates as needed.\n\n :param str path: Path to create.\n \"\"\"\n try:\n os.makedirs(path)\n except OSError as exception:\n if exception.errno != errno.EEXIST:\n raise\n\n def make_sure_path_exists(self, path):\n \"\"\"Alias for make_dir\"\"\"\n self.make_dir(path)\n\n # Borrowed from looper\n def check_command(self, command):\n \"\"\"\n Check if command can be called.\n \"\"\"\n\n # Use `command` to see if command is callable, store exit code\n code = os.system(\n \"command -v {0} >/dev/null 2>&1 || {{ exit 1; }}\".format(command)\n )\n\n # If exit code is not 0, report which command failed and return False, else return True\n if code != 0:\n print(\"Command is not callable: {0}\".format(command))\n return False\n else:\n return True\n\n def get_file_size(self, filenames):\n \"\"\"\n Get size of all files in string (space-separated) in megabytes (Mb).\n\n :param str filenames: a space-separated string of filenames\n \"\"\"\n # use (1024 ** 3) for gigabytes\n # equivalent to: stat -Lc '%s' filename\n\n # If given a list, recurse through it.\n if type(filenames) is list:\n return sum([self.get_file_size(filename) for filename in filenames])\n\n return round(\n sum([float(os.stat(f).st_size) for f in filenames.split(\" \")])\n / (1024**2),\n 4,\n )\n\n def mark_duplicates(\n self, aligned_file, out_file, metrics_file, remove_duplicates=\"True\"\n ):\n cmd = self.tools.java\n if self.pm.javamem: # If a memory restriction exists.\n cmd += \" -Xmx\" + self.pm.javamem\n cmd += \" -jar \" + self.tools.picard + \" MarkDuplicates\"\n cmd += \" INPUT=\" + aligned_file\n cmd += \" OUTPUT=\" + out_file\n cmd += \" METRICS_FILE=\" + metrics_file\n cmd += \" REMOVE_DUPLICATES=\" + remove_duplicates\n return cmd\n\n def bam2fastq(\n self, input_bam, output_fastq, output_fastq2=None, unpaired_fastq=None\n ):\n \"\"\"\n Create command to convert BAM(s) to FASTQ(s).\n\n :param str input_bam: Path to sequencing reads file to convert\n :param output_fastq: Path to FASTQ to write\n :param output_fastq2: Path to (R2) FASTQ to write\n :param unpaired_fastq: Path to unpaired FASTQ to write\n :return str: Command to convert BAM(s) to FASTQ(s)\n \"\"\"\n self._ensure_folders(output_fastq, output_fastq2, unpaired_fastq)\n cmd = self.tools.java + \" -Xmx\" + self.pm.javamem\n cmd += \" -jar \" + self.tools.picard + \" SamToFastq\"\n cmd += \" INPUT={0}\".format(input_bam)\n cmd += \" FASTQ={0}\".format(output_fastq)\n if output_fastq2 is not None and unpaired_fastq is not None:\n cmd += \" SECOND_END_FASTQ={0}\".format(output_fastq2)\n cmd += \" UNPAIRED_FASTQ={0}\".format(unpaired_fastq)\n return cmd\n\n def bam_to_fastq(self, bam_file, out_fastq_pre, paired_end):\n \"\"\"\n Build command to convert BAM file to FASTQ file(s) (R1/R2).\n\n :param str bam_file: path to BAM file with sequencing reads\n :param str out_fastq_pre: path prefix for output FASTQ file(s)\n :param bool paired_end: whether the given file contains paired-end\n or single-end sequencing reads\n :return str: file conversion command, ready to run\n \"\"\"\n self.make_sure_path_exists(os.path.dirname(out_fastq_pre))\n cmd = self.tools.java + \" -Xmx\" + self.pm.javamem\n cmd += \" -jar \" + self.tools.picard + \" SamToFastq\"\n cmd += \" I=\" + bam_file\n cmd += \" F=\" + out_fastq_pre + \"_R1.fastq\"\n if paired_end:\n cmd += \" F2=\" + out_fastq_pre + \"_R2.fastq\"\n cmd += \" INCLUDE_NON_PF_READS=true\"\n cmd += \" QUIET=true\"\n cmd += \" VERBOSITY=ERROR\"\n cmd += \" VALIDATION_STRINGENCY=SILENT\"\n return cmd\n\n def bam_to_fastq_awk(self, bam_file, out_fastq_pre, paired_end, zipmode=False):\n \"\"\"\n This converts bam file to fastq files, but using awk. As of 2016, this is much faster\n than the standard way of doing this using Picard, and also much faster than the\n bedtools implementation as well; however, it does no sanity checks and assumes the reads\n (for paired data) are all paired (no singletons), in the correct order.\n :param bool zipmode: Should the output be zipped?\n \"\"\"\n self.make_sure_path_exists(os.path.dirname(out_fastq_pre))\n fq1 = out_fastq_pre + \"_R1.fastq\"\n fq2 = out_fastq_pre + \"_R2.fastq\"\n\n if zipmode:\n fq1 = fq1 + \".gz\"\n fq2 = fq2 + \".gz\"\n fq1_target = ' | \"' + self.ziptool + \" -c > \" + fq1 + '\"'\n fq2_target = ' | \"' + self.ziptool + \" -c > \" + fq2 + '\"'\n else:\n fq1_target = ' > \"' + fq1 + '\"'\n fq2_target = ' > \"' + fq2 + '\"'\n\n if paired_end:\n cmd = self.tools.samtools + \" view \" + bam_file + \" | awk '\"\n cmd += r'{ if (NR%2==1) print \"@\"$1\"/1\\n\"$10\"\\n+\\n\"$11' + fq1_target + \";\"\n cmd += r' else print \"@\"$1\"/2\\n\"$10\"\\n+\\n\"$11' + fq2_target + \"; }\"\n cmd += \"'\" # end the awk command\n else:\n fq2 = None\n cmd = self.tools.samtools + \" view \" + bam_file + \" | awk '\"\n cmd += r'{ print \"@\"$1\"\\n\"$10\"\\n+\\n\"$11' + fq1_target + \"; }\"\n cmd += \"'\"\n return cmd, fq1, fq2\n\n def bam_to_fastq_bedtools(self, bam_file, out_fastq_pre, paired_end):\n \"\"\"\n Converts bam to fastq; A version using bedtools\n \"\"\"\n self.make_sure_path_exists(os.path.dirname(out_fastq_pre))\n fq1 = out_fastq_pre + \"_R1.fastq\"\n fq2 = None\n cmd = (\n self.tools.bedtools\n + \" bamtofastq -i \"\n + bam_file\n + \" -fq \"\n + fq1\n + \".fastq\"\n )\n if paired_end:\n fq2 = out_fastq_pre + \"_R2.fastq\"\n cmd += \" -fq2 \" + fq2\n\n return cmd, fq1, fq2\n\n def get_input_ext(self, input_file):\n \"\"\"\n Get the extension of the input_file. Assumes you're using either\n .bam or .fastq/.fq or .fastq.gz/.fq.gz.\n \"\"\"\n if input_file.endswith(\".bam\"):\n input_ext = \".bam\"\n elif input_file.endswith(\".fastq.gz\") or input_file.endswith(\".fq.gz\"):\n input_ext = \".fastq.gz\"\n elif input_file.endswith(\".fastq\") or input_file.endswith(\".fq\"):\n input_ext = \".fastq\"\n else:\n errmsg = (\n \"'{}'; this pipeline can only deal with .bam, .fastq, \"\n \"or .fastq.gz files\".format(input_file)\n )\n raise UnsupportedFiletypeException(errmsg)\n return input_ext\n\n def merge_or_link(self, input_args, raw_folder, local_base=\"sample\"):\n \"\"\"\n Standardizes various input possibilities by converting either .bam,\n .fastq, or .fastq.gz files into a local file; merging those if multiple\n files given.\n\n :param list input_args: This is a list of arguments, each one is a\n class of inputs (which can in turn be a string or a list).\n Typically, input_args is a list with 2 elements: first a list of\n read1 files; second an (optional!) list of read2 files.\n :param str raw_folder: Name/path of folder for the merge/link.\n :param str local_base: Usually the sample name. This (plus file\n extension) will be the name of the local file linked (or merged)\n by this function.\n \"\"\"\n self.make_sure_path_exists(raw_folder)\n\n if not isinstance(input_args, list):\n raise Exception(\"Input must be a list\")\n\n if any(isinstance(i, list) for i in input_args):\n # We have a list of lists. Process each individually.\n local_input_files = list()\n n_input_files = len(list(filter(bool, input_args)))\n print(\"Number of input file sets: \" + str(n_input_files))\n\n for input_i, input_arg in enumerate(input_args):\n # Count how many non-null items there are in the list;\n # we only append _R1 (etc.) if there are multiple input files.\n if n_input_files > 1:\n local_base_extended = local_base + \"_R\" + str(input_i + 1)\n else:\n local_base_extended = local_base\n if input_arg:\n out = self.merge_or_link(input_arg, raw_folder, local_base_extended)\n\n print(\"Local input file: '{}'\".format(out))\n # Make sure file exists:\n if not os.path.isfile(out):\n print(\"Not a file: '{}'\".format(out))\n\n local_input_files.append(out)\n\n return local_input_files\n\n else:\n # We have a list of individual arguments. Merge them.\n\n if len(input_args) == 1:\n # Only one argument in this list. A single input file; we just link\n # it, regardless of file type:\n # Pull the value out of the list\n input_arg = input_args[0]\n input_ext = self.get_input_ext(input_arg)\n\n # Convert to absolute path\n if not os.path.isabs(input_arg):\n input_arg = os.path.abspath(input_arg)\n\n # Link it to into the raw folder\n local_input_abs = os.path.join(raw_folder, local_base + input_ext)\n self.pm.run(\n \"ln -sf \" + input_arg + \" \" + local_input_abs,\n target=local_input_abs,\n shell=True,\n )\n # return the local (linked) filename absolute path\n return local_input_abs\n\n else:\n # Otherwise, there are multiple inputs.\n # If more than 1 input file is given, then these are to be merged\n # if they are in bam format.\n if all([self.get_input_ext(x) == \".bam\" for x in input_args]):\n sample_merged = local_base + \".merged.bam\"\n output_merge = os.path.join(raw_folder, sample_merged)\n cmd = self.merge_bams_samtools(input_args, output_merge)\n self.pm.debug(\"cmd: {}\".format(cmd))\n self.pm.run(cmd, output_merge)\n cmd2 = self.validate_bam(output_merge)\n self.pm.run(cmd, output_merge, nofail=True)\n return output_merge\n\n # if multiple fastq\n if all([self.get_input_ext(x) == \".fastq.gz\" for x in input_args]):\n sample_merged_gz = local_base + \".merged.fastq.gz\"\n output_merge_gz = os.path.join(raw_folder, sample_merged_gz)\n # cmd1 = self.ziptool + \"-d -c \" + \" \".join(input_args) + \" > \" + output_merge\n # cmd2 = self.ziptool + \" \" + output_merge\n # self.pm.run([cmd1, cmd2], output_merge_gz)\n # you can save yourself the decompression/recompression:\n cmd = \"cat \" + \" \".join(input_args) + \" > \" + output_merge_gz\n self.pm.run(cmd, output_merge_gz)\n return output_merge_gz\n\n if all([self.get_input_ext(x) == \".fastq\" for x in input_args]):\n sample_merged = local_base + \".merged.fastq\"\n output_merge = os.path.join(raw_folder, sample_merged)\n cmd = \"cat \" + \" \".join(input_args) + \" > \" + output_merge\n self.pm.run(cmd, output_merge)\n return output_merge\n\n # At this point, we don't recognize the input file types or they\n # do not match.\n raise NotImplementedError(\n \"Input files must be of the same type, and can only \"\n \"merge bam or fastq.\"\n )\n\n def input_to_fastq(\n self,\n input_file,\n sample_name,\n paired_end,\n fastq_folder,\n output_file=None,\n multiclass=False,\n zipmode=False,\n ):\n \"\"\"\n Builds a command to convert input file to fastq, for various inputs.\n\n Takes either .bam, .fastq.gz, or .fastq input and returns\n commands that will create the .fastq file, regardless of input type.\n This is useful to made your pipeline easily accept any of these input\n types seamlessly, standardizing you to fastq which is still the\n most common format for adapter trimmers, etc. You can specify you want\n output either zipped or not.\n\n Commands will place the output fastq file in given `fastq_folder`.\n\n :param str input_file: filename of input you want to convert to fastq\n :param bool multiclass: Are both read1 and read2 included in a single\n file? User should not need to set this; it will be inferred and used\n in recursive calls, based on number files, and the paired_end arg.\n :param bool zipmode: Should the output be .fastq.gz? Otherwise, just fastq\n :return str: A command (to be run with PipelineManager) that will ensure\n your fastq file exists.\n \"\"\"\n\n fastq_prefix = os.path.join(fastq_folder, sample_name)\n self.make_sure_path_exists(fastq_folder)\n\n # this expects a list; if it gets a string, wrap it in a list.\n if type(input_file) != list:\n input_file = [input_file]\n\n # If multiple files were provided, recurse on each file individually\n if len(input_file) > 1:\n cmd = []\n output_file = []\n for in_i, in_arg in enumerate(input_file):\n output = fastq_prefix + \"_R\" + str(in_i + 1) + \".fastq\"\n result_cmd, uf, result_file = self.input_to_fastq(\n in_arg,\n sample_name,\n paired_end,\n fastq_folder,\n output,\n multiclass=True,\n zipmode=zipmode,\n )\n cmd.append(result_cmd)\n output_file.append(result_file)\n\n else:\n # There was only 1 input class.\n # Convert back into a string\n input_file = input_file[0]\n if not output_file:\n output_file = fastq_prefix + \"_R1.fastq\"\n if zipmode:\n output_file = output_file + \".gz\"\n\n input_ext = self.get_input_ext(input_file) # handles .fq or .fastq\n\n if input_ext == \".bam\":\n print(\"Found .bam file\")\n # cmd = self.bam_to_fastq(input_file, fastq_prefix, paired_end)\n cmd, fq1, fq2 = self.bam_to_fastq_awk(\n input_file, fastq_prefix, paired_end, zipmode\n )\n # pm.run(cmd, output_file, follow=check_fastq)\n if fq2:\n output_file = [fq1, fq2]\n else:\n output_file = fq1\n elif input_ext == \".fastq.gz\":\n print(\"Found .fastq.gz file\")\n if paired_end and not multiclass:\n if zipmode:\n raise NotImplementedError(\n \"Can't use zipmode on interleaved fastq data.\"\n )\n # For paired-end reads in one fastq file, we must split the\n # file into 2. The pipeline author will need to include this\n # python script in the scripts directory.\n # TODO: make this self-contained in pypiper. This is a rare\n # use case these days, as fastq files are almost never\n # interleaved anymore.\n script_path = os.path.join(self.tools.scripts_dir, \"fastq_split.py\")\n cmd = self.tools.python + \" -u \" + script_path\n cmd += \" -i \" + input_file\n cmd += \" -o \" + fastq_prefix\n # Must also return the set of output files\n output_file = [\n fastq_prefix + \"_R1.fastq\",\n fastq_prefix + \"_R2.fastq\",\n ]\n else:\n if zipmode:\n # we do nothing!\n cmd = \"ln -sf \" + input_file + \" \" + output_file\n print(\"Found .fq.gz file; no conversion necessary\")\n else:\n # For single-end reads, we just unzip the fastq.gz file.\n # or, paired-end reads that were already split.\n cmd = (\n self.ziptool + \" -d -c \" + input_file + \" > \" + output_file\n )\n # a non-shell version\n # cmd1 = \"gunzip --force \" + input_file\n # cmd2 = \"mv \" + os.path.splitext(input_file)[0] + \" \" + output_file\n # cmd = [cmd1, cmd2]\n elif input_ext == \".fastq\":\n if zipmode:\n cmd = self.ziptool + \" -c \" + input_file + \" > \" + output_file\n else:\n cmd = \"ln -sf \" + input_file + \" \" + output_file\n print(\"Found .fastq file; no conversion necessary\")\n\n return [cmd, fastq_prefix, output_file]\n\n def check_fastq(self, input_files, output_files, paired_end):\n \"\"\"\n Returns a follow sanity-check function to be run after a fastq conversion.\n Run following a command that will produce the fastq files.\n\n This function will make sure any input files have the same number of reads as the\n output files.\n \"\"\"\n\n # Define a temporary function which we will return, to be called by the\n # pipeline.\n # Must define default parameters here based on the parameters passed in. This locks\n # these values in place, so that the variables will be defined when this function\n # is called without parameters as a follow function by pm.run.\n\n # This is AFTER merge, so if there are multiple files it means the\n # files were split into read1/read2; therefore I must divide by number\n # of files for final reads.\n def temp_func(\n input_files=input_files, output_files=output_files, paired_end=paired_end\n ):\n if type(input_files) != list:\n input_files = [input_files]\n if type(output_files) != list:\n output_files = [output_files]\n\n n_input_files = len(list(filter(bool, input_files)))\n n_output_files = len(list(filter(bool, output_files)))\n\n total_reads = sum(\n [\n int(self.count_reads(input_file, paired_end))\n for input_file in input_files\n ]\n )\n raw_reads = int(total_reads / n_input_files)\n self.pm.pipestat.report(values={\"Raw_reads\": str(raw_reads)})\n\n total_fastq_reads = sum(\n [\n int(self.count_reads(output_file, paired_end))\n for output_file in output_files\n ]\n )\n fastq_reads = int(total_fastq_reads / n_output_files)\n\n self.pm.pipestat.report(values={\"Fastq_reads\": fastq_reads})\n input_ext = self.get_input_ext(input_files[0])\n # We can only assess pass filter reads in bam files with flags.\n if input_ext == \".bam\":\n num_failed_filter = sum(\n [int(self.count_fail_reads(f, paired_end)) for f in input_files]\n )\n pf_reads = int(raw_reads) - num_failed_filter\n self.pm.pipestat.report(values={\"PF_reads\": str(pf_reads)})\n if fastq_reads != int(raw_reads):\n raise Exception(\n \"Fastq conversion error? Number of input reads \"\n \"doesn't number of output reads.\"\n )\n\n return fastq_reads\n\n return temp_func\n\n def check_trim(\n self, trimmed_fastq, paired_end, trimmed_fastq_R2=None, fastqc_folder=None\n ):\n \"\"\"\n Build function to evaluate read trimming, and optionally run fastqc.\n\n This is useful to construct an argument for the 'follow' parameter of\n a PipelineManager's 'run' method.\n\n :param str trimmed_fastq: Path to trimmed reads file.\n :param bool paired_end: Whether the processing is being done with\n paired-end sequencing data.\n :param str trimmed_fastq_R2: Path to read 2 file for the paired-end case.\n :param str fastqc_folder: Path to folder within which to place fastqc\n output files; if unspecified, fastqc will not be run.\n :return callable: Function to evaluate read trimming and possibly run\n fastqc.\n \"\"\"\n\n def temp_func():\n print(\"Evaluating read trimming\")\n\n if paired_end and not trimmed_fastq_R2:\n print(\"WARNING: specified paired-end but no R2 file\")\n\n n_trim = float(self.count_reads(trimmed_fastq, paired_end))\n self.pm.pipestat.report(values={\"Trimmed_reads\": int(n_trim)})\n try:\n rr = float(self.pm.pipestat.retrieve(\"Raw_reads\"))\n except:\n print(\"Can't calculate trim loss rate without raw read result.\")\n else:\n self.pm.report_result(\n \"Trim_loss_rate\", round((rr - n_trim) * 100 / rr, 2)\n )\n\n # Also run a fastqc (if installed/requested)\n if fastqc_folder:\n if fastqc_folder and os.path.isabs(fastqc_folder):\n self.make_sure_path_exists(fastqc_folder)\n cmd = self.fastqc(trimmed_fastq, fastqc_folder)\n self.pm.run(cmd, lock_name=\"trimmed_fastqc\", nofail=True)\n fname, ext = os.path.splitext(os.path.basename(trimmed_fastq))\n fastqc_html = os.path.join(fastqc_folder, fname + \"_fastqc.html\")\n self.pm.pipestat.report(\n values={\n \"FastQC_report_R1\": {\n \"path\": fastqc_html,\n \"title\": \"FastQC report R1\",\n }\n }\n )\n\n if paired_end and trimmed_fastq_R2:\n cmd = self.fastqc(trimmed_fastq_R2, fastqc_folder)\n self.pm.run(cmd, lock_name=\"trimmed_fastqc_R2\", nofail=True)\n fname, ext = os.path.splitext(os.path.basename(trimmed_fastq_R2))\n fastqc_html = os.path.join(fastqc_folder, fname + \"_fastqc.html\")\n self.pm.pipestat.report(\n values={\n \"FastQC_report_R2\": {\n \"path\": fastqc_html,\n \"title\": \"FastQC report R2\",\n }\n }\n )\n\n return temp_func\n\n def validate_bam(self, input_bam):\n \"\"\"\n Wrapper for Picard's ValidateSamFile.\n\n :param str input_bam: Path to file to validate.\n :return str: Command to run for the validation.\n \"\"\"\n cmd = self.tools.java + \" -Xmx\" + self.pm.javamem\n cmd += \" -jar \" + self.tools.picard + \" ValidateSamFile\"\n cmd += \" INPUT=\" + input_bam\n return cmd\n\n def merge_bams(self, input_bams, merged_bam, in_sorted=\"TRUE\", tmp_dir=None):\n \"\"\"\n Combine multiple files into one.\n\n The tmp_dir parameter is important because on poorly configured\n systems, the default can sometimes fill up.\n\n :param Iterable[str] input_bams: Paths to files to combine\n :param str merged_bam: Path to which to write combined result.\n :param bool | str in_sorted: Whether the inputs are sorted\n :param str tmp_dir: Path to temporary directory.\n \"\"\"\n if not len(input_bams) > 1:\n print(\"No merge required\")\n return 0\n\n outdir, _ = os.path.split(merged_bam)\n if outdir and not os.path.exists(outdir):\n print(\"Creating path to merge file's folder: '{}'\".format(outdir))\n os.makedirs(outdir)\n\n # Handle more intuitive boolean argument.\n if in_sorted in [False, True]:\n in_sorted = \"TRUE\" if in_sorted else \"FALSE\"\n\n input_string = \" INPUT=\" + \" INPUT=\".join(input_bams)\n cmd = self.tools.java + \" -Xmx\" + self.pm.javamem\n cmd += \" -jar \" + self.tools.picard + \" MergeSamFiles\"\n cmd += input_string\n cmd += \" OUTPUT=\" + merged_bam\n cmd += \" ASSUME_SORTED=\" + str(in_sorted)\n cmd += \" CREATE_INDEX=TRUE\"\n cmd += \" VALIDATION_STRINGENCY=SILENT\"\n if tmp_dir:\n cmd += \" TMP_DIR=\" + tmp_dir\n\n return cmd\n\n def merge_bams_samtools(self, input_bams, merged_bam):\n cmd = self.tools.samtools + \" merge -f \"\n cmd += \" -@ \" + str(self.pm.cores)\n cmd += \" \" + merged_bam + \" \"\n cmd += \" \".join(input_bams)\n return cmd\n\n def merge_fastq(self, inputs, output, run=False, remove_inputs=False):\n \"\"\"\n Merge FASTQ files (zipped or not) into one.\n\n :param Iterable[str] inputs: Collection of paths to files to merge.\n :param str output: Path to single output file.\n :param bool run: Whether to run the command.\n :param bool remove_inputs: Whether to keep the original files.\n :return NoneType | str: Null if running the command, otherwise the\n command itself\n :raise ValueError: Raise ValueError if the call is such that\n inputs are to be deleted but command is not run.\n \"\"\"\n if remove_inputs and not run:\n raise ValueError(\"Can't delete files if command isn't run\")\n cmd = \"cat {} > {}\".format(\" \".join(inputs), output)\n if run:\n subprocess.check_call(cmd.split(), shell=True)\n if remove_inputs:\n cmd = \"rm {}\".format(\" \".join(inputs))\n subprocess.check_call(cmd.split(), shell=True)\n else:\n return cmd\n\n def count_lines(self, file_name):\n \"\"\"\n Uses the command-line utility wc to count the number of lines in a file. For MacOS, must strip leading whitespace from wc.\n\n :param str file_name: name of file whose lines are to be counted\n \"\"\"\n x = subprocess.check_output(\n \"wc -l \" + file_name + \" | sed -E 's/^[[:space:]]+//' | cut -f1 -d' '\",\n shell=True,\n )\n return x.decode().strip()\n\n def count_lines_zip(self, file_name):\n \"\"\"\n Uses the command-line utility wc to count the number of lines in a file. For MacOS, must strip leading whitespace from wc.\n For compressed files.\n :param file: file_name\n \"\"\"\n x = subprocess.check_output(\n self.ziptool\n + \" -d -c \"\n + file_name\n + \" | wc -l | sed -E 's/^[[:space:]]+//' | cut -f1 -d' '\",\n shell=True,\n )\n return x.decode().strip()\n\n def get_chrs_from_bam(self, file_name):\n \"\"\"\n Uses samtools to grab the chromosomes from the header that are contained\n in this bam file.\n \"\"\"\n x = subprocess.check_output(\n self.tools.samtools\n + \" view -H \"\n + file_name\n + \" | grep '^@SQ' | cut -f2| sed s'/SN://'\",\n shell=True,\n )\n # Chromosomes will be separated by newlines; split into list to return\n return x.decode().split()\n\n ###################################\n # Read counting functions\n ###################################\n # In these functions, A paired-end read, with 2 sequences, counts as a two reads\n\n def count_unique_reads(self, file_name, paired_end):\n \"\"\"\n Sometimes alignment software puts multiple locations for a single read; if you just count\n those reads, you will get an inaccurate count. This is _not_ the same as multimapping reads,\n which may or may not be actually duplicated in the bam file (depending on the alignment\n software).\n This function counts each read only once.\n This accounts for paired end or not for free because pairs have the same read name.\n In this function, a paired-end read would count as 2 reads.\n \"\"\"\n if file_name.endswith(\"sam\"):\n param = \"-S\"\n if file_name.endswith(\"bam\"):\n param = \"\"\n if paired_end:\n r1 = self.samtools_view(\n file_name,\n param=param + \" -f64\",\n postpend=\" | cut -f1 | sort -k1,1 -u | wc -l | sed -E 's/^[[:space:]]+//'\",\n )\n r2 = self.samtools_view(\n file_name,\n param=param + \" -f128\",\n postpend=\" | cut -f1 | sort -k1,1 -u | wc -l | sed -E 's/^[[:space:]]+//'\",\n )\n else:\n r1 = self.samtools_view(\n file_name,\n param=param + \"\",\n postpend=\" | cut -f1 | sort -k1,1 -u | wc -l | sed -E 's/^[[:space:]]+//'\",\n )\n r2 = 0\n return int(r1) + int(r2)\n\n def count_unique_mapped_reads(self, file_name, paired_end):\n \"\"\"\n For a bam or sam file with paired or or single-end reads, returns the\n number of mapped reads, counting each read only once, even if it appears\n mapped at multiple locations.\n\n :param str file_name: name of reads file\n :param bool paired_end: True/False paired end data\n :return int: Number of uniquely mapped reads.\n \"\"\"\n\n _, ext = os.path.splitext(file_name)\n ext = ext.lower()\n\n if ext == \".sam\":\n param = \"-S -F4\"\n elif ext == \".bam\":\n param = \"-F4\"\n else:\n raise ValueError(\"Not a SAM or BAM: '{}'\".format(file_name))\n\n if paired_end:\n r1 = self.samtools_view(\n file_name,\n param=param + \" -f64\",\n postpend=\" | cut -f1 | sort -k1,1 -u | wc -l | sed -E 's/^[[:space:]]+//'\",\n )\n r2 = self.samtools_view(\n file_name,\n param=param + \" -f128\",\n postpend=\" | cut -f1 | sort -k1,1 -u | wc -l | sed -E 's/^[[:space:]]+//'\",\n )\n else:\n r1 = self.samtools_view(\n file_name,\n param=param + \"\",\n postpend=\" | cut -f1 | sort -k1,1 -u | wc -l | sed -E 's/^[[:space:]]+//'\",\n )\n r2 = 0\n\n return int(r1) + int(r2)\n\n def count_flag_reads(self, file_name, flag, paired_end):\n \"\"\"\n Counts the number of reads with the specified flag.\n\n :param str file_name: name of reads file\n :param str flag: sam flag value to be read\n :param bool paired_end: This parameter is ignored; samtools automatically correctly responds depending\n on the data in the bamfile. We leave the option here just for consistency, since all the other\n counting functions require the parameter. This makes it easier to swap counting functions during\n pipeline development.\n \"\"\"\n\n param = \" -c -f\" + str(flag)\n if file_name.endswith(\"sam\"):\n param += \" -S\"\n return self.samtools_view(file_name, param=param)\n\n def count_multimapping_reads(self, file_name, paired_end):\n \"\"\"\n Counts the number of reads that mapped to multiple locations. Warning:\n currently, if the alignment software includes the reads at multiple locations, this function\n will count those more than once. This function is for software that randomly assigns,\n but flags reads as multimappers.\n\n :param str file_name: name of reads file\n :param paired_end: This parameter is ignored; samtools automatically correctly responds depending\n on the data in the bamfile. We leave the option here just for consistency, since all the other\n counting functions require the parameter. This makes it easier to swap counting functions during\n pipeline development.\n \"\"\"\n return int(self.count_flag_reads(file_name, 256, paired_end))\n\n def count_uniquelymapping_reads(self, file_name, paired_end):\n \"\"\"\n Counts the number of reads that mapped to a unique position.\n\n :param str file_name: name of reads file\n :param bool paired_end: This parameter is ignored.\n \"\"\"\n param = \" -c -F256\"\n if file_name.endswith(\"sam\"):\n param += \" -S\"\n return self.samtools_view(file_name, param=param)\n\n def count_fail_reads(self, file_name, paired_end):\n \"\"\"\n Counts the number of reads that failed platform/vendor quality checks.\n :param paired_end: This parameter is ignored; samtools automatically correctly responds depending\n on the data in the bamfile. We leave the option here just for consistency, since all the other\n counting functions require the parameter. This makes it easier to swap counting functions during\n pipeline development.\n \"\"\"\n return int(self.count_flag_reads(file_name, 512, paired_end))\n\n def samtools_view(self, file_name, param, postpend=\"\"):\n \"\"\"\n Run samtools view, with flexible parameters and post-processing.\n\n This is used internally to implement the various count_reads functions.\n\n :param str file_name: file_name\n :param str param: String of parameters to pass to samtools view\n :param str postpend: String to append to the samtools command;\n useful to add cut, sort, wc operations to the samtools view output.\n \"\"\"\n cmd = \"{} view {} {} {}\".format(self.tools.samtools, param, file_name, postpend)\n # in python 3, check_output returns a byte string which causes issues.\n # with python 3.6 we could use argument: \"encoding='UTF-8'\"\"\n return subprocess.check_output(cmd, shell=True).decode().strip()\n\n def count_reads(self, file_name, paired_end):\n \"\"\"\n Count reads in a file.\n\n Paired-end reads count as 2 in this function.\n For paired-end reads, this function assumes that the reads are split\n into 2 files, so it divides line count by 2 instead of 4.\n This will thus give an incorrect result if your paired-end fastq files\n are in only a single file (you must divide by 2 again).\n\n :param str file_name: Name/path of file whose reads are to be counted.\n :param bool paired_end: Whether the file contains paired-end reads.\n \"\"\"\n\n _, ext = os.path.splitext(file_name)\n if not (is_sam_or_bam(file_name) or is_fastq(file_name)):\n # TODO: make this an exception and force caller to handle that\n # rather than relying on knowledge of possibility of negative value.\n return -1\n\n if is_sam_or_bam(file_name):\n param_text = \"-c\" if ext == \".bam\" else \"-c -S\"\n return self.samtools_view(file_name, param=param_text)\n else:\n num_lines = (\n self.count_lines_zip(file_name)\n if is_gzipped_fastq(file_name)\n else self.count_lines(file_name)\n )\n divisor = 2 if paired_end else 4\n return int(num_lines) / divisor\n\n def count_concordant(self, aligned_bam):\n \"\"\"\n Count only reads that \"aligned concordantly exactly 1 time.\"\n\n :param str aligned_bam: File for which to count mapped reads.\n \"\"\"\n cmd = self.tools.samtools + \" view \" + aligned_bam + \" | \"\n cmd += \"grep 'YT:Z:CP'\" + \" | uniq -u | wc -l | sed -E 's/^[[:space:]]+//'\"\n\n return subprocess.check_output(cmd, shell=True).decode().strip()\n\n def count_mapped_reads(self, file_name, paired_end):\n \"\"\"\n Mapped_reads are not in fastq format, so this one doesn't need to accommodate fastq,\n and therefore, doesn't require a paired-end parameter because it only uses samtools view.\n Therefore, it's ok that it has a default parameter, since this is discarded.\n\n :param str file_name: File for which to count mapped reads.\n :param bool paired_end: This parameter is ignored; samtools automatically correctly responds depending\n on the data in the bamfile. We leave the option here just for consistency, since all the other\n counting functions require the parameter. This makes it easier to swap counting functions during\n pipeline development.\n :return int: Either return code from samtools view command, or -1 to indicate an error state.\n \"\"\"\n if file_name.endswith(\"bam\"):\n return self.samtools_view(file_name, param=\"-c -F4\")\n if file_name.endswith(\"sam\"):\n return self.samtools_view(file_name, param=\"-c -F4 -S\")\n return -1\n\n def sam_conversions(self, sam_file, depth=True):\n \"\"\"\n Convert sam files to bam files, then sort and index them for later use.\n\n :param bool depth: also calculate coverage over each position\n \"\"\"\n cmd = (\n self.tools.samtools\n + \" view -bS \"\n + sam_file\n + \" > \"\n + sam_file.replace(\".sam\", \".bam\")\n + \"\\n\"\n )\n cmd += (\n self.tools.samtools\n + \" sort \"\n + sam_file.replace(\".sam\", \".bam\")\n + \" -o \"\n + sam_file.replace(\".sam\", \"_sorted.bam\")\n + \"\\n\"\n )\n cmd += (\n self.tools.samtools\n + \" index \"\n + sam_file.replace(\".sam\", \"_sorted.bam\")\n + \"\\n\"\n )\n if depth:\n cmd += (\n self.tools.samtools\n + \" depth \"\n + sam_file.replace(\".sam\", \"_sorted.bam\")\n + \" > \"\n + sam_file.replace(\".sam\", \"_sorted.depth\")\n + \"\\n\"\n )\n return cmd\n\n def bam_conversions(self, bam_file, depth=True):\n \"\"\"\n Sort and index bam files for later use.\n\n :param bool depth: also calculate coverage over each position\n \"\"\"\n cmd = (\n self.tools.samtools\n + \" view -h \"\n + bam_file\n + \" > \"\n + bam_file.replace(\".bam\", \".sam\")\n + \"\\n\"\n )\n cmd += (\n self.tools.samtools\n + \" sort \"\n + bam_file\n + \" -o \"\n + bam_file.replace(\".bam\", \"_sorted.bam\")\n + \"\\n\"\n )\n cmd += (\n self.tools.samtools\n + \" index \"\n + bam_file.replace(\".bam\", \"_sorted.bam\")\n + \"\\n\"\n )\n if depth:\n cmd += (\n self.tools.samtools\n + \" depth \"\n + bam_file.replace(\".bam\", \"_sorted.bam\")\n + \" > \"\n + bam_file.replace(\".bam\", \"_sorted.depth\")\n + \"\\n\"\n )\n return cmd\n\n def fastqc(self, file, output_dir):\n \"\"\"\n Create command to run fastqc on a FASTQ file\n\n :param str file: Path to file with sequencing reads\n :param str output_dir: Path to folder in which to place output\n :return str: Command with which to run fastqc\n \"\"\"\n # You can find the fastqc help with fastqc --help\n try:\n pm = self.pm\n except AttributeError:\n # Do nothing, this is just for path construction.\n pass\n else:\n if not os.path.isabs(output_dir) and pm is not None:\n output_dir = os.path.join(pm.outfolder, output_dir)\n self.make_sure_path_exists(output_dir)\n return \"{} --noextract --outdir {} {}\".format(\n self.tools.fastqc, output_dir, file\n )\n\n def fastqc_rename(self, input_bam, output_dir, sample_name):\n \"\"\"\n Create pair of commands to run fastqc and organize files.\n\n The first command returned is the one that actually runs fastqc when\n it's executed; the second moves the output files to the output\n folder for the sample indicated.\n\n :param str input_bam: Path to file for which to run fastqc.\n :param str output_dir: Path to folder in which fastqc output will be\n written, and within which the sample's output folder lives.\n :param str sample_name: Sample name, which determines subfolder within\n output_dir for the fastqc files.\n :return list[str]: Pair of commands, to run fastqc and then move the files to\n their intended destination based on sample name.\n \"\"\"\n cmds = list()\n initial = os.path.splitext(os.path.basename(input_bam))[0]\n cmd1 = self.fastqc(input_bam, output_dir)\n cmds.append(cmd1)\n cmd2 = \"if [[ ! -s {1}_fastqc.html ]]; then mv {0}_fastqc.html {1}_fastqc.html; mv {0}_fastqc.zip {1}_fastqc.zip; fi\".format(\n os.path.join(output_dir, initial), os.path.join(output_dir, sample_name)\n )\n cmds.append(cmd2)\n return cmds\n\n def samtools_index(self, bam_file):\n \"\"\"Index a bam file.\"\"\"\n cmd = self.tools.samtools + \" index {0}\".format(bam_file)\n return cmd\n\n def slurm_header(\n self,\n job_name,\n output,\n queue=\"shortq\",\n n_tasks=1,\n time=\"10:00:00\",\n cpus_per_task=8,\n mem_per_cpu=2000,\n nodes=1,\n user_mail=\"\",\n mail_type=\"end\",\n ):\n cmd = \"\"\" #!/bin/bash\n #SBATCH --partition={0}\n #SBATCH --ntasks={1}\n #SBATCH --time={2}\n\n #SBATCH --cpus-per-task={3}\n #SBATCH --mem-per-cpu={4}\n #SBATCH --nodes={5}\n\n #SBATCH --job-name={6}\n #SBATCH --output={7}\n\n #SBATCH --mail-type={8}\n #SBATCH --mail-user={9}\n\n # Start running the job\n hostname\n date\n\n \"\"\".format(\n queue,\n n_tasks,\n time,\n cpus_per_task,\n mem_per_cpu,\n nodes,\n job_name,\n output,\n mail_type,\n user_mail,\n )\n\n return cmd\n\n def slurm_footer(self):\n return \" date\"\n\n def slurm_submit_job(self, job_file):\n return os.system(\"sbatch %s\" % job_file)\n\n def remove_file(self, file_name):\n return \"rm {0}\".format(file_name)\n\n def move_file(self, old, new):\n return \"mv {0} {1}\".format(old, new)\n\n def preseq_curve(self, bam_file, output_prefix):\n return \"\"\"\n preseq c_curve -B -P -o {0}.yield.txt {1}\n \"\"\".format(\n output_prefix, bam_file\n )\n\n def preseq_extrapolate(self, bam_file, output_prefix):\n return \"\"\"\n preseq lc_extrap -v -B -P -e 1e+9 -o {0}.future_yield.txt {1}\n \"\"\".format(\n output_prefix, bam_file\n )\n\n def preseq_coverage(self, bam_file, output_prefix):\n return \"\"\"\n preseq gc_extrap -o {0}.future_coverage.txt {1}\n \"\"\".format(\n output_prefix, bam_file\n )\n\n def trimmomatic(\n self,\n input_fastq1,\n output_fastq1,\n cpus,\n adapters,\n log,\n input_fastq2=None,\n output_fastq1_unpaired=None,\n output_fastq2=None,\n output_fastq2_unpaired=None,\n ):\n PE = False if input_fastq2 is None else True\n pe = \"PE\" if PE else \"SE\"\n cmd = self.tools.java + \" -Xmx\" + self.pm.javamem\n cmd += \" -jar \" + self.tools.trimmomatic\n cmd += \" {0} -threads {1} -trimlog {2} {3}\".format(pe, cpus, log, input_fastq1)\n if PE:\n cmd += \" {0}\".format(input_fastq2)\n cmd += \" {0}\".format(output_fastq1)\n if PE:\n cmd += \" {0} {1} {2}\".format(\n output_fastq1_unpaired, output_fastq2, output_fastq2_unpaired\n )\n cmd += \" ILLUMINACLIP:{0}:1:40:15:8:true\".format(adapters)\n cmd += \" LEADING:3 TRAILING:3\"\n cmd += \" SLIDINGWINDOW:4:10\"\n cmd += \" MINLEN:36\"\n return cmd\n\n def skewer(\n self,\n input_fastq1,\n output_prefix,\n output_fastq1,\n log,\n cpus,\n adapters,\n input_fastq2=None,\n output_fastq2=None,\n ):\n \"\"\"\n Create commands with which to run skewer.\n\n :param str input_fastq1: Path to input (read 1) FASTQ file\n :param str output_prefix: Prefix for output FASTQ file names\n :param str output_fastq1: Path to (read 1) output FASTQ file\n :param str log: Path to file to which to write logging information\n :param int | str cpus: Number of processing cores to allow\n :param str adapters: Path to file with sequencing adapters\n :param str input_fastq2: Path to read 2 input FASTQ file\n :param str output_fastq2: Path to read 2 output FASTQ file\n :return list[str]: Sequence of commands to run to trim reads with\n skewer and rename files as desired.\n \"\"\"\n\n pe = input_fastq2 is not None\n mode = \"pe\" if pe else \"any\"\n cmds = list()\n cmd1 = self.tools.skewer + \" --quiet\"\n cmd1 += \" -f sanger\"\n cmd1 += \" -t {0}\".format(cpus)\n cmd1 += \" -m {0}\".format(mode)\n cmd1 += \" -x {0}\".format(adapters)\n cmd1 += \" -o {0}\".format(output_prefix)\n cmd1 += \" {0}\".format(input_fastq1)\n if input_fastq2 is None:\n cmds.append(cmd1)\n else:\n cmd1 += \" {0}\".format(input_fastq2)\n cmds.append(cmd1)\n if input_fastq2 is None:\n cmd2 = \"mv {0} {1}\".format(output_prefix + \"-trimmed.fastq\", output_fastq1)\n cmds.append(cmd2)\n else:\n cmd2 = \"mv {0} {1}\".format(\n output_prefix + \"-trimmed-pair1.fastq\", output_fastq1\n )\n cmds.append(cmd2)\n cmd3 = \"mv {0} {1}\".format(\n output_prefix + \"-trimmed-pair2.fastq\", output_fastq2\n )\n cmds.append(cmd3)\n cmd4 = \"mv {0} {1}\".format(output_prefix + \"-trimmed.log\", log)\n cmds.append(cmd4)\n return cmds\n\n def bowtie2_map(\n self,\n input_fastq1,\n output_bam,\n log,\n metrics,\n genome_index,\n max_insert,\n cpus,\n input_fastq2=None,\n ):\n # Admits 2000bp-long fragments (--maxins option)\n cmd = self.tools.bowtie2 + \" --very-sensitive --no-discordant -p {0}\".format(\n cpus\n )\n cmd += \" -x {0}\".format(genome_index)\n cmd += \" --met-file {0}\".format(metrics)\n if input_fastq2 is None:\n cmd += \" {0} \".format(input_fastq1)\n else:\n cmd += \" --maxins {0}\".format(max_insert)\n cmd += \" -1 {0}\".format(input_fastq1)\n cmd += \" -2 {0}\".format(input_fastq2)\n cmd += \" 2> {0} | samtools view -S -b - | samtools sort -o {1} -\".format(\n log, output_bam\n )\n return cmd\n\n def topHat_map(self, input_fastq, output_dir, genome, transcriptome, cpus):\n # TODO:\n # Allow paired input\n cmd = (\n self.tools.tophat\n + \" --GTF {0} --b2-L 15 --library-type fr-unstranded --mate-inner-dist 120\".format(\n transcriptome\n )\n )\n cmd += \" --max-multihits 100 --no-coverage-search\"\n cmd += \" --num-threads {0} --output-dir {1} {2} {3}\".format(\n cpus, output_dir, genome, input_fastq\n )\n return cmd\n\n def picard_mark_duplicates(self, input_bam, output_bam, metrics_file, temp_dir=\".\"):\n transient_file = re.sub(\"\\.bam$\", \"\", output_bam) + \".dups.nosort.bam\"\n output_bam = re.sub(\"\\.bam$\", \"\", output_bam)\n cmd1 = self.tools.java + \" -Xmx\" + self.pm.javamem\n cmd1 += \" -jar `which MarkDuplicates.jar`\"\n cmd1 += \" INPUT={0}\".format(input_bam)\n cmd1 += \" OUTPUT={0}\".format(transient_file)\n cmd1 += \" METRICS_FILE={0}\".format(metrics_file)\n cmd1 += \" VALIDATION_STRINGENCY=LENIENT\"\n cmd1 += \" TMP_DIR={0}\".format(temp_dir)\n # Sort bam file with marked duplicates\n cmd2 = self.tools.samtools + \" sort {0} {1}\".format(transient_file, output_bam)\n # Remove transient file\n cmd3 = \"if [[ -s {0} ]]; then rm {0}; fi\".format(transient_file)\n return [cmd1, cmd2, cmd3]\n\n def sambamba_remove_duplicates(self, input_bam, output_bam, cpus=16):\n cmd = self.tools.sambamba + \" markdup -t {0} -r {1} {2}\".format(\n cpus, input_bam, output_bam\n )\n return cmd\n\n def get_mitochondrial_reads(self, bam_file, output, cpus=4):\n \"\"\" \"\"\"\n tmp_bam = bam_file + \"tmp_rmMe\"\n cmd1 = self.tools.sambamba + \" index -t {0} {1}\".format(cpus, bam_file)\n cmd2 = (\n self.tools.sambamba\n + \" slice {0} chrM | {1} markdup -t 4 /dev/stdin {2} 2> {3}\".format(\n bam_file, self.tools.sambamba, tmp_bam, output\n )\n )\n cmd3 = \"rm {}\".format(tmp_bam)\n return [cmd1, cmd2, cmd3]\n\n def filter_reads(\n self, input_bam, output_bam, metrics_file, paired=False, cpus=16, Q=30\n ):\n \"\"\"\n Remove duplicates, filter for >Q, remove multiple mapping reads.\n For paired-end reads, keep only proper pairs.\n \"\"\"\n nodups = re.sub(\"\\.bam$\", \"\", output_bam) + \".nodups.nofilter.bam\"\n cmd1 = (\n self.tools.sambamba\n + \" markdup -t {0} -r --compression-level=0 {1} {2} 2> {3}\".format(\n cpus, input_bam, nodups, metrics_file\n )\n )\n cmd2 = self.tools.sambamba + \" view -t {0} -f bam --valid\".format(cpus)\n if paired:\n cmd2 += ' -F \"not (unmapped or mate_is_unmapped) and proper_pair'\n else:\n cmd2 += ' -F \"not unmapped'\n cmd2 += ' and not (secondary_alignment or supplementary) and mapping_quality >= {0}\"'.format(\n Q\n )\n cmd2 += \" {0} |\".format(nodups)\n cmd2 += self.tools.sambamba + \" sort -t {0} /dev/stdin -o {1}\".format(\n cpus, output_bam\n )\n cmd3 = \"if [[ -s {0} ]]; then rm {0}; fi\".format(nodups)\n cmd4 = \"if [[ -s {0} ]]; then rm {0}; fi\".format(nodups + \".bai\")\n return [cmd1, cmd2, cmd3, cmd4]\n\n def shift_reads(self, input_bam, genome, output_bam):\n # output_bam = re.sub(\"\\.bam$\", \"\", output_bam)\n cmd = self.tools.samtools + \" view -h {0} |\".format(input_bam)\n cmd += \" shift_reads.py {0} |\".format(genome)\n cmd += \" \" + self.tools.samtools + \" view -S -b - |\"\n cmd += \" \" + self.tools.samtools + \" sort -o {0} -\".format(output_bam)\n return cmd\n\n def sort_index_bam(self, input_bam, output_bam):\n tmp_bam = re.sub(\"\\.bam\", \".sorted\", input_bam)\n cmd1 = self.tools.samtools + \" sort {0} {1}\".format(input_bam, tmp_bam)\n cmd2 = \"mv {0}.bam {1}\".format(tmp_bam, output_bam)\n cmd3 = self.tools.samtools + \" index {0}\".format(output_bam)\n return [cmd1, cmd2, cmd3]\n\n def index_bam(self, input_bam):\n cmd = self.tools.samtools + \" index {0}\".format(input_bam)\n return cmd\n\n def run_spp(self, input_bam, output, plot, cpus):\n \"\"\"\n Run the SPP read peak analysis tool.\n\n :param str input_bam: Path to reads file\n :param str output: Path to output file\n :param str plot: Path to plot file\n :param int cpus: Number of processors to use\n :return str: Command with which to run SPP\n \"\"\"\n base = \"{} {} -rf -savp\".format(self.tools.Rscript, self.tools.spp)\n cmd = base + \" -savp={} -s=0:5:500 -c={} -out={} -p={}\".format(\n plot, input_bam, output, cpus\n )\n return cmd\n\n def get_fragment_sizes(self, bam_file):\n try:\n import numpy as np\n import pysam\n except:\n return\n frag_sizes = list()\n bam = pysam.Samfile(bam_file, \"rb\")\n for read in bam:\n if bam.getrname(read.tid) != \"chrM\" and read.tlen < 1500:\n frag_sizes.append(read.tlen)\n bam.close()\n return np.array(frag_sizes)\n\n def plot_atacseq_insert_sizes(\n self, bam, plot, output_csv, max_insert=1500, smallest_insert=30\n ):\n \"\"\"\n Heavy inspiration from here:\n https://github.com/dbrg77/ATAC/blob/master/ATAC_seq_read_length_curve_fitting.ipynb\n \"\"\"\n try:\n import matplotlib\n import matplotlib.mlab as mlab\n import numpy as np\n import pysam\n from scipy.integrate import simps\n from scipy.optimize import curve_fit\n\n matplotlib.use(\"Agg\")\n import matplotlib.pyplot as plt\n except:\n print(\"Necessary Python modules couldn't be loaded.\")\n return\n\n try:\n import seaborn as sns\n\n sns.set_style(\"whitegrid\")\n except:\n pass\n\n def get_fragment_sizes(bam, max_insert=1500):\n frag_sizes = list()\n\n bam = pysam.Samfile(bam, \"rb\")\n\n for i, read in enumerate(bam):\n if read.tlen < max_insert:\n frag_sizes.append(read.tlen)\n bam.close()\n\n return np.array(frag_sizes)\n\n def mixture_function(x, *p):\n \"\"\"\n Mixture function to model four gaussian (nucleosomal)\n and one exponential (nucleosome-free) distributions.\n \"\"\"\n m1, s1, w1, m2, s2, w2, m3, s3, w3, m4, s4, w4, q, r = p\n nfr = expo(x, 2.9e-02, 2.8e-02)\n nfr[:smallest_insert] = 0\n\n return (\n mlab.normpdf(x, m1, s1) * w1\n + mlab.normpdf(x, m2, s2) * w2\n + mlab.normpdf(x, m3, s3) * w3\n + mlab.normpdf(x, m4, s4) * w4\n + nfr\n )\n\n def expo(x, q, r):\n \"\"\"\n Exponential function.\n \"\"\"\n return q * np.exp(-r * x)\n\n # get fragment sizes\n frag_sizes = get_fragment_sizes(bam)\n\n # bin\n numBins = np.linspace(0, max_insert, max_insert + 1)\n y, scatter_x = np.histogram(frag_sizes, numBins, density=1)\n # get the mid-point of each bin\n x = (scatter_x[:-1] + scatter_x[1:]) / 2\n\n # Parameters are empirical, need to check\n paramGuess = [\n 200,\n 50,\n 0.7, # gaussians\n 400,\n 50,\n 0.15,\n 600,\n 50,\n 0.1,\n 800,\n 55,\n 0.045,\n 2.9e-02,\n 2.8e-02, # exponential\n ]\n\n try:\n popt3, pcov3 = curve_fit(\n mixture_function,\n x[smallest_insert:],\n y[smallest_insert:],\n p0=paramGuess,\n maxfev=100000,\n )\n except:\n print(\"Nucleosomal fit could not be found.\")\n return\n\n m1, s1, w1, m2, s2, w2, m3, s3, w3, m4, s4, w4, q, r = popt3\n\n # Plot\n plt.figure(figsize=(12, 12))\n\n # Plot distribution\n plt.hist(frag_sizes, numBins, histtype=\"step\", ec=\"k\", normed=1, alpha=0.5)\n\n # Plot nucleosomal fits\n plt.plot(x, mlab.normpdf(x, m1, s1) * w1, \"r-\", lw=1.5, label=\"1st nucleosome\")\n plt.plot(x, mlab.normpdf(x, m2, s2) * w2, \"g-\", lw=1.5, label=\"2nd nucleosome\")\n plt.plot(x, mlab.normpdf(x, m3, s3) * w3, \"b-\", lw=1.5, label=\"3rd nucleosome\")\n plt.plot(x, mlab.normpdf(x, m4, s4) * w4, \"c-\", lw=1.5, label=\"4th nucleosome\")\n\n # Plot nucleosome-free fit\n nfr = expo(x, 2.9e-02, 2.8e-02)\n nfr[:smallest_insert] = 0\n plt.plot(x, nfr, \"k-\", lw=1.5, label=\"nucleosome-free\")\n\n # Plot sum of fits\n ys = mixture_function(x, *popt3)\n plt.plot(x, ys, \"k--\", lw=3.5, label=\"fit sum\")\n\n plt.legend()\n plt.xlabel(\"Fragment size (bp)\")\n plt.ylabel(\"Density\")\n plt.savefig(plot, bbox_inches=\"tight\")\n\n # Integrate curves and get areas under curve\n areas = [\n [\"fraction\", \"area under curve\", \"max density\"],\n [\"Nucleosome-free fragments\", simps(nfr), max(nfr)],\n [\n \"1st nucleosome\",\n simps(mlab.normpdf(x, m1, s1) * w1),\n max(mlab.normpdf(x, m1, s1) * w1),\n ],\n [\n \"2nd nucleosome\",\n simps(mlab.normpdf(x, m2, s2) * w1),\n max(mlab.normpdf(x, m2, s2) * w2),\n ],\n [\n \"3rd nucleosome\",\n simps(mlab.normpdf(x, m3, s3) * w1),\n max(mlab.normpdf(x, m3, s3) * w3),\n ],\n [\n \"4th nucleosome\",\n simps(mlab.normpdf(x, m4, s4) * w1),\n max(mlab.normpdf(x, m4, s4) * w4),\n ],\n ]\n\n try:\n import csv\n\n with open(output_csv, \"w\") as f:\n writer = csv.writer(f)\n writer.writerows(areas)\n except:\n pass\n\n # TODO: parameterize in terms of normalization factor.\n def bam_to_bigwig(\n self,\n input_bam,\n output_bigwig,\n genome_sizes,\n genome,\n tagmented=False,\n normalize=False,\n norm_factor=1000,\n ):\n \"\"\"\n Convert a BAM file to a bigWig file.\n\n :param str input_bam: path to BAM file to convert\n :param str output_bigwig: path to which to write file in bigwig format\n :param str genome_sizes: path to file with chromosome size information\n :param str genome: name of genomic assembly\n :param bool tagmented: flag related to read-generating protocol\n :param bool normalize: whether to normalize coverage\n :param int norm_factor: number of bases to use for normalization\n :return list[str]: sequence of commands to execute\n \"\"\"\n # TODO:\n # addjust fragment length dependent on read size and real fragment size\n # (right now it asssumes 50bp reads with 180bp fragments)\n cmds = list()\n transient_file = os.path.abspath(re.sub(\"\\.bigWig\", \"\", output_bigwig))\n cmd1 = self.tools.bedtools + \" bamtobed -i {0} |\".format(input_bam)\n if not tagmented:\n cmd1 += (\n \" \"\n + self.tools.bedtools\n + \" slop -i stdin -g {0} -s -l 0 -r 130 |\".format(genome_sizes)\n )\n cmd1 += \" fix_bedfile_genome_boundaries.py {0} |\".format(genome)\n cmd1 += (\n \" \"\n + self.tools.genomeCoverageBed\n + \" {0}-bg -g {1} -i stdin > {2}.cov\".format(\n \"-5 \" if tagmented else \"\", genome_sizes, transient_file\n )\n )\n cmds.append(cmd1)\n if normalize:\n cmds.append(\n \"\"\"awk 'NR==FNR{{sum+= $4; next}}{{ $4 = ($4 / sum) * {1}; print}}' {0}.cov {0}.cov | sort -k1,1 -k2,2n > {0}.normalized.cov\"\"\".format(\n transient_file, norm_factor\n )\n )\n cmds.append(\n self.tools.bedGraphToBigWig\n + \" {0}{1}.cov {2} {3}\".format(\n transient_file,\n \".normalized\" if normalize else \"\",\n genome_sizes,\n output_bigwig,\n )\n )\n # remove tmp files\n cmds.append(\"if [[ -s {0}.cov ]]; then rm {0}.cov; fi\".format(transient_file))\n if normalize:\n cmds.append(\n \"if [[ -s {0}.normalized.cov ]]; then rm {0}.normalized.cov; fi\".format(\n transient_file\n )\n )\n cmds.append(\"chmod 755 {0}\".format(output_bigwig))\n return cmds\n\n def add_track_to_hub(\n self, sample_name, track_url, track_hub, colour, five_prime=\"\"\n ):\n cmd1 = (\n \"\"\"echo \"track type=bigWig name='{0} {1}' description='{0} {1}'\"\"\".format(\n sample_name, five_prime\n )\n )\n cmd1 += \"\"\" height=32 visibility=full maxHeightPixels=32:32:25 bigDataUrl={0} color={1}\" >> {2}\"\"\".format(\n track_url, colour, track_hub\n )\n cmd2 = \"chmod 755 {0}\".format(track_hub)\n return [cmd1, cmd2]\n\n def link_to_track_hub(self, track_hub_url, file_name, genome):\n import textwrap\n\n db = \"org\" if genome == \"hg19\" else \"db\" # different database call for human\n genome = \"human\" if genome == \"hg19\" else genome # change hg19 to human\n html = \"\"\"\n \n \n \n \n \n \"\"\".format(\n track_hub_url=track_hub_url, genome=genome, db=db\n )\n with open(file_name, \"w\") as handle:\n handle.write(textwrap.dedent(html))\n\n def htseq_count(self, input_bam, gtf, output):\n sam = input_bam.replace(\"bam\", \"sam\")\n cmd1 = \"samtools view {0} > {1}\".format(input_bam, sam)\n cmd2 = (\n \"htseq-count -f sam -t exon -i transcript_id -m union {0} {1} > {2}\".format(\n sam, gtf, output\n )\n )\n cmd3 = \"rm {0}\".format(sam)\n return [cmd1, cmd2, cmd3]\n\n def kallisto(\n self,\n input_fastq,\n output_dir,\n output_bam,\n transcriptome_index,\n cpus,\n input_fastq2=None,\n size=180,\n b=200,\n ):\n cmd1 = (\n self.tools.kallisto\n + \" quant --bias --pseudobam -b {0} -l {1} -i {2} -o {3} -t {4}\".format(\n b, size, transcriptome_index, output_dir, cpus\n )\n )\n if input_fastq2 is None:\n cmd1 += \" --single {0}\".format(input_fastq)\n else:\n cmd1 += \" {0} {1}\".format(input_fastq, input_fastq2)\n cmd1 += \" | \" + self.tools.samtools + \" view -Sb - > {0}\".format(output_bam)\n cmd2 = self.tools.kallisto + \" h5dump -o {0} {0}/abundance.h5\".format(\n output_dir\n )\n return [cmd1, cmd2]\n\n def genome_wide_coverage(self, input_bam, genome_windows, output):\n cmd = self.tools.bedtools + \" coverage -counts -abam {0} -b {1} > {2}\".format(\n input_bam, genome_windows, output\n )\n return cmd\n\n def calc_frip(self, input_bam, input_bed, threads=4):\n \"\"\"\n Calculate fraction of reads in peaks.\n\n A file of with a pool of sequencing reads and a file with peak call\n regions define the operation that will be performed. Thread count\n for samtools can be specified as well.\n\n :param str input_bam: sequencing reads file\n :param str input_bed: file with called peak regions\n :param int threads: number of threads samtools may use\n :return float: fraction of reads in peaks defined in given peaks file\n \"\"\"\n cmd = self.simple_frip(input_bam, input_bed, threads)\n return subprocess.check_output(cmd.split(\" \"), shell=True).decode().strip()\n\n def simple_frip(self, input_bam, input_bed, threads=4):\n cmd = \"{} view\".format(self.tools.samtools)\n cmd += \" -@ {} -c -L {}\".format(threads, input_bed)\n cmd += \" \" + input_bam\n return cmd\n\n def calculate_frip(self, input_bam, input_bed, output, cpus=4):\n cmd = self.tools.sambamba + \" depth region -t {0}\".format(cpus)\n cmd += \" -L {0}\".format(input_bed)\n cmd += \" {0}\".format(input_bam)\n cmd += \" | awk '{{sum+=$5}} END {{print sum}}' > {0}\".format(output)\n return cmd\n\n def macs2_call_peaks(\n self,\n treatment_bams,\n output_dir,\n sample_name,\n genome,\n control_bams=None,\n broad=False,\n paired=False,\n pvalue=None,\n qvalue=None,\n include_significance=None,\n ):\n \"\"\"\n Use MACS2 to call peaks.\n\n :param str | Iterable[str] treatment_bams: Paths to files with data to\n regard as treatment.\n :param str output_dir: Path to output folder.\n :param str sample_name: Name for the sample involved.\n :param str genome: Name of the genome assembly to use.\n :param str | Iterable[str] control_bams: Paths to files with data to\n regard as control\n :param bool broad: Whether to do broad peak calling.\n :param bool paired: Whether reads are paired-end\n :param float | NoneType pvalue: Statistical significance measure to\n pass as --pvalue to peak calling with MACS\n :param float | NoneType qvalue: Statistical significance measure to\n pass as --qvalue to peak calling with MACS\n :param bool | NoneType include_significance: Whether to pass a\n statistical significance argument to peak calling with MACS; if\n omitted, this will be True if the peak calling is broad or if\n either p-value or q-value is specified; default significance\n specification is a p-value of 0.001 if a significance is to be\n specified but no value is provided for p-value or q-value.\n :return str: Command to run.\n \"\"\"\n sizes = {\n \"hg38\": 2.7e9,\n \"hg19\": 2.7e9,\n \"mm10\": 1.87e9,\n \"dr7\": 1.412e9,\n \"mm9\": 1.87e9,\n }\n\n # Whether to specify to MACS2 a value for statistical significance\n # can be either directly indicated, but if not, it's determined by\n # whether the mark is associated with broad peaks. By default, we\n # specify a significance value to MACS2 for a mark associated with a\n # broad peak.\n if include_significance is None:\n include_significance = broad\n\n cmd = self.tools.macs2 + \" callpeak -t {0}\".format(\n treatment_bams if type(treatment_bams) is str else \" \".join(treatment_bams)\n )\n\n if control_bams is not None:\n cmd += \" -c {0}\".format(\n control_bams if type(control_bams) is str else \" \".join(control_bams)\n )\n\n if paired:\n cmd += \" -f BAMPE \"\n\n # Additional settings based on whether the marks is associated with\n # broad peaks\n if broad:\n cmd += \" --broad --nomodel --extsize 73\"\n else:\n cmd += \" --fix-bimodal --extsize 180 --bw 200\"\n\n if include_significance:\n # Allow significance specification via either p- or q-value,\n # giving preference to q-value if both are provided but falling\n # back on a default p-value if neither is provided but inclusion\n # of statistical significance measure is desired.\n if qvalue is not None:\n cmd += \" --qvalue {}\".format(qvalue)\n else:\n cmd += \" --pvalue {}\".format(pvalue or 0.00001)\n cmd += \" -g {0} -n {1} --outdir {2}\".format(\n sizes[genome], sample_name, output_dir\n )\n\n return cmd\n\n def macs2_call_peaks_atacseq(self, treatment_bam, output_dir, sample_name, genome):\n genome_sizes = {\n \"hg38\": 2.7e9,\n \"hg19\": 2.7e9,\n \"mm10\": 1.87e9,\n \"dr7\": 1.412e9,\n \"mm9\": 1.87e9,\n }\n cmd = self.tools.macs2 + \" callpeak -t {0}\".format(treatment_bam)\n cmd += \" --nomodel --extsize 147 -g {0} -n {1} --outdir {2}\".format(\n genome_sizes[genome], sample_name, output_dir\n )\n return cmd\n\n def macs2_plot_model(self, r_peak_model_file, sample_name, output_dir):\n # run macs r script\n cmd1 = \"{} {}\".format(self.tools.Rscript, r_peak_model_file)\n # move output plot to sample dir\n cmd2 = \"mv {0}/{1}_model.pdf {2}/{1}_model.pdf\".format(\n os.getcwd(), sample_name, output_dir\n )\n return [cmd1, cmd2]\n\n def spp_call_peaks(\n self,\n treatment_bam,\n control_bam,\n treatment_name,\n control_name,\n output_dir,\n broad,\n cpus,\n qvalue=None,\n ):\n \"\"\"\n Build command for R script to call peaks with SPP.\n\n :param str treatment_bam: Path to file with data for treatment sample.\n :param str control_bam: Path to file with data for control sample.\n :param str treatment_name: Name for the treatment sample.\n :param str control_name: Name for the control sample.\n :param str output_dir: Path to folder for output.\n :param str | bool broad: Whether to specify broad peak calling mode.\n :param int cpus: Number of cores the script may use.\n :param float qvalue: FDR, as decimal value\n :return str: Command to run.\n \"\"\"\n broad = \"TRUE\" if broad else \"FALSE\"\n cmd = (\n self.tools.Rscript\n + \" `which spp_peak_calling.R` {0} {1} {2} {3} {4} {5} {6}\".format(\n treatment_bam,\n control_bam,\n treatment_name,\n control_name,\n broad,\n cpus,\n output_dir,\n )\n )\n if qvalue is not None:\n cmd += \" {}\".format(qvalue)\n return cmd\n\n def bam_to_bed(self, input_bam, output_bed):\n cmd = self.tools.bedtools + \" bamtobed -i {0} > {1}\".format(\n input_bam, output_bed\n )\n return cmd\n\n def zinba_call_peaks(self, treatment_bed, control_bed, cpus, tagmented=False):\n fragmentLength = 80 if tagmented else 180\n cmd = self.tools.Rscript + \" `which zinba.R` -l {0} -t {1} -c {2}\".format(\n fragmentLength, treatment_bed, control_bed\n )\n return cmd\n\n def filter_peaks_mappability(self, peaks, alignability, filtered_peaks):\n cmd = self.tools.bedtools + \" intersect -wa -u -f 1\"\n cmd += \" -a {0} -b {1} > {2} \".format(peaks, alignability, filtered_peaks)\n return cmd\n\n def homer_find_motifs(\n self,\n peak_file,\n genome,\n output_dir,\n size=150,\n length=\"8,10,12,14,16\",\n n_motifs=12,\n ):\n cmd = \"findMotifsGenome.pl {0} {1} {2}\".format(peak_file, genome, output_dir)\n cmd += \" -mask -size {0} -len {1} -S {2}\".format(size, length, n_motifs)\n return cmd\n\n def homer_annotate_pPeaks(self, peak_file, genome, motif_file, output_bed):\n cmd = \"annotatePeaks.pl {0} {1} -mask -mscore -m {2} |\".format(\n peak_file, genome, motif_file\n )\n cmd += \"tail -n +2 | cut -f 1,5,22 > {3}\".format(output_bed)\n return cmd\n\n def center_peaks_on_motifs(\n self, peak_file, genome, window_width, motif_file, output_bed\n ):\n cmd = \"annotatePeaks.pl {0} {1} -size {2} -center {3} |\".format(\n peak_file, genome, window_width, motif_file\n )\n cmd += \" awk -v OFS='\\t' '{print $2, $3, $4, $1, $6, $5}' |\"\n cmd += \"\"\" awk -v OFS='\\t' -F '\\t' '{ gsub(\"0\", \"+\", $6) ; gsub(\"1\", \"-\", $6) ; print }' |\"\"\"\n cmd += \" fix_bedfile_genome_boundaries.py {0} | sortBed > {1}\".format(\n genome, output_bed\n )\n return cmd\n\n def get_read_type(self, bam_file, n=10):\n \"\"\"\n Gets the read type (single, paired) and length of bam file.\n :param str bam_file: Bam file to determine read attributes.\n :param int n: Number of lines to read from bam file.\n :return str, int: tuple of read type and read length\n \"\"\"\n\n from collections.abc import Counter\n\n try:\n p = subprocess.Popen(\n [self.tools.samtools, \"view\", bam_file], stdout=subprocess.PIPE\n )\n # Count paired alignments\n paired = 0\n read_length = Counter()\n while n > 0:\n line = p.stdout.next().split(\"\\t\")\n flag = int(line[1])\n read_length[len(line[9])] += 1\n if 1 & flag: # check decimal flag contains 1 (paired)\n paired += 1\n n -= 1\n p.kill()\n except IOError(\"Cannot read provided bam file.\") as e:\n raise e\n # Get most abundant read read_length\n read_length = sorted(read_length)[-1]\n # If at least half is paired, return True\n if paired > (n / 2.0):\n return \"PE\", read_length\n else:\n return \"SE\", read_length\n\n def parse_bowtie_stats(self, stats_file):\n \"\"\"\n Parses Bowtie2 stats file, returns series with values.\n :param str stats_file: Bowtie2 output file with alignment statistics.\n \"\"\"\n import pandas as pd\n\n stats = pd.Series(\n index=[\n \"readCount\",\n \"unpaired\",\n \"unaligned\",\n \"unique\",\n \"multiple\",\n \"alignmentRate\",\n ]\n )\n try:\n with open(stats_file) as handle:\n content = handle.readlines() # list of strings per line\n except:\n return stats\n # total reads\n try:\n line = [\n i for i in range(len(content)) if \" reads; of these:\" in content[i]\n ][0]\n stats[\"readCount\"] = re.sub(\"\\D.*\", \"\", content[line])\n if 7 > len(content) > 2:\n line = [\n i\n for i in range(len(content))\n if \"were unpaired; of these:\" in content[i]\n ][0]\n stats[\"unpaired\"] = re.sub(\"\\D\", \"\", re.sub(\"\\(.*\", \"\", content[line]))\n else:\n line = [\n i\n for i in range(len(content))\n if \"were paired; of these:\" in content[i]\n ][0]\n stats[\"unpaired\"] = stats[\"readCount\"] - int(\n re.sub(\"\\D\", \"\", re.sub(\"\\(.*\", \"\", content[line]))\n )\n line = [i for i in range(len(content)) if \"aligned 0 times\" in content[i]][\n 0\n ]\n stats[\"unaligned\"] = re.sub(\"\\D\", \"\", re.sub(\"\\(.*\", \"\", content[line]))\n line = [\n i for i in range(len(content)) if \"aligned exactly 1 time\" in content[i]\n ][0]\n stats[\"unique\"] = re.sub(\"\\D\", \"\", re.sub(\"\\(.*\", \"\", content[line]))\n line = [i for i in range(len(content)) if \"aligned >1 times\" in content[i]][\n 0\n ]\n stats[\"multiple\"] = re.sub(\"\\D\", \"\", re.sub(\"\\(.*\", \"\", content[line]))\n line = [\n i for i in range(len(content)) if \"overall alignment rate\" in content[i]\n ][0]\n stats[\"alignmentRate\"] = re.sub(\"\\%.*\", \"\", content[line]).strip()\n except IndexError:\n pass\n return stats\n\n def parse_duplicate_stats(self, stats_file):\n \"\"\"\n Parses sambamba markdup output, returns series with values.\n\n :param str stats_file: sambamba output file with duplicate statistics.\n \"\"\"\n import pandas as pd\n\n series = pd.Series()\n try:\n with open(stats_file) as handle:\n content = handle.readlines() # list of strings per line\n except:\n return series\n try:\n line = [\n i\n for i in range(len(content))\n if \"single ends (among them \" in content[i]\n ][0]\n series[\"single-ends\"] = re.sub(\"\\D\", \"\", re.sub(\"\\(.*\", \"\", content[line]))\n line = [\n i\n for i in range(len(content))\n if \" end pairs... done in \" in content[i]\n ][0]\n series[\"paired-ends\"] = re.sub(\n \"\\D\", \"\", re.sub(\"\\.\\.\\..*\", \"\", content[line])\n )\n line = [\n i\n for i in range(len(content))\n if \" duplicates, sorting the list... done in \" in content[i]\n ][0]\n series[\"duplicates\"] = re.sub(\n \"\\D\", \"\", re.sub(\"\\.\\.\\..*\", \"\", content[line])\n )\n except IndexError:\n pass\n return series\n\n def parse_qc(self, qc_file):\n \"\"\"\n Parse phantompeakqualtools (spp) QC table and return quality metrics.\n\n :param str qc_file: Path to phantompeakqualtools output file, which\n contains sample quality measurements.\n \"\"\"\n import pandas as pd\n\n series = pd.Series()\n try:\n with open(qc_file) as handle:\n line = (\n handle.readlines()[0].strip().split(\"\\t\")\n ) # list of strings per line\n series[\"NSC\"] = line[-3]\n series[\"RSC\"] = line[-2]\n series[\"qualityTag\"] = line[-1]\n except:\n pass\n return series\n\n def get_peak_number(self, sample):\n \"\"\"\n Counts number of peaks from a sample's peak file.\n\n :param pipelines.Sample sample: Sample object with \"peaks\" attribute.\n \"\"\"\n proc = subprocess.Popen([\"wc\", \"-l\", sample.peaks], stdout=subprocess.PIPE)\n out, err = proc.communicate()\n sample[\"peakNumber\"] = re.sub(\"\\D.*\", \"\", out)\n return sample\n\n def get_frip(self, sample):\n \"\"\"\n Calculates the fraction of reads in peaks for a given sample.\n\n :param pipelines.Sample sample: Sample object with \"peaks\" attribute.\n \"\"\"\n import pandas as pd\n\n with open(sample.frip, \"r\") as handle:\n content = handle.readlines()\n reads_in_peaks = int(re.sub(\"\\D\", \"\", content[0]))\n mapped_reads = sample[\"readCount\"] - sample[\"unaligned\"]\n return pd.Series(reads_in_peaks / mapped_reads, index=\"FRiP\")\n","repo_name":"databio/pypiper","sub_path":"pypiper/ngstk.py","file_name":"ngstk.py","file_ext":"py","file_size_in_byte":82806,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"61"}
+{"seq_id":"30639480944","text":"from flask import Blueprint\nfrom flask_restful import Api\n\nfrom eproc.resources.vendor.vendor import (\n VendorDetailResource,\n VendorResource\n)\n\nvendor_blueprint = Blueprint(\"vendor_blueprint\", __name__, url_prefix=\"/vendor\")\n\nvendor_api = Api(vendor_blueprint)\n\nvendor_api.add_resource(VendorResource, \"\")\nvendor_api.add_resource(VendorDetailResource, \"/details\")\n","repo_name":"keyinvoker/svc-procurement","sub_path":"eproc/blueprints/vendor.py","file_name":"vendor.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40921653554","text":"#!/usr/bin/python\n#\n# Practice Python Exercise #5\n# https://www.practicepython.org/exercise/2014/03/05/05-list-overlap.html\n# New Edit, for the sake of GIT / edit 1\n# Take two lists, say for example these two:\na = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]\nb = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]\nc = []\n\n# and write a program that returns a list that contains only the elements that are \n# common between the lists (without duplicates). Make sure your program works on two\n# lists of different sizes.\n# Extras:\n# ** Randomly generate two lists to test this\n# ** Write this in one line of Python\nprint (\"Welcome to exercise 5: List Overlaps.\")\nprint (\"First iteration is with predefined lists called 'a' and 'b':\")\nif len(a) >= len(b):\n for i in range(len(b)):\n if b[i] in a:\n if b[i] not in c: # Have to make sure we aren't duplicating a number that is already in our c list.\n c.append(b[i])\nelse:\n for i in range(len(a)):\n if a[i] in b:\n if a[i] not in c: # Have to make sure we aren't duplicating a number that is already in our c list.\n c.append(a[i])\n\n# print(set(c)) # Probably cheaty to use a set to print only the unique values\nprint (\"List A:\",a)\nprint (\"List B:\",b)\nprint (\"Overlaps:\",c)\n\n# Generate two lists of a random length, with random numbers in it\n# and print a list that has the overlaps between the two lists.\n\n#Create 3 empty lists\nx = []\ny = []\nz = []\n\nimport random # Needed for random numbers\n\ndef gen_r_list(stop, start=0): # Function to generate a list of varying sizes, composed of random numbers 0-10. \n iter=start\n while iter <= stop:\n yield random.randint(0,10)\n iter += 1\n\nsize1 = random.randint(5,15) # Get a random size for the first list x[]\nsize2 = random.randint(5,15) # Get a random size for the second list y[]\nwhile size2 == size1: # Make sure the second list, y[], is not equal in size to x[]\n size2 = random.randint(5,15)\n print (size1, size2)\n\nx = list(gen_r_list(size1))\ny = list(gen_r_list(size2))\n\n# Now that we've created both lists, lets create a list of overlapping values\n\nif len(x) >= len(y):\n for i in range(len(y)):\n if y[i] in x:\n if y[i] not in z: # Have to make sure we aren't duplicating a number that is already in our z list.\n z.append(y[i])\nelse:\n for i in range(len(x)):\n if x[i] in y:\n if x[i] not in z: # Have to make sure we aren't duplicating a number that is already in our z list.\n z.append(x[i])\n\nprint(\"Challenge #2: Randomly generate two lists to test non-duplicated overlaps between lists\")\nprint (\"List X: \",x,\"size:\",int(size1))\nprint (\"List Y: \",y,\"size:\",int(size2))\nprint (\"Overlaps: \",sorted(z)) # If you want to use z.sort() here you have to do z.sort() on a given line by itself, and then print it. You can't do print(z.sort()). (Why?)\n","repo_name":"dpalmero1971/python_exercises","sub_path":"ex05.py","file_name":"ex05.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6295263267","text":"from flask import Flask, render_template, flash, url_for, logging, request, redirect, session, jsonify, make_response\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import desc\nimport json\nfrom datetime import datetime\nfrom functools import wraps\n\napp = Flask(__name__)\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///school.db'\napp.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\ndb = SQLAlchemy(app)\n\n\nclass Users(db.Model):\n id = db.Column(db.Integer, primary_key=True)\n username = db.Column(db.String(50), nullable=False)\n email = db.Column(db.String(50), nullable=False)\n password = db.Column(db.String(50), nullable=False)\n role = db.Column(db.String(20), nullable=False)\n # created_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)\n\n def __repr__(self):\n return '{\"id\":\"'+str(self.id) + '\", \"username\":\"' + str(self.username) + '\", \"email\":\"'+str(self.email)+'\",'+ '\"role\":\"'+str(self.role)+'\"}'\n\n\n# Check if is admin\ndef is_admin(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if session['role'] == 'admin':\n return f(*args, **kwargs)\n else:\n return redirect(url_for('login'))\n return wrap\n\n# Check if user logged in\n\n\ndef is_logged_in(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n return f(*args, **kwargs)\n else:\n return redirect(url_for('login'))\n return wrap\n\n\n@app.route('/')\ndef index():\n\n return render_template('index.html')\n\n\n@app.route('/admin')\n@is_logged_in\n@is_admin\ndef admin():\n all_users = Users.query.order_by(desc(Users.id)).all()\n return render_template('admin.html', users=all_users)\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n\n if request.method == 'POST':\n email = request.form['email']\n password = request.form['password']\n user = Users.query.filter_by(\n password=password,\n email=email\n ).first()\n if user:\n session['logged_in'] = True\n session['username'] = user.username\n session['role'] = user.role\n session['user_id'] = user.id\n if session['role'] == 'admin':\n return redirect(url_for('admin'))\n else:\n return render_template('dashboard.html', user=user)\n\n else:\n msg = 'Invalid Login'\n return render_template('login.html', msg=msg)\n else:\n return render_template('login.html')\n\n\n@app.route('/register', methods=['POST', 'GET'])\n@app.route('/add-person', methods=['POST', 'GET'])\ndef register():\n\n if request.method == 'POST':\n username = request.form['username']\n email = request.form['email']\n password = request.form['password']\n role = request.form['role']\n new_user = Users(\n username=username,\n email=email,\n password=password,\n role=role\n )\n db.session.add(new_user)\n db.session.commit()\n if request.form['redirect'] == 'admin':\n return redirect(url_for('admin'))\n else:\n return redirect('/login')\n else:\n return render_template('register.html')\n\n\n@app.route('/user/delete/')\ndef delete_user(id):\n user = Users.query.get_or_404(id)\n db.session.delete(user)\n db.session.commit()\n return redirect(url_for('admin'))\n\n\n@app.route('/user/get/')\ndef get_user(id):\n user = Users.query.get_or_404(id)\n return user\n\n\n@app.route('/search', methods=['GET', 'POST'])\ndef search():\n\n results = []\n if request.method == 'POST':\n search = request.form['search']\n if search != '':\n results = Users.query.filter(Users.username.like(search)).all()\n else:\n results = Users.query.order_by(desc(Users.id)).all()\n\n return render_template('admin.html', users=results)\n\n\n@app.route('/profile/update/', methods=['GET', 'POST'])\ndef profile_edit(id):\n\n user = Users.query.get_or_404(id)\n\n if request.method == 'POST':\n user.username = request.form['username']\n user.email = request.form['email']\n user.password = request.form['password']\n db.session.commit()\n\n return redirect(url_for('dashboard'))\n\n\n@app.route('/dashboard')\n@is_logged_in\ndef dashboard():\n user_id = session['user_id']\n user = Users.query.get_or_404(user_id)\n return render_template('dashboard.html', user=user)\n\n# Logout\n@app.route('/logout')\n@is_logged_in\ndef logout():\n session.clear()\n flash('You are now logged out', 'success')\n return redirect(url_for('login'))\n\n\nif __name__ == \"__main__\":\n app.secret_key = 'secret123'\n app.run(debug=True)\n","repo_name":"qadeesz/python-flask-app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16817921873","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.path import Path\nimport matplotlib.patches as patches\nimport math as math\nfrom matplotlib import pyplot\nfrom matplotlib import cm\nfrom shapely.geometry import LineString\n\nimport tsdf\n\ndef circular_weighted_average(angles, weights):\n summed_weight = 0\n summed_y = 0\n summed_x =0\n for i in range(len(angles)):\n summed_y += np.sin(angles[i]) * weights[i]\n summed_x += np.cos(angles[i]) * weights[i]\n return math.atan2(summed_y,summed_x)\n \n \n\ndef getRaytracingHelperVariables(observation_origin, observation_ray,t_start, t_end, grid_size_inv):\n traversal_start = observation_origin + t_start * observation_ray\n traversal_end = observation_origin + t_end * observation_ray\n traversal_start_scaled = traversal_start * grid_size_inv\n traversal_end_scaled = traversal_end * grid_size_inv\n traversal_ray_scaled = traversal_end_scaled - traversal_start_scaled\n traversal_ray_scaled_inv =(1. / traversal_ray_scaled[0], 1. / traversal_ray_scaled[1])\n grid_index = np.round(traversal_start_scaled)\n grid_step = np.sign(traversal_ray_scaled)\n t_max = (grid_index - traversal_start_scaled) * traversal_ray_scaled_inv\n t_delta = grid_step * traversal_ray_scaled_inv\n return grid_index, grid_step, t_max, t_delta\n\ndef unit_vector(vector):\n return vector / np.linalg.norm(vector)\n\ndef toTwoPi(value):\n if(value > math.pi):\n return toTwoPi(value - 2 * math.pi) #value % math.pi\n if(value < - math.pi):\n return toTwoPi(value + 2 * math.pi) #value % -math.pi\n return value\n\ndef angle_between(v1, v2):\n v1_normalized = unit_vector(v1)\n v2_normalized = unit_vector(v2)\n return toTwoPi(angle(v1)-angle(v2))\n\ndef angle(v):\n v_normalized = unit_vector(v)\n return math.atan2(v_normalized[1], v_normalized[0]) \n \ndef distanceLinePoint(line_p0, line_p1, point):\n numerator = np.abs((line_p1[1]-line_p0[1])*point[0] - (line_p1[0]-line_p0[0])*point[1] + line_p1[0]*line_p0[1] - line_p1[1]*line_p0[0]) \n denominator = np.linalg.norm(line_p1-line_p0)\n return numerator/denominator \n\ndef gaussian(x, mu=0, sigma=1):\n return 1/(math.sqrt(2*math.pi)*sigma**2)*math.e**(-0.5*((x-mu)/sigma**2)**2)\n\nclass ScanNormalTSDFRangeInserter: \n \n def __init__(self, use_normals_weight=False, n_normal_samples=8, default_weight=1, use_distance_cell_to_observation_weight=False, use_distance_cell_to_ray_weight=False, use_scale_distance=False, normal_distance_factor=1, max_weight=1000, draw_normals_scan_indices=[0], use_distance_cell_to_hit = False):\n self.use_normals_weight = use_normals_weight\n self.use_distance_cell_to_observation_weight = use_distance_cell_to_observation_weight\n self.sigma_distance_cell_to_observation_weight = 1.0\n self.use_distance_cell_to_ray_weight = use_distance_cell_to_ray_weight\n self.sigma_distance_cell_to_ray_weight = 0.6\n self.n_normal_samples = n_normal_samples\n self.default_weight = default_weight\n self.normal_distance_factor = normal_distance_factor #0 --> all normals same weight, 1 --> f(0)=1, f(0.1)=0.9 f(0.2)=0.82 independent of distance, inf -->only closest normal counts\n self.max_weight = max_weight\n self.draw_normals_scan_indices = draw_normals_scan_indices\n self.num_inserted_scans = 0\n self.use_scale_distance = use_scale_distance\n self.use_distance_cell_to_hit = use_distance_cell_to_hit\n print(self)\n \n def __str__(self):\n return \"ScanNormalTSDFRangeInserter \\n use_normals_weight %s \\n n_normal_samples %s\\n default_weight %s\\n normal_distance_factor %s\\n\" % (self.use_normals_weight, self.n_normal_samples, self.default_weight, self.normal_distance_factor)\n \n \n def updateCell(self, tsdf, cell_index, update_distance, ray_length, update_weight): \n if(abs(update_distance)< tsdf.truncation_distance):\n updated_weight = min(tsdf.getWeight(cell_index) + update_weight, self.max_weight)\n updated_tsdf = (tsdf.getTSDF(cell_index) * tsdf.getWeight(cell_index) + update_distance * update_weight) / (update_weight + tsdf.getWeight(cell_index)) \n tsdf.setWeight(cell_index, updated_weight)\n tsdf.setTSDF(cell_index, updated_tsdf)\n #tsdf.setWeight(cell_index, 0.5)\n #tsdf.setTSDF(cell_index, 0.5) \n\n \n def computeNormal(self, sample, neighbors, sample_origin):\n normals = []\n normal_distances = []\n normal_weights = []\n for neighbor in neighbors:\n sample_to_neighbor = sample - neighbor\n origin_to_neighbor = sample_origin - neighbor\n origin_to_sample = sample_origin - sample\n sample_to_neighbor_rotated = np.array([-sample_to_neighbor[1],sample_to_neighbor[0]])\n if(sample_to_neighbor_rotated.dot(origin_to_sample) > 0):\n sample_to_neighbor = -sample_to_neighbor\n \n tangent_angle = angle(sample_to_neighbor)\n normal_angle = toTwoPi(tangent_angle - math.pi/2)\n normals += [normal_angle]\n normal_distance = np.linalg.norm(sample-neighbor)\n normal_distances += [normal_distance]\n normal_weights += [math.e**(-self.normal_distance_factor * normal_distance)]\n \n normals = np.array(normals)\n normal_weights = np.array(normal_weights)\n normal_mean = circular_weighted_average(normals, normal_weights)\n delta = normals-normal_mean\n delta_flipped = (normals-normal_mean)-2*math.pi\n is_min_delta = np.abs(delta) < np.abs(delta_flipped)\n min_deltas = delta*is_min_delta + delta_flipped*(1-is_min_delta)\n normal_var = np.average((min_deltas-normal_mean)**2, weights=normal_weights)\n normal_weight_sum = np.sum(normal_weights)\n return normal_mean, normal_var, normal_weight_sum\n \n def drawScanWithNormals(self, hits, normal_orientations, sensor_origin, normal_weights, normal_variances, normal_angle_to_ray):\n fig = plt.figure()\n ax = plt.subplot(311)\n x_val = [x[0] for x in hits]\n y_val = [x[1] for x in hits]\n sc = ax.scatter(x_val, y_val, c=normal_weights, marker='x', cmap=cm.jet)\n plt.colorbar(sc)\n ax.scatter(sensor_origin[0], sensor_origin[1], marker='x')\n for idx, normal_orientation in enumerate(normal_orientations): \n normal_scale = 0.1\n dx = normal_scale*np.cos(normal_orientation)\n dy = normal_scale*np.sin(normal_orientation) \n ax.arrow(x_val[idx], y_val[idx], dx, dy, fc='k', ec='k', color='b')\n ax.set_aspect('equal') \n plt.title('Normal Estimation Weights')\n ''' \n ax = plt.subplot(412)\n x_val = [x[0] for x in hits]\n y_val = [x[1] for x in hits]\n sc = ax.scatter(x_val, y_val, c=normal_variances, marker='x', cmap=cm.jet)\n plt.colorbar(sc)\n ax.scatter(sensor_origin[0], sensor_origin[1], marker='x')\n for idx, normal_orientation in enumerate(normal_orientations): \n normal_scale = 0.1\n dx = normal_scale*np.cos(normal_orientation)\n dy = normal_scale*np.sin(normal_orientation) \n ax.arrow(x_val[idx], y_val[idx], dx, dy, fc='k', ec='k', color='b')\n ax.set_aspect('equal')\n plt.title('Normal Estimation Variances')\n ''' \n ax = plt.subplot(312)\n x_val = [x[0] for x in hits]\n y_val = [x[1] for x in hits]\n sc = ax.scatter(x_val, y_val, c=np.cos(normal_angle_to_ray), marker='x', cmap=cm.jet)\n plt.colorbar(sc)\n ax.scatter(sensor_origin[0], sensor_origin[1], marker='x')\n for idx, normal_orientation in enumerate(normal_orientations): \n normal_scale = 0.1\n dx = normal_scale*np.cos(normal_orientation)\n dy = normal_scale*np.sin(normal_orientation) \n ax.arrow(x_val[idx], y_val[idx], dx, dy, fc='k', ec='k', color='b')\n ax.set_aspect('equal')\n plt.title('Angle normal to ray')\n \n ax = plt.subplot(313)\n x_val = [x[0] for x in hits]\n y_val = [x[1] for x in hits]\n combined_weights = np.reciprocal(np.sqrt(np.array(normal_variances))) * (np.square(np.array(normal_weights))) * np.square(np.cos(normal_angle_to_ray))\n combined_weights = np.cos(normal_angle_to_ray)\n sc = ax.scatter(x_val, y_val, c=combined_weights, marker='x', cmap=cm.jet)\n plt.colorbar(sc)\n ax.scatter(sensor_origin[0], sensor_origin[1], marker='x')\n for idx, normal_orientation in enumerate(normal_orientations): \n normal_scale = 0.1\n dx = normal_scale*np.cos(normal_orientation)\n dy = normal_scale*np.sin(normal_orientation) \n ax.arrow(x_val[idx], y_val[idx], dx, dy, fc='k', ec='k', color='b')\n ax.set_aspect('equal')\n plt.title('Combined weight')\n \n \n def insertScan(self, tsdf, hits, origin):\n origin = np.array(origin)\n hits = np.array(hits)\n n_hits = len(hits)\n normal_orientations = []\n normal_orientation_variances = []\n normal_estimation_weight_sums = []\n normal_estimation_angles_to_ray = []\n normal_estimation_angle_to_ray = 0\n normal_orientation = 0\n for idx, hit in enumerate(hits): \n #print('origin',origin) \n #print('hit',hit) \n hit = np.array(hit)\n ray = hit - origin \n \n if self.use_normals_weight or True:\n neighbor_indices = np.array(list(range(idx-int(np.floor(self.n_normal_samples/2)), idx)) + list(range(idx+1, idx+int(np.ceil(self.n_normal_samples/2) + 1))))\n neighbor_indices = neighbor_indices[neighbor_indices >= 0]\n neighbor_indices = neighbor_indices[neighbor_indices < n_hits]\n normal_orientation, normal_var, normal_estimation_weight_sum = self.computeNormal(hit, hits[neighbor_indices], origin)\n normal_orientations += [normal_orientation]\n normal_estimation_weight_sums += [normal_estimation_weight_sum]\n normal_orientation_variances += [normal_var]\n normal_estimation_angle_to_ray = normal_orientation - angle(-ray)\n normal_estimation_angles_to_ray += [normal_estimation_angle_to_ray] # \n \n ray_range = np.linalg.norm(ray) \n range_inv = 1.0 / ray_range\n t_truncation_distance = tsdf.truncation_distance * range_inv\n t_start = 1.0 - t_truncation_distance\n t_end = 1.0 + t_truncation_distance\n grid_index, grid_step, t_max, t_delta = getRaytracingHelperVariables(origin, ray, t_start,t_end, 1. / tsdf.resolution)\n t = 0\n while t < 1.0 : \n #print('t',t,'t_max',t_max,'t_delta',t_delta) \n #print('grid_index',grid_index)\n t_next = np.min(t_max)\n min_coeff_idx = np.argmin(t_max)\n sampling_point = grid_index * tsdf.resolution #origin + (t + t_next)/2 * ray\n #print('sampling_point',sampling_point,'t',origin + (t) * ray,'tn',origin + (t_next) * ray)\n cell_index = tsdf.getCellIndexAtPosition(sampling_point)\n cell_center = tsdf.getPositionAtCellIndex(cell_index)\n distance_cell_center_to_origin = np.linalg.norm(cell_center - origin)\n distance_cell_center_to_hit = np.linalg.norm(cell_center - hit)\n update_weight = 1\n update_distance = ray_range - distance_cell_center_to_origin\n #use_distance_cell_to_observation_weight\n if self.use_normals_weight:\n update_weight = np.cos(normal_estimation_angle_to_ray)\n if(update_weight < 0):\n print('WARNING update_weight=',update_weight)\n if self.use_distance_cell_to_observation_weight:\n normalized_distance_cell_to_observation = np.abs(ray_range - distance_cell_center_to_origin)/tsdf.resolution\n distance_cell_to_observation_weight = gaussian(normalized_distance_cell_to_observation, 0, self.sigma_distance_cell_to_observation_weight) \n ''' \n distance_cell_to_observation_weight = np.abs((tsdf.truncation_distance - np.abs(ray_range - distance_cell_center_to_origin))/tsdf.truncation_distance)\n '''\n update_weight *= distance_cell_to_observation_weight\n if distance_cell_to_observation_weight < 0:\n print('WARNING distance_cell_to_observation_weight=',distance_cell_to_observation_weight)\n if self.use_distance_cell_to_ray_weight:\n distance_cell_to_ray = distanceLinePoint(origin, hit, cell_center)/tsdf.resolution\n #distance_cell_to_ray_weight = distance_cell_to_ray\n distance_cell_to_ray_weight = gaussian(distance_cell_to_ray, 0, self.sigma_distance_cell_to_ray_weight) \n update_weight *= distance_cell_to_ray_weight\n if distance_cell_to_ray_weight < 0:\n print('WARNING distance_cell_to_ray_weight=',distance_cell_to_ray_weight)\n \n if self.use_scale_distance:\n #print(np.array([np.cos(normal_orientation), np.sin(normal_orientation)]))\n update_distance = (cell_center - hit).dot(np.array([np.cos(normal_orientation), np.sin(normal_orientation)]))\n if self.use_distance_cell_to_hit:\n update_distance = distance_cell_center_to_hit\n if self.use_distance_cell_to_hit and self.use_scale_distance:\n print('CONFIGURATION ERROR')\n \n \n self.updateCell(tsdf, cell_index, update_distance , ray_range, update_weight)\n #print('cell_index', cell_index) \n t = t_next\n grid_index[min_coeff_idx] += grid_step[min_coeff_idx]\n t_max[min_coeff_idx] += t_delta[min_coeff_idx]\n if self.use_normals_weight:\n if self.num_inserted_scans in self.draw_normals_scan_indices :\n self.drawScanWithNormals(hits, normal_orientations, origin, normal_estimation_weight_sums, normal_orientation_variances, normal_estimation_angles_to_ray)\n self.draw_normals = False\n #print('avg normal error', np.mean(np.abs(normal_orientations)))\n pass\n self.num_inserted_scans += 1\n","repo_name":"kdaun/ray_simulator","sub_path":"tsdf_inserter.py","file_name":"tsdf_inserter.py","file_ext":"py","file_size_in_byte":14871,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"18901291967","text":"# 生成器函数\ndef my_range(end):\n number = -1\n while number < end - 1:\n number += 1\n yield number\n\n\n# for item in my_range(5):\n# print(item)\n\n# 生成器 = 可迭代对象 + 迭代器\n\n\nlist01 = [5, 1, 7, 5, 4, 6, 10]\n\n\ndef get_num(list_target):\n list_res = []\n for item in list_target:\n if not item % 2:\n list_res.append(item)\n return list_res # 一去不复返, 如果返回多个结果必须先整体存起来再返回\n\n\ndef get_res(list_target): # 调函数不执行, 返回生成器对象 = 可迭代对象 + 迭代器\n for item in list_target:\n if not item % 2:\n yield item # 暂时离开\n\n\nprint(get_num(list01))\n\n# def get_res(list_target):\n# index = 0\n# while index < len(list_target):\n# if not list01[index] % 2:\n# yield list_target[index]\n# index += 1\n#\n#\n# for i in get_res(list01):\n# print(i)\n","repo_name":"QiWang-SJTU/AID1906","sub_path":"Part1 Python base/03Python_core/03Exercise_code/Day16/exercise09.py","file_name":"exercise09.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"691514515","text":"from offregister_fab_utils.apt import apt_depends\nfrom offregister_fab_utils.fs import cmd_avail\nfrom offregister_fab_utils.git import clone_or_update\n\n\ndef install_plugin(c, repo_team, repo_name, location=None):\n \"\"\"\n :param c: Connection\n :type c: ```fabric.connection.Connection```\n \"\"\"\n\n apt_depends(c, \"git\")\n cmd = \"dokku\"\n if not cmd_avail(c, cmd):\n raise EnvironmentError(\n \"Install {cmd} before installing plugins\".format(cmd=cmd)\n )\n with c.cd(\"/var/lib/dokku/plugins\"):\n clone_or_update(c, team=repo_team, repo=repo_name, to_dir=location or repo_name)\n c.run(\"dokku plugins-install\")\n","repo_name":"offscale/offregister","sub_path":"offregister/aux_recipes/dokku_plugin.py","file_name":"dokku_plugin.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"11684215589","text":"# mldesigner package contains the command_component which can be used to define component from a python function\nimport logging\nfrom pathlib import Path\n\nfrom mldesigner import command_component, Input, Output\n\nURI_FOLDER = \"uri_folder\"\n\n\n@command_component(\n display_name=\"Evaluate\",\n environment=\"./environment.conda.yaml\",\n)\ndef evaluate_step(\n model_input: Input(type=URI_FOLDER),\n images_input: Input(type=URI_FOLDER),\n model_output: Output(type=URI_FOLDER),\n integration_output: Output(type=URI_FOLDER),\n):\n from evaluate import evaluate\n\n evaluate(logging, Path(model_input), Path(images_input),\n Path(model_output), Path(integration_output))\n\n\n","repo_name":"guillaume-thomas/MLOpsPython-2022-2023","sub_path":"train/evaluate/azureml_step.py","file_name":"azureml_step.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"8551947307","text":"def answer(question):\n parts = question.split()\n expression = []\n operations = {\n 'plus': '+', 'minus': '-', 'multiplied': '*', 'divided': '/'\n }\n for part in parts:\n if part.isdecimal():\n expression.append(part)\n elif part[-1] == '?':\n try:\n expression.append(str(int(part[:-1])))\n except ValueError:\n if part[:-1] not in operations.keys():\n if len(expression) == 0 and question == 'What is?':\n raise ValueError(\"syntax error\")\n raise ValueError(\"unknown operation\")\n else:\n expression.append(part[:-1])\n elif part in operations.keys():\n expression.append(part)\n elif part[0] == '-':\n expression.append(part)\n\n if len(expression) == 1:\n if expression[0] not in operations.keys():\n return int(expression[0])\n else:\n raise ValueError(\"syntax error\")\n\n valid_mask = [part not in operations.keys() for part in expression]\n\n if not valid_mask[0] or not valid_mask[-1]:\n raise ValueError(\"syntax error\")\n\n if len(valid_mask) % 2 == 0:\n if expression[-2] == 'multiplied':\n raise ValueError(\"unknown operation\")\n if not valid_mask[1] and not valid_mask[2]:\n raise ValueError(\"syntax error\")\n if valid_mask[-2] and valid_mask[-1]:\n raise ValueError(\"syntax error\")\n raise ValueError(\"unknown operation\")\n\n if valid_mask[1]:\n raise ValueError(\"syntax error\")\n\n result = 0\n op = ''\n for part in expression:\n if part in operations.keys():\n op = part\n else:\n if op:\n result = int(eval(f'{result}{operations[op]}{part}'))\n op = ''\n else:\n result += int(part)\n return result\n\n\nif __name__ == '__main__':\n print(answer(\"What is 7 plus multiplied by -2?\"))\n #print(answer(\"What is 1 plus 2 1?\"))\n #print(answer(\"What is 7 plus multiplied by -2?\"))\n #print(answer('What is 52?'))\n #print(answer('What is -3 plus 7 multiplied by -2?'))\n #print(answer('What is 52 cubed?'))\n #print(answer('What is 25 divided by 5?'))\n #print(answer('What is 3 plus 2 multiplied by 3?'))\n\n","repo_name":"itsanti/exercism","sub_path":"python/wordy/wordy.py","file_name":"wordy.py","file_ext":"py","file_size_in_byte":2337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"39861309353","text":"import os\r\nfrom dotenv import load_dotenv\r\nimport random \r\nimport hashlib\r\nimport requests\r\nimport pdb\r\nload_dotenv('../.env')\r\n\r\ngoogle_client_id = os.getenv('GOOGLE_CLIENT_ID')\r\ngoogle_client_secret = os.getenv('GOOGLE_CLIENT_SECRET')\r\n\r\nclass Authentication:\r\n def __init__(self):\r\n self.google_state = None\r\n pass\r\n\r\n def check(session):\r\n try:\r\n if session[\"logged_in\"] == None or session[\"logged_in\"] == False:\r\n return False\r\n else:\r\n return True\r\n except KeyError:\r\n return False\r\n\r\n def authGoogle():\r\n scope = ['https://www.googleapis.com/auth/userinfo.email', 'https://www.googleapis.com/auth/userinfo.profile']\r\n\r\n #generate random md5 string for state\r\n state = hashlib.md5(str(random.getrandbits(256)).encode('utf-8')).hexdigest()\r\n google_url = f'https://accounts.google.com/o/oauth2/v2/auth?scope={\"%20\".join(scope)}&redirect_uri=http://localhost:5000/auth/google/callback&response_type=code&client_id={google_client_id}&state={state}'\r\n \r\n return {\r\n 'google_url': google_url,\r\n 'state': state\r\n }\r\n\r\n def getGoogleToken(code):\r\n \"\"\"\r\n {\r\n \"access_token\": \"xxxxxxxxxxxxxxx\",\r\n \"expires_in\": 3920,\r\n \"token_type\": \"Bearer\",\r\n \"scope\": \"https://www.googleapis.com/auth/drive.metadata.readonly\",\r\n \"refresh_token\": \"xxxxxxxxxxxxxxxxxxxxx\"\r\n }\r\n \"\"\"\r\n \r\n \r\n data = {\r\n 'code': code,\r\n 'client_id': google_client_id,\r\n 'client_secret': google_client_secret,\r\n 'redirect_uri': 'http://localhost:5000/auth/google/callback',\r\n 'grant_type': 'authorization_code'\r\n }\r\n\r\n headers = {\r\n 'Content-Type': 'application/x-www-form-urlencoded'\r\n }\r\n\r\n response = requests.post('https://oauth2.googleapis.com/token', data=data, headers=headers)\r\n return response.json()\r\n","repo_name":"viniciuspereiras/OAuth-playground","sub_path":"blueprints/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"74544647554","text":"from user_drive_database import userVerification, createDatabaseConnections\nimport json\nimport os\n# [\n# {\"userLoggedIn\":\"boolean_value\", \"UserAccess\":\"access_level\"},\n# {\"name\":\"drive_name\", \"gameName\":\"game_name\", \"gameSize\":\"int(gameSize)\", \"sizeMetric\":\"gameSizeMetric\", \"gameTags\":\"[listOfTags]\",\"dateAdded\":\"mm/dd/yyyyy\",\"playTime\":\"YYYY:DD:HH:MM\"},\n# ['username','password','email','dir_to_drive_database','dir_to_game_database', int(acclev), int(randid)],\n# int(randID_sentByBrowser)\n# ]\n\ntableName = ''\n\ndef addGameToDB(information):\n verified = json.loads(userVerification(information))\n if int(verified[\"errorcode\"])==0:\n databaseConnections = createDatabaseConnections(information)\n gameInformation = list(information[1].values())\n matchingGameInformation = len(list(databaseConnections[1].execute(\"\"\"SELECT * FROM\"\"\")))\n\n\n#removeGameFromDB()\n#retrieveGamesFromDB()\n#addUpdateToGame()\n#removeUpdateFromGame()\n#retrieveAllInfoOnGameInDB()\n#addMath()\n#subMath()","repo_name":"goldeneye5671/Game-Tracker-Ultimate","sub_path":"Depreciated FIles/user_game_database.py","file_name":"user_game_database.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3724118291","text":"# Day 19\n\nimport pandas as pd\nimport mysql.connector\n\nmydb = mysql.connector.connect(\n host=\"localhost\",\n user=\"root\",\n password=\"\",\n database=\"bestenlist\"\n)\nmycursor = mydb.cursor()\nmycursor.execute(\n \"CREATE TABLE employee (name VARCHAR(255), id INT,salary INT)\")\n\n# a.\nmycursor.execute(\"SELECT max(salary),min(salary) FROM employee\")\nmyresult = mycursor.fetchall()\nfor x in myresult:\n print(f\"Max Salary : {x[0]}, Min Salary : {x[1]}\")\n\n# b.\nmycursor.execute(\"SELECT count(id) FROM employee\")\nmyresult = mycursor.fetchall()\nfor x in myresult:\n print(\"Number of employees : \", x[0])\n\n\n# c.\nmycursor.execute(\"SELECT substring(e.name,1,3) FROM employee e\")\nmyresult = mycursor.fetchall()\nfor x in range(len(myresult)):\n print(myresult[x][0])\n","repo_name":"BenMeehan/BestEnlist","sub_path":"Day 20.py","file_name":"Day 20.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23606521671","text":"from numpy import *\nf = open('C-small-attempt0.in', 'r')\nd = open('c.out', 'w')\nc=int(f.readline())\nfor test in range(1,c+1):\n\tbuffer=0\n\tmoola=0\n\tcontroll=f.readline()\n\tgroups=f.readline()\n\tcontroll=controll.split()\n\tcontroll=map(int, controll) \n\tgroups=groups.split()\n\tqueu=map(int, groups) \n\tseat=list()\n\ttemp=0\n\tfor i in range(1,controll[0]+1):\n\t\tbuffer=0\n\t\twhile queu and queu[0]+buffer <= controll[1]:\n\t\t\tbuffer+=queu[0]\n\t\t\ttemp=queu.pop(0)\n\t\t\tseat.append(temp)\n\t\tfor x in seat:\n\t\t\tqueu.append(x)\t\n\t\tseat=[]\n\t\tmoola+=buffer\n\td.write ('Case #{0}: {1}\\n'.format(test,moola))\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_55/800.py","file_name":"800.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"12043225737","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.db.models import Q\nfrom django.urls import reverse\nfrom .models import Ingredient, Recipe\n# Create your views here.\n\n\ndef recipe_detail(request, pk):\n \"\"\" Полная информация по рецепту с пошаговой инструкцией \"\"\"\n recipe = get_object_or_404(Recipe, pk=pk)\n recipe.recipe_text = recipe.text.strip().split('\\n')\n return render(\n request,\n 'bookCook/recipe_detail.html',\n {'recipe': recipe}\n )\n\n\ndef home(request):\n \"\"\" Список рецептов с поиском по назвению и ингредиентам\"\"\"\n\n try:\n recipe_id = int(request.GET.get(\"recipe_id\"))\n except (ValueError, TypeError):\n recipe_id = None\n\n try:\n ingredient_id = int(request.GET.get(\"ingredient_id\"))\n except (ValueError, TypeError):\n ingredient_id = None\n\n query = Q()\n if recipe_id:\n query.add(\n Q(pk=recipe_id), Q.AND,\n )\n if ingredient_id:\n query.add(\n Q(ingredients__pk=ingredient_id), Q.AND,\n )\n\n recipes_object = Recipe.objects.prefetch_related(\"ingredients\").filter(query)\n recipes = Recipe.objects.all()\n ingredients = Ingredient.objects.all()\n\n\n return render(\n request,\n 'bookCook/recipes.html',\n {\n 'recipes': recipes_object,\n 'form': {\n 'description': \"Здесь вы можете ввести название рецепта или ингредиента\",\n 'ingredient': {\n 'name': 'Ингредиент',\n 'objects': ingredients,\n 'selected': ingredient_id,\n },\n 'recipe': {\n 'name': 'Название',\n 'objects': recipes,\n 'selected': recipe_id,\n },\n }\n }\n )\n","repo_name":"TaWerKa111/django-bookCook","sub_path":"app/bookCook/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70113265476","text":"from datetime import date\nfrom ariadne import convert_kwargs_to_snake_case\nfrom api import db\nfrom api.models.user import User\nfrom modules.hash import hash_password\n\n\n@convert_kwargs_to_snake_case\ndef createUser_resolver(obj, info, username, password):\n try:\n prev_user = User.query.filter(User.username == username).scalar()\n if prev_user:\n payload = {\n \"success\": False,\n \"errors\": [\"username in use\"]\n }\n else:\n today = date.today()\n user = User(\n username=username,\n hash=hash_password(password),\n display_name='',\n created_at=today,\n post_ids=[]\n )\n db.session.add(user)\n db.session.commit()\n payload = {\n \"success\": True,\n \"user\": user.to_dict()\n }\n except ValueError:\n payload = {\n \"success\": False,\n \"errors\": [\"Invalid date\"]\n }\n return payload\n\n\n@convert_kwargs_to_snake_case\ndef updateUser_resolver(obj, info, id, username, display_name):\n try:\n user = User.query.get(id)\n if user:\n user.username = username\n user.display_name = display_name\n db.session.add(user)\n db.session.commit()\n payload = {\n \"success\": True,\n \"user\": user.to_dict()\n }\n except AttributeError as error:\n payload = {\n \"success\": False,\n \"errors\": [\"user not found\", str(error)]\n }\n return payload\n\n\n@convert_kwargs_to_snake_case\ndef deleteUser_resolver(obj, info, id):\n try:\n user = User.query.get(id)\n db.session.delete(user)\n db.session.commit()\n payload = {\"success\": True, \"user\": user.to_dict()}\n except AttributeError:\n payload = {\n \"success\": False,\n \"errors\": [\"user not found\"]\n }\n return payload\n","repo_name":"zrwaite/CredibleSource","sub_path":"server/api/mutations/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"30649078800","text":"import xml.etree.ElementTree\nimport dbnormalizer.experiments.functionalDepExtractor as extract\nimport dbnormalizer.experiments.Normalization_algo as depMatrix\n\n\ndef table_names(file):\n relations = []\n database = xml.etree.ElementTree.parse('dbnormalizer/output/' + file).getroot()\n for a in database.iter('table'):\n primary = []\n attributes = []\n for x in a.iter('attribute'):\n attributes.append(x.attrib['attname'])\n if str(x.find('columnKey').text).lower() == 'pri':\n primary.append(x.attrib['attname'])\n relations.append([a.attrib['tbname'], attributes,primary])\n return relations\n\n\n# get the relevant dependencies from the list\ndef get_relevantDep(fds, primary):\n alldep = []\n for i, key in enumerate(primary):\n relevantfds = []\n print(\"table Name, \",key[0])\n for fd in fds:\n if [fds for fds in fd[0] if fds in key[2]] and len(fd[0]) <= len(key[1]):\n relevantfds.append(fd)\n print(\"fd\",fd)\n if [fds for fds in fd[0] if fds in key[1] and (fds not in relevantfds)]:\n relevantfds.append(fd)\n print(\"fd\", fd)\n alldep.append([key[0], key[2], relevantfds])\n return alldep\n\n\ndef normalize(dep, relation, database_name):\n sqlText = ''\n for i in range(len(relation)):\n\n fds = dep[i][2]\n rel = relation[i][1]\n\n # ind = v\n # print(\"Table Name,\", v[0])\n # print(\"functional dep\", d[2])\n # print(\"relation\", ind)\n # rel = ind[1]\n\n # fds = d[2]\n # print(\"fds\",fds)\n DM, determinents = depMatrix.dependencyMatrix(rel, fds)\n # print(\"DM\")\n # print(DM)\n\n DG = depMatrix.directedGraph(DM, determinents, rel)\n # print(\"DG\")\n # print(DG)\n\n DC = depMatrix.dependencyClosure(DM, DG, determinents, rel, fds)\n # print(DC)\n\n CDC = depMatrix.circularDependency(DM, DC)\n # print(\"CDC\")\n # print(CDC)\n\n\n sqlText += str(depMatrix.to3NF(CDC, rel, fds, database_name))\n\n return sqlText\n\ndef start_normalizer(file_name=\"example_scenario.txt\", xml_file=\"example.xml\", database_name=None):\n\n content = extract.readfile(file_name)\n x = extract.table_names(xml_file)\n s = extract.get_functionaldep(extract.extractor(content))\n\n fds = extract.restructure_keys(s, x)\n\n tables = table_names(xml_file)\n\n dependencies = get_relevantDep(fds, tables)\n\n return normalize(dependencies, tables, database_name)\n","repo_name":"amilacjay/isyntax","sub_path":"dbnormalizer/experiments/tableNormalizer.py","file_name":"tableNormalizer.py","file_ext":"py","file_size_in_byte":2541,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"23542884341","text":"def foo(s, k, c):\r\n num = 0\r\n for i in range(len(s) - k):\r\n if s[i] != c:\r\n for j in range(i, i + k):\r\n s[j] = '+' if s[j] == '-' else '-'\r\n num += 1\r\n cc = s[-k]\r\n if cc != c:\r\n num += 1\r\n for i in range(-k, 0):\r\n if cc != s[i]:\r\n return -1\r\n return num\r\n\r\n\r\nf = open(\"QA.in\", \"r\")\r\nout = open(\"QA.out\", \"w\")\r\nn = int(f.readline())\r\nfor t in range(n):\r\n line = f.readline().split()\r\n s1, s2, k = list(line[0]), list(line[0]), int(line[1])\r\n p = foo(s1, k, '+')\r\n if p == -1:\r\n out.write(\"Case #\" + str(t + 1) + \": IMPOSSIBLE\\n\")\r\n else:\r\n out.write(\"Case #\" + str(t + 1) + \": \" + str(p) + \"\\n\")\r\nout.close()","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_199/2251.py","file_name":"2251.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16079917749","text":"A = [3,4,3,2,3,-1,3,3]\n\ndef solution(A):\n # write your code in Python 3.6\n leader_index = -1\n if len(A) > 0:\n A_not_sorted = A.copy()\n A.sort() \n n = len(A)//2\n candidate = A[n]\n frequency = 0\n for i in range(len(A)):\n if A[i] == candidate:\n frequency += 1\n if frequency > n:\n leader_index = A_not_sorted.index(A[n])\n return leader_index\n\nprint(solution(A))\n","repo_name":"ymik0410/codility","sub_path":"dominator.py","file_name":"dominator.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70408634755","text":"# std\nimport unittest\n\n# internal\nfrom terraform_model.all import *\nfrom terraform_model.types.internal import TfUnknown\n\n\nclass TestTfRegex(unittest.TestCase):\n\n def test_tfregex_type(self):\n x = variable('x', type=TfString)\n result = tfregex('[a-z]+', x)\n self.assertIsInstance(result, TfUnknown)\n\n def test_tfregex_str(self):\n x = variable('x', type=TfString)\n result = str(tfregex('[a-z]+', x))\n self.assertEqual(result, 'regex(\"[a-z]+\", var.x)')\n","repo_name":"Mohadi3O/python-terraform-utils","sub_path":"packages/terraform_model/tests/test_functions/test_string/test_tfregex.py","file_name":"test_tfregex.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"43401881910","text":"import pymongo\n\n_author_ = 'panong'\n\nuri = \"mongodb://Harry:Hogwarts4ever@192.142.32.100/gryffindor\"\nclient = pymongo.MongoClient(uri)\ndatabase = client['gryffindor']\ncollection = database['SortingHat']\n\n\ndef record():\n wizards = collection.find({})\n for person in wizards:\n print (\"Are you afraid of what you'll hear?\\nYour Animagus is a {}, {}\".format(person['Animagus'],person['Member']))\n\nrecord()\n\n","repo_name":"PatriciaAnong/Blog","sub_path":"Connect.py","file_name":"Connect.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"61"}
+{"seq_id":"34760151933","text":"\nimport numpy as np\nimport torch as tr\nfrom torch.nn import Sequential, Conv2d, Linear, Flatten, ReLU, Tanh, Sigmoid\n\ndef TicTacToeNet1(board_size):\n model = Sequential(Flatten(),Linear(4*board_size**2, 2, True),Tanh(),Linear(2,1))\n return model\n \n\ndef calculate_loss(net, x, y_targ):\n y = net(x)\n e = tr.sum((y-y_targ)**2)\n return (y, e)\n \n\ndef optimization_step(optimizer, net, x, y_targ):\n optimizer.zero_grad()\n y, e = calculate_loss(net, x, y_targ)\n # print(\"Y:\\n\",y)\n e.backward()\n optimizer.step()\n return (y,e)\n \ndef helper(board_size):\n net = TicTacToeNet1(board_size=board_size)\n print(net)\n\n import pickle as pk\n with open(\"data1%d.pkl\" % board_size,\"rb\") as f: (x, y_targ) = pk.load(f)\n optimizer = tr.optim.Adam(net.parameters())\n print(optimizer)\n train_loss, test_loss = [], []\n shuffle = np.random.permutation(range(len(x)))\n split = 5\n train, test = shuffle[:-split], shuffle[-split:]\n \n for epoch in range(500):\n y_train, e_train = optimization_step(optimizer, net, x[train], y_targ[train])\n y_test, e_test = calculate_loss(net, x[test], y_targ[test])\n if epoch % 10 == 0: print(\"%d: %f (%f)\" % (epoch, e_train.item(), e_test.item()))\n train_loss.append(e_train.item() / (len(shuffle)-split))\n np.seterr(divide='ignore', invalid='ignore')\n test_loss.append(e_test.item() / split)\n \n tr.save(net.state_dict(), \"model%d.pth\" % board_size)\n \n \n\n \n\n","repo_name":"hemant717556/tictactoewithAI","sub_path":"tictactoe_net.py","file_name":"tictactoe_net.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"70449344834","text":"#Bu kod kameraya gösterilen AprilTag'i detect edip çerçeve içine alıyor.\nimport cv2\nfrom apriltag import apriltag\nimport numpy as np\n\n\ncap = cv2.VideoCapture(0)\n\nwhile(True):\n # Capture frame-by-frame\n ret, frame = cap.read()\n cap.set(cv2.CAP_PROP_FRAME_WIDTH,640); \n cap.set(cv2.CAP_PROP_FRAME_HEIGHT,640); \n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n detector = apriltag('tag36h11')\n results = detector.detect(frame)\n print(results)\n \n for r in results:\n\t# extract the bounding box (x, y)-coordinates for the AprilTag\n\t# and convert each of the (x, y)-coordinate pairs to integers\n (ptA, ptB, ptC, ptD) = r[\"lb-rb-rt-lt\"]\n ptB = (int(ptB[0]), int(ptB[1]))\n ptC = (int(ptC[0]), int(ptC[1]))\n ptD = (int(ptD[0]), int(ptD[1]))\n ptA = (int(ptA[0]), int(ptA[1]))\n\t# draw the bounding box of the AprilTag detection\n cv2.line(frame, ptA, ptB, (0, 255, 0), 2)\n cv2.line(frame, ptB, ptC, (0, 255, 0), 2)\n cv2.line(frame, ptC, ptD, (0, 255, 0), 2)\n cv2.line(frame, ptD, ptA, (0, 255, 0), 2)\n\t# draw the center (x, y)-coordinates of the AprilTag\n (cX, cY) = (int(r[\"center\"][0]), int(r[\"center\"][1]))\n cv2.circle(frame, (cX, cY), 5, (255, 255, 0), -1)\n\t# draw the tag family on the image\n \n \n\n # Display the resulting frame\n cv2.imshow('frame',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"fatmausalan/ApriltagExperiment","sub_path":"Code/test2.py","file_name":"test2.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23553049851","text":"import sys\r\n\r\n\r\ndef tidy(number):\r\n rev_number = list(reversed(number))\r\n last_nine = -1\r\n for i, digit in enumerate(rev_number):\r\n if i < len(number)-1:\r\n digit1 = int(rev_number[i])\r\n digit2 = int(rev_number[i+1])\r\n if digit1 < digit2:\r\n last_nine = i\r\n #print(rev_number)\r\n rev_number[i+1] = str(digit2-1)\r\n #print(rev_number)\r\n #print(last_nine)\r\n for j in range(last_nine+1):\r\n rev_number[j] = \"9\"\r\n res = list(reversed(rev_number))\r\n #print(res)\r\n #print(''.join(res).lstrip(\"0\"))\r\n return int(''.join(res).lstrip(\"0\"))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n name = \"B-large\"\r\n f = open(\"{0}.in\".format(name))\r\n output = open(\"{0}.out\".format(name), \"w\")\r\n cases = int(f.readline())\r\n for i in range(cases):\r\n num = list(f.readline().strip())\r\n #print(num)\r\n output.write(\"Case #\" + str(i + 1) + \": \" + str(tidy(num)) + \"\\n\")\r\n f.close()\r\n output.close()\r\n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_200/1584.py","file_name":"1584.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"34290093395","text":"import cv2\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QImage, QPixmap\nfrom zdl.utils.helper.opencv import countFrames\n\nfrom actionlabeller.model.AbcPlayable import AbcPlayable\nfrom actionlabeller.presenter import MySignals\nfrom actionlabeller.presenter.Settings import Settings\n\n\nclass Video(AbcPlayable):\n def __init__(self, fname):\n super().__init__()\n self.fname = fname\n self._cap = cv2.VideoCapture(self.fname)\n self._info = None\n self._indices = list(range(self.get_info()['frame_c']))\n # self.frames_buffer = queue.Queue(maxsize=100)\n\n def __del__(self):\n self._cap.release()\n\n def set_viewer(self, viewer):\n self.viewer = viewer\n return self\n\n def get_info(self):\n if self._info is None:\n cap = cv2.VideoCapture(self.fname)\n success, img = cap.read()\n fps = cap.get(cv2.CAP_PROP_FPS)\n frame_count = countFrames(cap=cap)\n duration = frame_count / fps\n self._info = {'fname': self.fname,\n 'frame_c': frame_count,\n 'duration': duration,\n 'shape': img.shape,\n 'width': img.shape[1],\n 'height': img.shape[0],\n 'channels': img.shape[2],\n 'fps': fps,\n 'Tms': 1000 / fps}\n return self._info\n\n @property\n def indices(self):\n return self._indices\n\n def to_head(self):\n self.schedule(0, -1, 0, self.__class__)\n\n def to_tail(self):\n tail = self.get_info()['frame_c'] - 1\n self.schedule(tail, -1, tail, self.__class__)\n\n def flush(self):\n if not self._flag_playing and self.scheduled.jump_to is None:\n return None\n if self.scheduled.stop_at:\n _interval = 1\n else:\n _interval = Settings.v_interval\n\n if self.scheduled.jump_to is not None:\n dest_index, self.scheduled.jump_to = self.scheduled.jump_to, None\n else:\n dest_index = self._flag_cur_index + _interval\n\n if self.scheduled.stop_at is not None and dest_index > self.scheduled.stop_at:\n self.scheduled.clear()\n self.pause()\n return None\n\n _gap = dest_index - self._flag_cur_index\n if _gap > 80 or _gap < 1:\n self._cap.set(cv2.CAP_PROP_POS_FRAMES, dest_index)\n _gap = 1\n while _gap:\n _gap -= 1\n ret, frame = self._cap.read()\n if not ret:\n self.schedule(0, -1, 0, MySignals.Emitter.V_PLAYER)\n return None\n\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n # self.frames_buffer.append((self.cur_index, frame))\n height, width, bytesPerComponent = frame.shape\n bytesPerLine = bytesPerComponent * width\n q_image = QImage(frame.data, width, height, bytesPerLine,\n QImage.Format_RGB888).scaled(self.viewer.width(), self.viewer.height(),\n Qt.KeepAspectRatio, Qt.SmoothTransformation)\n q_pixmap = QPixmap.fromImage(q_image)\n self.viewer.setPixmap(q_pixmap)\n\n self._flag_cur_index = dest_index\n self.signals.flushed.emit(self._flag_cur_index)\n return self._flag_cur_index\n","repo_name":"ZDL-Git/ActionLabeller","sub_path":"actionlabeller/model/Video.py","file_name":"Video.py","file_ext":"py","file_size_in_byte":3399,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"27727284187","text":"import time\nimport numpy as np\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom docplex.mp.model import Model\nfrom qiskit_optimization.translators import from_docplex_mp\nfrom qiskit.utils import algorithm_globals, QuantumInstance\nfrom qiskit import Aer, execute, QuantumCircuit\nfrom qiskit.algorithms.minimum_eigensolvers import QAOA\nfrom qiskit_optimization.algorithms import MinimumEigenOptimizer\nfrom qiskit.algorithms.optimizers import COBYLA\n# from qiskit.primitives import Sampler\nfrom qiskit_optimization.converters.quadratic_program_to_qubo import QuadraticProgramToQubo\n\nfrom qiskit_ibm_runtime import Estimator, Sampler, Session\n\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)\n\n# ----------------------------------------------------------------------------------------------------------------------\n# PREPARING THE TSP PROBLEM:\n\nn = 4 # establish the number of nodes for TSP\n\ncoordinates = np.random.default_rng(123).uniform(low=0, high=100, size=(n, 2))\n# create a random distribution of nodes in a grid (coordinates)\npos = dict()\nfor i, coordinate in enumerate(coordinates):\n pos[i] = (coordinate[0], coordinate[1])\n\nhigh = 100\nlow = 0\ngraph = nx.random_geometric_graph(n=n, radius=np.sqrt((high - low) ** 2 + (high - low) ** 2) + 1, pos=pos)\n\nfor w, v in graph.edges:\n delta = []\n for i in range(2):\n delta.append(graph.nodes[w][\"pos\"][i] - graph.nodes[v][\"pos\"][i])\n graph.edges[w, v][\"weight\"] = np.rint(np.sqrt(delta[0] ** 2 + delta[1] ** 2))\n\nindex = dict(zip(list(graph), range(n)))\nA = np.full((n, n), np.nan)\nfor u, wdict in graph.adjacency():\n for v, d in wdict.items():\n A[index[u], index[v]] = d.get(\"weight\", 1)\n\nA[np.isnan(A)] = 0.0\nA = np.asarray(A)\nM = np.asmatrix(A)\nprint(M)\n\n\n# defining the graph drawing fucntion\ndef draw_graph(G, colors, pos):\n default_axes = plt.axes(frameon=True)\n nx.draw_networkx(G, node_color=colors, node_size=600, alpha=.8, ax=default_axes, pos=pos)\n edge_labels = nx.get_edge_attributes(G, \"weight\")\n nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels)\n\n\ncolors = [\"r\" for node in graph.nodes]\npos = [graph.nodes[node][\"pos\"] for node in graph.nodes]\ndraw_graph(graph, colors, pos)\n\n# ----------------------------------------------------------------------------------------------------------------------\n# DEFINING THE OPTIMIZATION PROBLEM (TSP):\n\nmdl = Model(name=\"TSP\") # establishing a model\n\n# defining the matrix tha connects the different nodes of the network\nx = dict()\nfor i in range(n):\n for j in range(n):\n x[(i, j)] = mdl.binary_var(name=\"x_{0}_{1}\".format(i, j))\n\n# defines the cost function being a product of all possible paths and the distances\nC_x = mdl.sum(\n M[i, j] * x[(i, k)] * x[(j, (k + 1) % n)]\n for i in range(n)\n for j in range(n)\n for k in range(n)\n if i != j\n)\n\n# establishes that the goal is to minimize the cost function\nmdl.minimize(C_x)\n\n# establishes the main constraint of the optimization problem, being that each node is visited once (first loop) and is\n# left once (second loop)\nfor i in range(n):\n mdl.add_constraint(mdl.sum(x[i, p] for p in range(n)) == 1)\nfor p in range(n):\n mdl.add_constraint(mdl.sum(x[i, p] for i in range(n)) == 1)\n\n# ----------------------------------------------------------------------------------------------------------------------\n# TRANSFORMING THE QUADRATIC PROBLEM\n\n\nqp = from_docplex_mp(mdl) # transforms the quadratic problem into a qiskit optimization QUADRATIC PROBLEM\nqubo = QuadraticProgramToQubo().convert(problem=qp) # the quantum problem is now converted into a Quadratic\n# Unconstrained Binary Optimization problem so we can later apply Quantum Optimization Solvers\n\n\ndef route_x(x):\n # \"route_x\" is a special tool that will help us later! ;)\n # it searches a matrix of binary solutions to determine which nodes are joined in the solution and thus what is the\n # shortest route\n n = int(np.sqrt(len(x))) # determines the grid size by taking the root square of the x length\n route = [] # creates a route list\n for p in range(n): # iterates through the solution looking for the joined nodes and adding them to the list\n for i in range(n):\n if x[i * n + p]:\n route.append(i)\n\n return route\n\n\nalgorithm_globals.random_seed = 10598\n\ndef optimizer_call(qubo, session):\n\n qaoa_mes = QAOA(sampler=Sampler(session = session), optimizer=COBYLA(), )\n qaoa = MinimumEigenOptimizer(qaoa_mes)\n # qaoa_result = qaoa.solve(qubo)\n qaoa_result = qaoa.run(qubo, backend=backend)\n print(\"\\nQAOA:\\n\", qaoa_result)\n qaoa_result = np.asarray([int(y) for y in reversed(list(qaoa_result))])\n print(\"\\nRoute\\n\", route_x(qaoa_result))\n\n return\n\n\n# Quantum Instance creates a iteration of Qiskit Terra that stores the employed backend\n# quantum_instance = QuantumInstance(Aer.get_backend(\"qasm_simulator\"), seed_simulator=algorithm_globals.random_seed,\n# seed_transpiler=algorithm_globals.random_seed)\nbackend = Aer.get_backend('qasm_simulator')\n\nopt_start_time = time.time()\n\n\nsession = Session(backend=backend)\noptimizer_call(qubo=qubo, session=session)\n\nopt_end_time = time.time()\nexecution_time = opt_end_time - opt_start_time\nlogging.debug(\"optimizer execution time on sim: {:.2f} seconds\".format(execution_time))\n\n# ----------------------------------------------------------------------------------------------------------------------\n# TRYING ON A QUANTUM BACKEND\n\nfrom qiskit_ibm_runtime import QiskitRuntimeService\n\nIBM_API = \"a998d08dcbe837698586eebef6b0bd5f6edb78e05a74cdd944ace2636e41329ffa39585a8f923c4145d02caf3931e2fd9c9b788164a7d0097795289c931ef872\"\n\nservice = QiskitRuntimeService(token=IBM_API)\nbackend = service.least_bussy(simulator=True, operational=True, min_num_qubits=10)\n\nopt_start_time = time.time()\n\nsession = Session(backend=backend)\noptimizer_call(qubo=qubo, session=session)\n\nopt_end_time = time.time()\nexecution_time = opt_end_time - opt_start_time\nlogging.debug(\"optimizer execution time on backend: {:.2f} seconds\".format(execution_time))\n\n# opt_start_time = time.time()\n#\n# # Get the optimized circuit from the QAOA result\n# optimized_circuit = qaoa.get_optimal_circuit()\n# # optimized_circuit = qaoa_mes._ret['optimal_circuit']\n#\n# # Run the optimized circuit on the backend\n# job = execute(optimized_circuit, backend)\n# # Obtain the result of the job\n# result = job.result()\n# # Get the counts (measurement outcomes) from the result\n# counts = result.get_counts()\n#\n# opt_end_time = time.time()\n# execution_time = opt_end_time - opt_start_time\n#\n# # Print the measurement outcomes\n# print(counts)\n# print(\"Backend execution time: {:.2f} seconds\".format(execution_time))\n#\n","repo_name":"Quintanaaalberto/ciclab23","sub_path":"src/algorithms/tsp-medium.py","file_name":"tsp-medium.py","file_ext":"py","file_size_in_byte":6740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29175510253","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Nov 13 13:09:37 2019\r\n\r\n@author: Dan-L\r\n\"\"\"\r\n\r\nimport sys\r\nimport time\r\ndef createAaTable():\r\n #aa = ['A','B','C','D']\r\n #weights = [1,3,5,6]\r\n aa = ['G','A','S','P','V','T','C','I','L','N','D','K','Q','E','M','H','F','R','Y','W']\r\n weights = [57,71,87,97,99,101,103,113,113,114,115,128,128,129,131,137,147,156,163,186]\r\n massTable = dict(zip(weights, aa))\r\n return massTable\r\n\r\ndef findComb(pepMass):\r\n table = {}\r\n for i in range(pepMass+1):\r\n table[i] = 0\r\n aaTable = createAaTable()\r\n for w in aaTable:\r\n table[w] += 1\r\n for m in range(pepMass+1):\r\n #m is the current mass number\r\n for weight in aaTable:\r\n diff = m-weight\r\n #aa = aaTable[weight]\r\n if diff in table:\r\n table[m]+=table[diff]\r\n print(table[pepMass])\r\n return table[pepMass]\r\n\r\n \r\n \r\n\r\ndef main():\r\n start = time.time()\r\n# inNum = sys.argv[1]\r\n# inNum = int(inNum)\r\n pepMass = 1426\r\n numComb = findComb(pepMass)\r\n end = time.time()\r\n print(\"runtime:\", str(end-start), \"seconds\")\r\n \r\nmain()","repo_name":"dlewis27/rosalind","sub_path":"ComputeTheNumberOfPeptidesOfGivenTotalMass.py","file_name":"ComputeTheNumberOfPeptidesOfGivenTotalMass.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"5385653221","text":"from typing import Optional\n\nclass Node:\n def __init__(self, value: int):\n self.value = value\n self.next: Optional[Node] = None\n\nclass LinkedList:\n def __init__(self, node: Node = None):\n self.head = node\n\n def append_head(self, node: Node):\n current = self.head\n self.head = node\n self.head.next = current\n \n def append_tail(self, node: Node):\n if self.head is None:\n self.head = node\n return\n \n current = self.head\n while current.next:\n current = current.next\n current.next = node\n\n def get_position(self, position: int) -> Optional[Node]:\n if position < 1:\n return None\n \n current = self.head\n while current:\n position -= 1\n if position == 0:\n return current\n current = current.next\n \n return None\n\n def insert(self, node: Node, position: int):\n if position < 1:\n return\n \n current = self.head\n if position == 1:\n self.head = node\n self.head.next = current\n return\n \n while current:\n position -= 1\n if position == 1:\n old_next = current.next\n current.next = node\n node.next = old_next\n return\n current = current.next\n \n def delete(self, value: int):\n if value == self.head.value:\n self.head = self.head.next\n return\n\n current = self.head\n while current:\n previous = current\n current = current.next\n if current.value == value:\n previous.next = current.next\n return\n","repo_name":"vladimirdotk/alg","sub_path":"python/alg/linked_list.py","file_name":"linked_list.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"37659382831","text":"import random\n\nsentence = \" Reeves, whose name means over the in Hawaiian, for a living.\"\nsentence2 = \" in the and then the later.\"\nsentence3 = \" eats a before he goes to . It was there, where he encountered his enemy , and then for the entire day.\"\n\nd= {}\nd[\"First_Name\"] = [\"Keanu\", \"Charles\", \"Agatha\", \"Leslie\"]\nd[\"Adjective\"] = [\"dead\", \"metal\", \"massive\", \"blue\"]\nd[\"Noun\"] = [\"tank\", \"sky\", \"kitty\", \"jaguar\", \"mountain\", \"karate\", \"weeds\", \"wolf\"]\nd[\"Verb\"] = [\"meditates\", \"acts\", \"jumps\", \"explodes\", \"ate\", \"ran\"]\nd[\"Hero\"] = [\"Superman\", \"Wonder-Woman\", \"Batman\", \"Thor\", \"Spiderman\"]\n\ndef madlibs(s, dict):\n new_sentence = []\n hero_name = random.choice(d[\"Hero\"])\n for item in s.split():\n if item == \"\":\n new_sentence.append(random.choice(dict[\"First_Name\"]))\n elif item == \"\":\n new_sentence.append(random.choice(dict[\"Adjective\"]))\n elif item == \"\":\n new_sentence.append(random.choice(dict[\"Noun\"]))\n elif item == \"\":\n new_sentence.append(random.choice(dict[\"Verb\"]))\n elif item == \"\":\n new_sentence.append(hero_name)\n else:\n new_sentence.append(item)\n return \" \".join(new_sentence)\n\nprint(madlibs(sentence, d))\nprint(madlibs(sentence2, d))\nprint(madlibs(sentence3, d))","repo_name":"Kushendra1/csci127-assignments","sub_path":"hw_07/madlib.py","file_name":"madlib.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"147502359","text":"lopA1 = [7.8, 5.6, 8.7, 8.9, 9, 9.5]\nlopA2 = [6.0, 6.5, 9.3, 9.2, 7.5]\n\nchoice = input(\"Hãy lựa chọn yêu cầu:\\n1. Bấm phím 1 nếu muốn sắp xếp bảng điểm theo thứ tự tăng dần.\\n2. Bấm phím 2 nếu muốn sắp xếp bảng điểm theo thứ tự giảm dẫn.\\n\")\n\nif choice == \"1\":\n diem = lopA1 + lopA2\n diem.sort()\n print(diem)\n\nif choice == \"2\":\n diem = lopA1 + lopA2\n diem.sort(reserve=True)\n print(diem)\n","repo_name":"TienLe0305/Internship-19-10-2023","sub_path":"Python/sort.py","file_name":"sort.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"17721159382","text":"'''def name(name, age):\n print(\"Hello\")\n print(f\"Hai {name} . Your age is {age}\")\n\n\nprint(\"Start\")\nname(\"Syam\", 30)\nname(age=27, name=\"sarath\")\nprint('Stop')'''\n\n# Return statement\n\n\n'''def square(number):\n print(number * number)\n\nsquare(3)'''\n\n\n'''def emogi_converter(message):\n words = message.split(' ')\n emojis = {\n \":)\": \"😊\",\n \":(\": \"😒\"\n }\n output = \" \"\n for word in words:\n output = output + emojis.get(word, word) + \" \"\n return output\n\n\nmessage = input(\">\")\n\nprint(emogi_converter(message))'''\n\n# Exception\ntry:\n age = int(input(\"Age : \"))\n income = 20000\n risk = income / age\n print(age)\nexcept ZeroDivisionError:\n print(\"Age cannot be zero\")\nexcept ValueError:\n print(\"Invalid value\")\n\n\n\n\n\n","repo_name":"Sarathbabu0108/Learn_Python_Tutorial2","sub_path":"Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"33141562860","text":"import urllib.request, urllib.parse, urllib.error\nimport re\nfhand= urllib.request.urlopen('http://py4e-data.dr-chuck.net/comments_42.html')\nx=list()\n\ndic= dict()\n\nfor line in fhand:\n line= line.decode()\n print(line)\n y= line.split('0-9')\n w= re.findall('[0-9+]', y)\n print(w)\n #type(y)\n","repo_name":"uwaiseibna/pythonall","sub_path":"url1.py","file_name":"url1.py","file_ext":"py","file_size_in_byte":304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"35834669814","text":"import random\r\nimport time\r\n\r\nimport numpy as np\r\n\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef create_points(each_train_num, each_test_num):\r\n '''\r\n 生成训练和测试用的正态分布点\r\n :return:\r\n '''\r\n\r\n a_train = []\r\n b_train = []\r\n a_test = []\r\n b_test = []\r\n\r\n for i in range(0, each_train_num):\r\n # a组训练样本初始化\r\n a_train.append({})\r\n a_train[i]['x1'] = np.random.normal(loc = -5.0, scale = 1.0)\r\n a_train[i]['x2'] = np.random.normal(loc = 0.0, scale = 1.0)\r\n a_train[i]['bias'] = 1\r\n a_train[i]['y'] = 1\r\n a_train[i]['y_'] = 0\r\n\r\n # b组训练样本初始化\r\n b_train.append({})\r\n b_train[i]['x1'] = np.random.normal(loc = 0.0, scale = 1.0)\r\n b_train[i]['x2'] = np.random.normal(loc = 5.0, scale = 1.0)\r\n b_train[i]['bias'] = 1\r\n b_train[i]['y'] = -1\r\n b_train[i]['y_'] = 0\r\n\r\n for i in range(0, each_test_num):\r\n # a组测试样本初始化\r\n a_test.append({})\r\n a_test[i]['x1'] = np.random.normal(loc = -5.0, scale = 1.0)\r\n a_test[i]['x2'] = np.random.normal(loc = 0.0, scale = 1.0)\r\n a_test[i]['bias'] = 1\r\n a_test[i]['y'] = 1\r\n a_test[i]['y_'] = 0\r\n\r\n # b组测试样本初始化\r\n b_test.append({})\r\n b_test[i]['x1'] = np.random.normal(loc = 0.0, scale = 1.0)\r\n b_test[i]['x2'] = np.random.normal(loc = 5.0, scale = 1.0)\r\n b_test[i]['bias'] = 1\r\n b_test[i]['y'] = -1\r\n b_test[i]['y_'] = 0\r\n\r\n return [a_train, b_train, a_test, b_test]\r\n\r\n\r\ndef get_mv(a_train, b_train):\r\n mv_a = np.array([0.0, 0.0])\r\n mv_b = np.array([0.0, 0.0])\r\n for a in a_train:\r\n mv_a += np.array([a['x1'], a['x2']])\r\n for b in b_train:\r\n mv_b += np.array([b['x1'], b['x2']])\r\n mv_a = mv_a / len(a_train)\r\n mv_b = mv_b / len(b_train)\r\n return [np.mat(mv_a).T, np.mat(mv_b).T]\r\n\r\n\r\ndef get_w_and_s(a_train, b_train, mv_a, mv_b):\r\n segma_a = np.mat([[0.0, 0.0],\r\n [0.0, 0.0]])\r\n segma_b = np.mat([[0.0, 0.0],\r\n [0.0, 0.0]])\r\n sw = np.mat([[0.0, 0.0],\r\n [0.0, 0.0]])\r\n for a in a_train:\r\n segma_a += (np.mat([a['x1'], a['x2']]).T - mv_a) * (np.mat([a['x1'], a['x2']]).T - mv_a).T\r\n for b in b_train:\r\n segma_b += (np.mat([b['x1'], b['x2']]).T - mv_b) * (np.mat([b['x1'], b['x2']]).T - mv_b).T\r\n sw = segma_a + segma_b\r\n print(segma_a)\r\n sw_inverse = sw.I\r\n w = sw_inverse * (mv_a - mv_b)\r\n s = w.T * (mv_a + mv_b)\r\n print(\"the s= \"+str(s[0,0]))\r\n return [w, s]\r\n\r\n\r\ndef test(a_test, b_test, w, s):\r\n acc = 0\r\n for a in a_test:\r\n if w.T * np.mat([a['x1'], a['x2']]).T > s:\r\n a['y_'] = 1\r\n acc += 1\r\n else:\r\n a['y_'] = -1\r\n for b in b_test:\r\n if w.T * np.mat([b['x1'], b['x2']]).T > s:\r\n a['y_'] = 1\r\n else:\r\n a['y_'] = -1\r\n acc += 1\r\n acc /= (len(a_test) + len(b_test))\r\n print('test_acc= ' + str(acc))\r\n\r\n\r\ndef get_train_acc():\r\n acc = 0\r\n for a in a_train:\r\n if w.T * np.mat([a['x1'], a['x2']]).T > s:\r\n a['y_'] = 1\r\n acc += 1\r\n else:\r\n a['y_'] = -1\r\n for b in b_train:\r\n if w.T * np.mat([b['x1'], b['x2']]).T > s:\r\n a['y_'] = 1\r\n else:\r\n a['y_'] = -1\r\n acc += 1\r\n acc /= (len(a_train) + len(b_train))\r\n print('train_acc= ' + str(acc))\r\n\r\n\r\ndef draw(w, s):\r\n for a in a_train:\r\n plt.scatter(a['x1'], a['x2'], c = 'red', s = 1, label = 'a')\r\n for b in b_train:\r\n plt.scatter(b['x1'], b['x2'], c = 'blue', s = 1, label = 'b')\r\n for a in a_test:\r\n plt.scatter(a['x1'], a['x2'], c = 'red', s = 20, label = 'a', marker = '+')\r\n for b in b_test:\r\n plt.scatter(b['x1'], b['x2'], c = 'blue', s = 20, label = 'b', marker = '+')\r\n # plt.plot([-5, 5], [-(w[0,0] * (-5) + s[0,0]) / w[1,0], -(w[0,0] * 5 + s[0,0]) / w[1,0]], c = 'green')\r\n plt.plot([-5, 5], [-(w[0, 0] * 5 + s[0, 0]) / w[1, 0], -(w[0, 0] * (-5) + s[0, 0]) / w[1, 0]],\r\n c = 'green') # 取mat中的某个元素m[i,j]\r\n plt.plot([-5, 5], [-(w[0, 0] * (-5) + s[0, 0]) / w[1, 0], -(w[0, 0] * 5 + s[0, 0]) / w[1, 0]], c = 'pink')\r\n\r\n plt.xlabel(\"x1\", fontdict = {'size': 16})\r\n plt.ylabel(\"x2\", fontdict = {'size': 16})\r\n plt.show()\r\n\r\n\r\neach_train_num = 160\r\neach_test_num = 40\r\n\r\n[a_train, b_train, a_test, b_test] = create_points(each_train_num, each_test_num) # 得到训练、测试数据\r\n[mv_a, mv_b] = get_mv(a_train, b_train) # 得到mv\r\n[w, s] = get_w_and_s(a_train, b_train, mv_a, mv_b) # 得到w和s\r\nget_train_acc()\r\ntest(a_test, b_test, w, s) # 在测试数据上测试正确率\r\ndraw(w, s) # 画图\r\n","repo_name":"Liwen-Xiao/Pattern_Recognization_and_Machine_Learning","sub_path":"Fisher/Fisher.py","file_name":"Fisher.py","file_ext":"py","file_size_in_byte":4831,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"25587389124","text":"import random\nimport time\n\n# Reduces the power by taking modulo every iteration. Log(exp) runtime.\ndef power_mod(num, exp, mod) : \n ans = 1\n num = num % mod \n while exp > 0: \n # Check if exp is odd. If it is mutiply num one time to ans.\n if (exp & 1) == 1: \n ans = (ans * num) % mod\n # Divide exp by 2\n exp = exp >> 1 \n num = (num * num) % mod \n return ans\n\n# Factors all the 2's from num\ndef div_2(num):\n count = 0\n # Check if even. If even divide by 2\n while (num & 1) == 0:\n num = num >> 1\n count = count + 1\n return {'number': num, 'count': count}\n\n# Check if number is probably prime\ndef miller_rabin_test(number, repeat): \n # Factor all 2's from number-1. (number-1) would be the order of\n # unit group mod number, if number were prime.\n div_result = div_2(number-1)\n r_power = div_result['count']\n d_number = div_result['number']\n # Will repeat the miller-rabin test with pseudorandom numbers \n # between 2 and number.\n for count in range(repeat):\n check_int = random.randrange(2, number)\n check = power_mod(check_int, d_number, number)\n mainloop = True\n if (check == 1) or (check == number-1):\n continue\n for innner_count in range(r_power):\n check = power_mod(check, 2, number)\n if check == number-1:\n mainloop = False\n break\n if mainloop:\n return False\n return True\n\n# This is an implementaion of binary gcd recursively\ndef fast_gcd(num1, num2):\n # If the numbers are the same then GCD is either number\n if num1 == num2:\n return num1\n # If either of the numbers is 0, any number divides 0,\n # so just return the other number.\n elif num1 == 0:\n return num2\n elif num2 == 0:\n return num1\n # If num1 is even and num 2 is odd gcd(num1,num2)=gcd((num1)/2,num2)\n # else if num1 is even and num 2 is also even gcd(num1,num2)=\n # 2*gcd((num1)/2,(num2)/2)\n elif (num1 & 1) == 0:\n if (num2 & 1) == 1:\n return fast_gcd(num1 >> 1, num2)\n else:\n return fast_gcd(num1 >> 1, num2 >> 1) << 1\n # If num1 is odd and num2 is even gcd(num1,num2)=gcd(num1,(num2)/2)\n elif (num2 & 1) == 0:\n return fast_gcd(num1, num2 >> 1)\n # If num1 and num2 are odd and num1 > num2 then \n # gcd(num1,num2)=gcd((num1-num2)/2, num2)\n elif num1 > num2:\n return fast_gcd((num1-num2) >> 1, num2)\n else:\n return fast_gcd((num2-num1) >> 1, num1)\n\n# Implementation of binary gcd iteratively\ndef iter_fast_gcd(num1, num2):\n shift = 0\n if num1 == 0:\n return num2\n elif num2 == 0:\n return num1\n else:\n while ((num1|num2) & 1) == 0:\n shift += 1\n num1 >>= 1\n num2 >>= 1\n while (num1 & 1) == 0:\n num1 >>= 1\n while True:\n while (num2 & 1) == 0:\n num2 >>= 1\n if num1 > num2:\n temp = num1\n num1 = num2\n num2 = temp\n num2 -= num1\n if num2 == 0:\n break\n return num1 << shift\n\ndef fast_lcm(num1, num2):\n gcd = iter_fast_gcd(num1,num2)\n return (num1*num2) // gcd\n\ndef generate_probable_prime(bits):\n # Generate a pseudoprime of 'bits' bits\n rand_int = random.getrandbits(bits)\n start_time = time.time()\n # Increment until we find prime\n while True:\n if (rand_int & 1) == 0:\n rand_int = rand_int + 1\n # Check if probable prime\n elif miller_rabin_test(rand_int, 11):\n break\n # If it takes more then 10 seconds to find a probable prime\n # run the funtion again.\n elif (time.time() - start_time) > 10:\n rand_int = generate_probable_prime(bits)\n else:\n rand_int = rand_int + 2\n return rand_int\n\n# Iterative version of extended gcd to find inverse\ndef mod_inverse(num, mod_temp) : \n\tmod = mod_temp\n\ty = 0\n\tx = 1\n\tif (mod == 1) : \n\t\treturn 0\n\twhile (num > 1) : \n\t\tq = num // mod_temp\n\t\tt = mod_temp\n\t\tmod_temp = num % mod_temp\n\t\tnum = t \n\t\tt = y \n\t\ty = x - q * y \n\t\tx = t \n\tif (x < 0) : \n\t\tx = x + mod\n\treturn x \n","repo_name":"Dweej-Patel/RSA-Encryption","sub_path":"python/number_theory.py","file_name":"number_theory.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"1132747076","text":"from AvailibleWords import AvailibleWords\nfrom WordleGameEngine import WorldeGameEngine\n\nimport statistics\n\ndef get_all_words():\n all_words_file = open(\"dictionary.txt\", \"rt\")\n all_words = all_words_file.readlines()\n return [word.strip().lower() for word in all_words]\n\ndef let_us_play(all_words):\n availible_words = AvailibleWords(all_words)\n print(\"now let's start\")\n while len(availible_words) > 1:\n guess = input(\"what word was guessed\\n\").strip().lower()\n if len(guess) < 5:\n if guess == 's':\n for words in availible_words.words():\n print(word)\n continue\n if guess == 'q':\n return 'q'\n if guess == 'r':\n return 'r'\n response = input(\"what did the system respond. b for blank, y for yellow, g for green\\n\").lower().strip()\n\n availible_words.filter_guess(guess, response)\n availible_words.words()\n no_words_left = len(availible_words)\n print(\"availible words left\", no_words_left)\n if no_words_left < 11:\n for word in availible_words.words():\n print(word)\n\n\n if len(availible_words) == 0:\n print('seems like we hit an error exiting program')\n return 'q'\n print(\"the word is\", availible_words.words().pop())\n return 'r'\n\n\ndef human_against_gameEngine(all_words):\n gameEngine = WorldeGameEngine(all_words)\n word=input(\"would you like to set the word\\n\").strip()\n if word not in all_words:\n print(\"invalid word setting a random one\")\n word=None\n gameEngine.set_word_to_guess(word)\n response = ''\n while(response != 'ggggg'):\n guess = input(\"what would would you like to guess\\n\")\n response = gameEngine.guess(guess)\n print(\"response was\", response)\n\n\ndef assistant_mode(all_words):\n availible_words = AvailibleWords(all_words)\n print(\"Menu instead of guessing a word type these letters\\nclick enter for next guess\\n\\ts to show what words are availilbe\\n\\tq to quit\\n\\tr to restart with a new word\\n\")\n while (let_us_play(all_words) == 'r'):\n pass\n\n\ndef self_playing_machine(all_words):\n availible_words = AvailibleWords(all_words)\n gameEngine = WorldeGameEngine(all_words)\n gameEngine.set_word_to_guess()\n response = ''\n round = 0\n while(response != 'ggggg'):\n if round % 20 == 0 and round != 0:\n input(\"We just reached %s guesses do you want to continue?\" % (round))\n print(\"Words left in the pool\", len(availible_words))\n if len(availible_words) == 0:\n print(gameEngine.guesses_so_far, gameEngine.secret_word)\n guess = availible_words.get_next_guess()\n # print(\"guess was\", guess)\n response = gameEngine.guess(guess)\n # print(\"response was\", response)\n availible_words.filter_guess(guess, response)\n round+=1\n\n return gameEngine.guesses_so_far\n\nif __name__ == '__main__':\n all_words = get_all_words()\n\n # human_against_gameEngine(all_words)\n assistant_mode(all_words)\n # guesses_distribution = set()\n # total_games = 200\n # for count in range(total_games):\n # guesses = self_playing_machine(all_words)\n # # print(guesses)\n # guesses_distribution.add(len(guesses))\n #\n # print(statistics.mean(guesses_distribution))\n","repo_name":"zingales/WordleSolver","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"42105995933","text":"from __future__ import print_function, division\n\nimport os\nimport json\n\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output, State\n\nfrom sasdash.datamodel import warehouse\n\nfrom .style import XLABEL, YLABEL, TITLE, LINE_STYLE\nfrom .style import AXIS_OPTIONS\nfrom .style import INLINE_LABEL_STYLE, GRAPH_GLOBAL_CONFIG\nfrom ..base import dash_app\n\n_DIFF_OPTIONS = [{\n 'label': 'Relative difference',\n 'value': 'relative_diff',\n}, {\n 'label': 'Absolute difference',\n 'value': 'absolute_diff',\n}, {\n 'label': 'Error',\n 'value': 'error',\n}, {\n 'label': 'Error relative difference',\n 'value': 'error_relative_diff',\n}]\n\n_CALC_FUNCTION = {\n 'relative_diff': lambda x, ref: (x.i - ref.i) / ref.i * 100.0,\n 'absolute_diff': lambda x, ref: x.i - ref.i,\n 'error': lambda x, ref: x.err,\n 'error_relative_diff': lambda x, ref: (x.err - ref.err) / ref.err * 100.0,\n}\n\n_DEFAULT_PLOT_TYPE = 'relative_diff'\n\n_DEFAULT_LAYOUT = html.Div(children=[\n dcc.Graph(\n id='difference-graph',\n figure={'data': ()},\n config=GRAPH_GLOBAL_CONFIG,\n ),\n html.Label('Select as base reference:'),\n dcc.Dropdown(\n id='difference-ref-selection',\n options={},\n value=0,\n ),\n html.Label('Plot type'),\n dcc.RadioItems(\n id='difference-plot-type',\n options=_DIFF_OPTIONS,\n value=_DEFAULT_PLOT_TYPE,\n labelStyle=INLINE_LABEL_STYLE,\n ),\n html.Label('X axis type'),\n dcc.RadioItems(\n id='difference-xaxis-scale',\n options=AXIS_OPTIONS,\n value='linear',\n labelStyle=INLINE_LABEL_STYLE,\n ),\n html.Label('Slider for xlim'),\n dcc.RangeSlider(\n id='difference-xlim',\n # count=1,\n # disabled=True,\n min=0.0,\n max=0.20,\n step=0.01,\n value=[0.0, 0.14],\n ),\n html.Label('Slider for ylim'),\n dcc.RangeSlider(\n id='difference-ylim',\n min=-150.0,\n max=150.0,\n step=1.0,\n value=[-50.0, 50.0],\n ),\n # html.Label('Parameters for smoothing'),\n # html.Label('window length'),\n # dcc.Input(\n # placeholder='Enter a positive odd integer...', value=25,\n # type='number'),\n # html.Label('Polyorder'),\n # dcc.Input(\n # placeholder='Enter an integer less than window length ...',\n # value=5,\n # type='number',\n # ),\n])\n\n\ndef get_series_analysis():\n return _DEFAULT_LAYOUT\n\n\ndef _get_figure(info, plot_type, ref_idx, xaxis_scale, xlim=None, ylim=None):\n per_dict = {key: info[key] for key in ('project', 'experiment', 'run')}\n sasm_list = warehouse.get_sasprofile(**per_dict)\n if 'diff' in plot_type.lower():\n ref_sasm = sasm_list[ref_idx]\n else:\n ref_sasm = None\n\n xaxis = dict(title=XLABEL[xaxis_scale], type=xaxis_scale)\n yaxis = dict(title=YLABEL[plot_type])\n if xlim:\n xaxis['range'] = xlim\n if ylim:\n yaxis['range'] = ylim\n\n data = [{\n 'x': each_sasm.q,\n 'y': _CALC_FUNCTION[plot_type](each_sasm, ref_sasm),\n 'type': 'line',\n 'line': LINE_STYLE,\n 'name': each_sasm.get_parameter('filename'),\n } for each_sasm in sasm_list]\n\n return {\n 'data': data,\n 'layout': {\n 'height': 500,\n 'hovermode': 'closest',\n 'title': TITLE[plot_type],\n 'xaxis': xaxis,\n 'yaxis': yaxis,\n },\n }\n\n\n@dash_app.callback(\n Output('difference-graph', 'figure'),\n [\n Input('difference-plot-type', 'value'),\n Input('difference-ref-selection', 'value'),\n Input('difference-xaxis-scale', 'value'),\n Input('difference-xlim', 'value'),\n Input('difference-ylim', 'value'),\n Input('page-info', 'children'),\n ],\n)\ndef _update_figure(plot_type, ref_idx, xaxis_scale, xlim, ylim, info_json):\n info_dict = json.loads(info_json)\n return _get_figure(info_dict, plot_type, ref_idx, xaxis_scale, xlim, ylim)\n\n\n@dash_app.callback(\n Output('difference-ref-selection', 'options'),\n [Input('page-info', 'children')])\ndef _set_ref_options(info_json):\n info = json.loads(info_json)\n project, experiment, run = info['project'], info['experiment'], info['run']\n file_list = warehouse.get_files(project, experiment, run,\n 'subtracted_files')\n return [{\n 'label': os.path.basename(each),\n 'value': i,\n } for i, each in enumerate(file_list)]\n","repo_name":"lqhuang/SAS-dashboard","sub_path":"sasdash/dashboard/layouts/series_analysis.py","file_name":"series_analysis.py","file_ext":"py","file_size_in_byte":4515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"27087750081","text":"class Solution:\n def uniqueLetterString(self, s: str) -> int:\n index, rslt = {c:[-1, -1] for c in string.ascii_uppercase}, 0\n for i, c in enumerate(s):\n pre, last = index[c]\n rslt += (i-last)*(last-pre)\n index[c] = [last, i]\n n = len(s)\n for c in index:\n rslt += (n-index[c][1])*(index[c][1]-index[c][0])\n return rslt%(10**9+7)\n","repo_name":"Mela2014/lc_punch","sub_path":"lc828_twopointer.py","file_name":"lc828_twopointer.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32486410737","text":"# FTP Server was implmented by Kavilan Nair (1076342) \nimport socket\nimport threading\nimport os\nimport random\nimport platform\n\n# FTP server class that inherits from the threading module\nclass FTPServer (threading.Thread):\n def __init__(self, connection_socket, address_ip):\n threading.Thread.__init__(self)\n # initialise member variables to be used later in the codde\n self.command_connection = connection_socket\n self.data_connection = None\n self.address_ip = address_ip\n self.data_connection = None\n self.type = None\n self.isConnectionTerminated = False\n self.isActiveMode = None\n self.cwd = os.getcwd()\n self.user = ' '\n\n def run(self):\n print(\"Connection from: \", str(self.address_ip))\n self.command_connection.send('220 Welcome to the FTP server\\r\\n'.encode())\n # infinite for loop to continuously preceive commands from client\n while True:\n # commands available that have been implemented and can be used by a client\n commands_available = ['USER', 'PASS', 'PASV', 'LIST', 'PWD', 'CWD', 'TYPE', 'SYST', 'RETR', 'STOR', 'NOOP',\n 'QUIT', 'PORT', 'DELE', 'MKD', 'RMD', 'CDUP']\n\n if self.isConnectionTerminated:\n break\n\n # formatting of client commands to split into command and argument\n client_message = self.command_connection.recv(1024).decode()\n print(\"From connected client \" + self.user + \": \" + client_message)\n command = client_message[:4].strip()\n argument = client_message[4:].strip()\n\n if command in commands_available:\n # call function based off string supplied through client command\n ftp_command = getattr(self, command)\n\n if argument == '':\n ftp_command()\n else:\n ftp_command(argument)\n\n elif command not in commands_available:\n self.command_connection.send(\"502 Command not implemented \\r\\n\".encode())\n\n # Function to handle USER command\n def USER(self, argument):\n if argument == \"group18\" or argument == \"group19\":\n self.user = argument\n reply = \"331 Please Specify Password\\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n else:\n reply = \"530 Login incorrect\\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n self.command_connection.close()\n\n # Function to handle password associated with username\n def PASS(self, argument):\n if (self.user == \"group18\" and argument == \"dan\") or (self.user == \"group19\" and argument == \"mat\"):\n reply = \"230 Login successful\\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n else:\n reply = \"530 Login incorrect\\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n self.command_connection.close()\n\n # Function to handle passive connection from client\n def PASV(self):\n self.isActiveMode = False\n # Randomly generate port numbers for client to connect to\n port_number1 = random.randint(47, 234)\n port_number2 = random.randint(0, 255)\n server_address = socket.gethostbyname(socket.gethostname())\n # string manipulation to format in appropriate\n server_address = server_address.split(\".\")\n server_address = ','.join(server_address)\n server_address = \"(\" + server_address + \",\" + str(port_number1) + \",\" + str(port_number2) + \")\"\n data_port = (port_number1 * 256) + port_number2\n host = socket.gethostbyname(socket.gethostname())\n try:\n # Attempt to establish data connection\n self.data_connection = self.data_establish(host, data_port)\n reply = \"227 Entering passive mode\" + str(server_address) + '\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n except socket.error:\n reply = \"425 Cannot open Data connection \\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to handle active connection to client\n def PORT(self, argument):\n self.isActiveMode = True\n # string handling\n argument = argument.split(',')\n data_host = '.'.join(argument[0:4])\n port_number = argument[-2:]\n data_port = (int(port_number[0]) * 256) + int(port_number[1])\n data_port = int(data_port)\n self.data_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n # Attempt to establish data connection\n self.data_connection.connect((data_host, data_port))\n reply = \"225 Entering Active mode \\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n except socket.error:\n reply = \"425 Cannot open Data connection \\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to handle directory listing\n def LIST(self):\n reply = \"150 File status okay; about to open data connection.\\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n if not self.isActiveMode:\n data_sock, data_address = self.data_connection.accept()\n\n directory_list = os.listdir(self.cwd)\n for item in directory_list:\n # Uncomment to see what list contents are being sent\n # print('sending: ' + str(item))\n if not self.isActiveMode:\n data_sock.sendall((str(item) + '\\r\\n').encode())\n else:\n self.data_connection.sendall((str(item) + '\\r\\n').encode())\n\n reply = '226 Closing data connection. Requested transfer action successful\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n if not self.isActiveMode:\n data_sock.close()\n self.data_connection.close()\n\n # Function to obtain current working directory\n def PWD(self):\n reply = '257' + ' \"' + self.cwd + '\" ' + 'is the working directory\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to obtain change working directory\n def CWD(self, argument):\n path = argument\n self.cwd = self.cwd + '/' + str(path)\n if os.path.exists(self.cwd):\n reply = '250 Requested file action okay, completed.\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n else:\n reply = '550 Requested action not taken. File/Directory unavailable\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to choose ASCII or Binary mode\n def TYPE(self, argument):\n if argument == 'A':\n reply = '200 ASCII mode enabled\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n self.type = 'A'\n elif argument == 'I':\n reply = '200 binary mode enabled\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n self.type = 'I'\n else:\n reply = '501 Syntax error in parameters or arguments\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to obtain the operating system\n def SYST(self):\n reply = \"215 \" + platform.system() + \"\\r\\n\"\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to download file from server\n def RETR(self, argument):\n reply = '150 File status okay; about to open data connection.\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n if not self.isActiveMode:\n data_sock, data_address = self.data_connection.accept()\n filename = self.cwd + '/' + argument\n if self.type == 'A':\n file = open(filename, 'r')\n reading = file.read(8192)\n\n while reading:\n print('reading file')\n if not self.isActiveMode:\n data_sock.send((reading + '\\r\\n').encode())\n else:\n self.data_connection.send((reading + '\\r\\n').encode())\n reading = file.read(8192)\n\n file.close()\n if not self.isActiveMode:\n data_sock.close()\n self.data_connection.close()\n reply = '226 Closing data connection. Requested transfer action successful \\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n elif self.type == 'I':\n file = open(filename, 'rb')\n reading = file.read(8192)\n\n while reading:\n print('reading file')\n if not self.isActiveMode:\n data_sock.send(reading)\n else:\n self.data_connection.send(reading)\n\n reading = file.read(8192)\n\n file.close()\n if not self.isActiveMode:\n data_sock.close()\n self.data_connection.close()\n reply = '226 Closing data connection. Requested transfer action successful \\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n # should I close the data_connection\n\n # Function to upload file to server\n def STOR(self, argument):\n reply = '150 File status okay; about to open data connection.\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n if not self.isActiveMode:\n data_sock, data_address = self.data_connection.accept()\n filename = self.cwd + '/' + argument\n if self.type == 'A':\n file = open(filename, 'w')\n if not self.isActiveMode:\n file_data = data_sock.recv(8192).decode()\n else:\n file_data = self.data_connection.recv(8192).decode()\n\n while file_data:\n print('writing file')\n file.write(file_data)\n if not self.isActiveMode:\n file_data = data_sock.recv(8192).decode()\n else:\n file_data = self.data_connection.recv(8192).decode()\n\n file.close()\n if not self.isActiveMode:\n data_sock.close()\n self.data_connection.close()\n reply = '226 Closing data connection. Requested transfer action successful \\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n elif self.type == 'I':\n file = open(filename, 'wb')\n if not self.isActiveMode:\n file_data = data_sock.recv(8192)\n else:\n file_data = self.data_connection.recv(8192)\n\n while file_data:\n print('writing file')\n file.write(file_data)\n if not self.isActiveMode:\n file_data = data_sock.recv(8192)\n else:\n file_data = self.data_connection.recv(8192)\n\n file.close()\n if not self.isActiveMode:\n data_sock.close()\n self.data_connection.close()\n reply = '226 Closing data connection. Requested transfer action successful \\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n file.close()\n\n # Function to check if connection is still active\n def NOOP(self):\n reply = '200 NOOP OK \\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to delete specific file\n def DELE(self, argument):\n file_name = argument\n file_path = self.cwd + '/' + str(file_name)\n if os.path.exists(file_path):\n os.remove(file_path)\n reply = '250 Requested file action okay, completed.\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n else:\n reply = '550 Could not execute delete, file not found\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to obtain create a directory\n def MKD(self, argument):\n directory_name = argument\n directory_path = self.cwd + '/' + str(directory_name)\n if os.path.exists(directory_path):\n reply = '550 Requested action not taken. File/Directory unavailable\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n else:\n os.makedirs(directory_path)\n reply = '257 Folder has been successfully created\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to delete specified working directory\n def RMD(self, argument):\n directory_name = argument\n directory_path = self.cwd + '/' + str(directory_name)\n if os.path.exists(directory_name):\n os.rmdir(directory_path)\n reply = '250 Requested file action okay, completed. \\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n else:\n reply = '550 Requested action not taken. File/Directory unavailable\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to change to parent directory\n def CDUP(self):\n print('Here')\n print(self.cwd)\n parent_directory = self.cwd.split('/')\n parent_directory = parent_directory[:-1]\n parent_directory = '/'.join(parent_directory)\n print(parent_directory)\n\n if os.path.exists(parent_directory):\n self.cwd = parent_directory\n reply = '200 Changed directory successfully \\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n else:\n reply = '550 Requested action not taken. File/Directory unavailable\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n\n # Function to end FTP session\n def QUIT(self):\n reply = '221 Goodbye\\r\\n'\n print('Response sent to connected client ' + self.user + ': ' + reply)\n self.command_connection.send(reply.encode())\n self.command_connection.close()\n self.isConnectionTerminated = True\n\n # establish data connection in passive mode\n def data_establish(self, host, port):\n data_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n data_socket.bind((host, port))\n data_socket.listen(5)\n return data_socket\n\n\ndef main():\n # Local Machine IP and port\n host = socket.gethostbyname(socket.gethostname())\n port = 6000\n\n server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server_socket.bind((host, port))\n print('FTP Server initialized at ' + host)\n print(\"Awaiting a connection from a client\")\n\n # infinite loop to accept multiple client conenction and run them in separate threads\n while True:\n server_socket.listen(1)\n connection_socket, address_ip = server_socket.accept()\n thread = FTPServer(connection_socket, address_ip)\n thread.start()\n\nif __name__ == '__main__':\n main()","repo_name":"NetworkFundamentalsELEN4017/FTP-Project","sub_path":"FTP_Server.py","file_name":"FTP_Server.py","file_ext":"py","file_size_in_byte":17375,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"26697718968","text":"room = \"start\"\nkey = False\nlooked = False\n\nwhile room != \"end\":\n if room == \"start\":\n print(\"Actions available: forward, look\")\n action = input(\"> \")\n if action == \"forward\":\n room = \"middle\"\n\n elif room == \"middle\":\n if looked == True:\n print(\"Actions available: forward, backward, look, pickup\")\n else:\n print(\"Actions available: forward, backward, look\")\n action = input(\"> \")\n if action == \"forward\":\n if key == True:\n room = \"end\"\n else:\n print(\"The door is locked.\")\n elif action == \"backward\":\n room = \"start\"\n elif action == \"look\":\n print(\"You spot a key on the floor.\")\n looked = True\n elif action == \"pickup\":\n print(\"You picked up the key!\")\n key = True\n\n if room == \"start\":\n print(\"You are standing in the entrace to the castle. There is no exit.\")\n elif room == \"middle\":\n print(\"You are in the middle room of the castle.\")\nprint(\"You have unlocked the door and escaped the castle. You win!\")\n","repo_name":"computingacademy/tcc-webinar-two","sub_path":"castle-game/castle.py","file_name":"castle.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6171743844","text":"from tkinter import *\nimport tkinter.messagebox\nmain_window=Tk()\nmain_window.title(\"Tic-Tac-Toe\")\nmain_window.geometry(\"540x590\")\nmain_window.resizable(False, False)\nk=1\ncount=0\nmy_font=('Segoe UI Historic',11,'bold')\nmy_font1=('Adobe Hebrew',10,'bold')\ndef clearbuttons():\n B1['text']=''\n B1.configure(bg='SystemButtonFace')\n B2['text']=''\n B2.configure(bg='SystemButtonFace')\n B3['text']=''\n B3.configure(bg='SystemButtonFace')\n B4['text']=''\n B4.configure(bg='SystemButtonFace')\n B5['text']=''\n B5.configure(bg='SystemButtonFace')\n B6['text']=''\n B6.configure(bg='SystemButtonFace')\n B7['text']=''\n B7.configure(bg='SystemButtonFace')\n B8['text']=''\n B8.configure(bg='SystemButtonFace')\n B9['text']=''\n B9.configure(bg='SystemButtonFace')\ndef checking():\n global k,count\n if((B1['text']=='X' and B2['text']=='X' and B3['text']=='X') or (B2['text']==\"X\" and B5['text']=='X' and B8['text']=='X')\n or (B1['text']=='X' and B4['text']=='X' and B7['text']=='X') or (B3['text']=='X'and B6['text']=='X' and B9['text']=='X')\n or (B1['text']=='X' and B5['text']=='X' and B9['text']=='X') or (B3['text']=='X'and B5['text']=='X' and B7['text']=='X')\n or (B4['text']=='X' and B5['text']=='X' and B6['text']=='X') or (B7['text']=='X'and B8['text']=='X' and B9['text']=='X')):\n tkinter.messagebox.showinfo(\"Tic-Tac-Toe\",\"Congrats!! X IS THE WINNER\")\n k=1\n count=0\n clearbuttons()\n elif((B1['text']=='O' and B2['text']=='O' and B3['text']=='O') or (B2['text']==\"O\" and B5['text']=='O' and B8['text']=='O')\n or (B1['text']=='O' and B4['text']=='O' and B7['text']=='O') or (B3['text']=='O'and B6['text']=='O' and B9['text']=='O')\n or (B1['text']=='O' and B5['text']=='O' and B9['text']=='O') or (B3['text']=='O'and B5['text']=='O' and B7['text']=='O')\n or (B4['text']=='O' and B5['text']=='O' and B6['text']=='O') or (B7['text']=='O'and B8['text']=='O' and B9['text']=='O')):\n tkinter.messagebox.showinfo(\"Tic-Tac-Toe\", \"Congrats!! O IS THE WINNER\")\n k=1\n count=0\n clearbuttons()\n elif(count==9):\n tkinter.messagebox.showinfo(\"Tic-Tac-Toe\", \"Oh!! Its a Tie Game\")\n k=1\n count=0\n clearbuttons()\ndef cliking(B):\n global k,count\n if(B['text']==''):\n if(k):\n B['text']='X'\n k=0\n count=count+1\n B.configure(bg='#63f2eb')\n else:\n B['text']='O'\n k=1\n count=count+1\n B.configure(bg='#FF69B4')\n if(count>=5):\n checking()\nB1=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B1),font=my_font)\nB2=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B2),font=my_font)\nB3=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B3),font=my_font)\nB4=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B4),font=my_font)\nB5=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B5),font=my_font)\nB6=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B6),font=my_font)\nB7=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B7),font=my_font)\nB8=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B8),font=my_font)\nB9=Button(main_window,text=\"\",height=8,width=19,command=lambda:cliking(B9),font=my_font)\nB1.grid(row=0,column=0)\nB2.grid(row=0,column=1)\nB3.grid(row=0,column=2)\nB4.grid(row=1,column=0)\nB5.grid(row=1,column=1)\nB6.grid(row=1,column=2)\nB7.grid(row=2,column=0)\nB8.grid(row=2,column=1)\nB9.grid(row=2,column=2)\nLabel(main_window,text=\"Player 1 is X,Player 2 is O\",font=my_font1).grid(row=4,column=1)\nend=Button(main_window,text=\"End Game\",command=main_window.destroy,bg='orange',font=my_font)\nend.grid(row=5,column=1)\nmain_window.mainloop()","repo_name":"SurajKumar-27/Tic-tac-toe","sub_path":"tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"32141894240","text":"from urllib.error import HTTPError\nfrom urllib.request import Request, urlopen\nfrom urllib.parse import urljoin\nfrom cgi import parse_header\nimport json\nfrom django.conf import settings\nfrom rest_framework import authentication\nfrom rest_framework import exceptions\nfrom rest_framework.authentication import get_authorization_header\n\n\nclass User(object):\n def __init__(self, id):\n self.__id = id\n\n def get_id(self):\n return self.__id\n\n def is_authenticated(self):\n return True\n\n def __str__(self):\n return \"User \" + str(self.__id)\n\n\nclass PolicyCompassAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n token = self.__get_token(request)\n if token:\n return User(token), None\n else:\n return None\n\n def __get_token(self, request):\n auth = get_authorization_header(request).split()\n\n if not auth or auth[0].lower() != b'token':\n return None\n\n if len(auth) == 1:\n msg = 'Invalid token header. No credentials provided.'\n raise exceptions.AuthenticationFailed(msg)\n\n elif len(auth) > 2:\n msg = 'Invalid token header. Token string should not contain spaces.'\n raise exceptions.AuthenticationFailed(msg)\n\n return auth[1]\n\n\nclass AdhocracyUser:\n def __init__(self, user_ressource_path, is_admin=False):\n self.resource_path = user_ressource_path\n self.is_admin = is_admin\n self.is_staff = False\n self.is_superuser = is_admin\n self.user_permissions = []\n self.groups = []\n\n def get_username(self):\n return self.resource_path\n\n def is_authenticated(self):\n return True\n\n def get_all_permissions(self):\n return self.user_permissions\n\n def set_password(self, _password):\n raise NotImplementedError\n\n def check_password(self, _password):\n raise NotImplementedError\n\n def save(self):\n raise NotImplementedError\n\n def delete(self):\n raise NotImplementedError\n\n def __repr__(self):\n return \"AdhocracyUser('%s', is_admin=%r)\" % (self.resource_path, self.is_admin)\n\n\nclass AdhocracyAuthentication(authentication.BaseAuthentication):\n def authenticate(self, request):\n adhocracy_base_url = settings.PC_SERVICES['references'][\n 'adhocracy_api_base_url']\n user_path = request.META.get('HTTP_X_USER_PATH')\n user_token = request.META.get('HTTP_X_USER_TOKEN')\n user_url = urljoin(adhocracy_base_url, user_path)\n\n if user_path is None and user_token is None:\n return None\n elif user_path is None or user_token is None:\n raise exceptions.AuthenticationFailed(\n 'No `X-User-Path` and `X-User-Token` header provided.')\n\n request = Request(user_url)\n request.add_header('X-User-Path', user_url)\n request.add_header('X-User-Token', user_token)\n\n try:\n response = urlopen(request)\n\n content_type, params = parse_header(\n response.getheader(\"content-type\"))\n encoding = params['charset'].lower()\n if content_type != \"application/json\":\n exceptions.AuthenticationFailed(\n 'Adhocracy authentication failed due to wrong response.')\n resource_as_string = response.read().decode(encoding)\n user_resource = json.loads(resource_as_string)\n roles = user_resource['data'][\n 'adhocracy_core.sheets.principal.IPermissions']['roles']\n\n is_admin = 'admin' in roles\n return (AdhocracyUser(user_path, is_admin), None)\n\n except HTTPError as e:\n if (e.code == 400):\n raise exceptions.AuthenticationFailed(\n 'Adhocracy authentication failed due to invalid credentials.')\n else:\n raise\n","repo_name":"policycompass/policycompass-services","sub_path":"policycompass_services/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"32005761533","text":"import numpy as np\nimport tensorflow as tf\nfrom tensorflow import keras\nimport logging\nimport datetime\nfrom spiro.core.backends import TENSORFLOW\nfrom spiro.core.config import set_backend\nset_backend(TENSORFLOW)\nfrom spiro.dtdg.dataloader import ogb_dataset, supported_ogb_datasets\nfrom spiro.dtdg.models.encoder.implicitTimeEncoder.staticGraphEncoder import GCN, SGCN, GAT, GraphSage\nfrom spiro.dtdg.models.decoder.sequentialDecoders import SelfAttention, PTSA, FTSA, Conv1D, NodeTrackingPTSA\nfrom spiro.dtdg.models.decoder.simpleDecoders import MLP\nfrom spiro.core.commonF import to_tensor\nfrom spiro.core.utils import printProgressBar\nfrom spiro.automl.model_assembler import assembler\nfrom spiro.automl.tf.prepare_dataset import prepare_citation_task, TARGET, LABEL\nfrom spiro.automl.tf.batch_training import NodeBatchGenerator\n\n\n\"\"\"\ndef loss_fn(predict, label):\n return torch.sqrt(torch.mean(torch.abs(torch.log1p(predict) - torch.log1p(label))))\n\"\"\"\nif __name__ == '__main__':\n #----------------------------------------------------------------\n data_to_test = supported_ogb_datasets()[1]\n this_graph = ogb_dataset(data_to_test)\n n_snapshot = len(this_graph)\n n_nodes = this_graph.dispatcher(n_snapshot -1)[0].observation.num_nodes()\n this_snapshot,_ = this_graph.dispatcher(20)\n in_dim = this_snapshot.num_node_features()\n hidden_dim = 32\n num_GNN_layers = 2\n num_RNN_layers = 3\n output_dim = 10\n layer_dims = [64,output_dim]\n activation_f = None\n encoders = ['gcn', 'sgcn', 'gat', 'sage']\n decoders = ['sa', 'ptsa', 'node_tracking_ptsa', 'tsa_sum', 'node_tracking_tsa', 'conv1d']\n epochs = 1000\n prepare_citation_task(this_graph)\n for g in range(1):\n for r in range(6):\n #set up logger\n this_logger = logging.getLogger('citation_predictoin_pipeline')\n this_logger.setLevel(logging.INFO)\n # create file handler which logs even debug messages\n log_path = f\"model_{encoders[g]}_{decoders[r]}.log\"\n fh = logging.FileHandler(log_path)\n fh.setLevel(logging.DEBUG)\n for hdlr in this_logger.handlers[:]: # remove all old handlers\n this_logger.removeHandler(hdlr)\n this_logger.addHandler(fh)\n this_logger.info(\"--------------------------------------------------------\")\n for trial in range(10):\n this_logger.info(\"--------------------------------------------------------\")\n this_logger.info(f\"start trial {trial}\")\n if g == 0:\n gnn = GCN(num_GNN_layers, in_dim, hidden_dim, activation=None,norm='none', allow_zero_in_degree=True, dropout=0.2)\n elif g == 1:\n gnn = SGCN(num_GNN_layers, in_dim, hidden_dim ,allow_zero_in_degree=True)\n elif g == 2:\n gnn = GAT([1], in_dim, hidden_dim, activation=activation_f,allow_zero_in_degree=True)\n else:\n gnn = GraphSage('gcn', in_dim, hidden_dim, activation=activation_f)\n\n output_decoder = MLP(output_dim, [hidden_dim,20,10,5], activation=\"linear\")\n \n if r == 0:\n sa = SelfAttention( 3, hidden_dim, [8,output_dim], n_nodes, 5, output_decoder)\n elif r == 1:\n sa = PTSA( 3, hidden_dim,layer_dims , n_nodes, 5, output_decoder)\n elif r == 2:\n sa = NodeTrackingPTSA( 3, hidden_dim,layer_dims , n_nodes, 5, output_decoder)\n elif r == 3:\n sa = FTSA( 3, hidden_dim, layer_dims, n_nodes, 5,3,'sum', output_decoder)\n elif r == 4:\n sa = FTSA( 3, hidden_dim, layer_dims, n_nodes, 5,3,'sum', output_decoder, node_tracking=True)\n elif r == 5:\n sa = Conv1D(hidden_dim, [8,output_dim], n_nodes, 5, output_decoder)\n else:\n pass\n\n\n this_model = assembler(gnn, sa)\n save_path = f\"model_{encoders[g]}_{decoders[r]}_{trial}\"\n loss_fn_eval = keras.losses.MeanSquaredError()\n loss_fn = keras.losses.MeanAbsolutePercentageError()\n loss_list=[]\n all_predictions=[]\n eval_loss = []\n eval_predictions = []\n eval_loss2 = []\n eval_predictions2= []\n lr = 1e-3\n optimizer = keras.optimizers.Adam(learning_rate=lr, epsilon=1e-8)\n batch_size = 5000\n batchs = NodeBatchGenerator(this_graph, 40, 10, n_snapshot-2)\n eval_batchs = NodeBatchGenerator(this_graph, 40, n_snapshot-2, n_snapshot-1)\n total_batches = len(batchs)\n for epoch in range(epochs):\n this_model.decoder.training()\n this_model.decoder.memory.reset_state()\n progress = 0\n printProgressBar(progress, total_batches, prefix = 'Progress:', suffix = 'Complete', length = 50)\n for snapshot, target, label in batchs:\n with tf.GradientTape() as tape:\n predict = tf.reshape(this_model((snapshot,target), training=True), (-1))\n all_predictions.append(predict.numpy())\n loss = loss_fn(label,predict)\n grads = tape.gradient(loss, this_model.trainable_weights)\n optimizer.apply_gradients(zip(grads, this_model.trainable_weights))\n loss_list.append(loss.numpy())\n progress+=1\n printProgressBar(progress, total_batches, prefix = 'Progress:', suffix = 'Complete', length = 50)\n print(f\"train loss: {loss_list[-1]}\")\n eval_t = n_snapshot - 2\n predicts = np.array([])\n labels = np.array([])\n for snapshot, target, label in eval_batchs:\n predicts = tf.experimental.numpy.hstack((predicts,tf.reshape(this_model((snapshot,target)),(-1))))\n labels = tf.experimental.numpy.hstack((labels, label))\n eval_predictions.append(predicts)\n print(eval_predictions[-1][:20])\n print(labels[:20])\n test_loss = loss_fn(labels, predicts).numpy()\n print(f\"test loss:{test_loss}\")\n eval_loss.append(test_loss)\n test_loss_2 = loss_fn_eval(labels, predicts).numpy()\n eval_loss2.append(test_loss_2)\n print(f\"eval loss: {test_loss_2}\")\n mini = min(eval_loss)\n batchs.on_epoch_end()\n eval_batchs.on_epoch_end()\n if eval_loss[-1] == mini:\n print(f\"save best model for loss {mini}\")\n this_model.save_model(save_path)\n if epoch > 10:\n if all(eval_loss[-40:] > mini):\n print(mini)\n break\n\n this_logger.info(loss_list)\n this_logger.info(eval_loss)\n this_logger.info(eval_loss2)\n this_logger.info(f\"best loss {mini}\")\n\n\"\"\"\n gnn = GCN(num_GNN_layers, in_dim, hidden_dim, activation=activation_f, allow_zero_in_degree=True, dropout=0.2)\n output_decoder = MLP(output_dim, [hidden_dim,20,10,5])\n decoder = FTSA( 3, hidden_dim, [8], n_nodes, 7,3,'sum', output_decoder)\n new_model = assembler(gnn, decoder)\n new_snapshot = this_graph.dispatcher(n_snapshot-2)\n next_snapshot = this_graph.dispatcher(n_snapshot-1)\n node_samples = np.arange(this_snapshot.num_nodes())\n new_predict = new_model((this_snapshot, node_samples))\n new_model.load_model(save_path)\n new_model.decoder.memory.reset_state()\n for t in range(1,n_snapshot-2):\n this_snapshot = this_graph.dispatcher(t)\n next_snapshot = this_graph.dispatcher(t+1)\n node_samples = np.arange(this_snapshot.num_nodes())\n predict = new_model((this_snapshot,node_samples))\n label = next_snapshot.node_feature()[:this_snapshot.num_nodes(), -1]\n all_predictions.append(tf.squeeze(predict).numpy())\n loss = loss_fn(tf.squeeze(predict), label)\n loss_list.append(loss.numpy())\n print(loss_list[-1])\n\n this_snapshot = this_graph.dispatcher(n_snapshot-2)\n next_snapshot = this_graph.dispatcher(n_snapshot-1)\n node_samples = np.arange(this_snapshot.num_nodes())\n predict = new_model((this_snapshot,node_samples))\n label = next_snapshot.node_feature()[:this_snapshot.num_nodes(), -1]\n eval_predictions.append(tf.squeeze(predict).numpy())\n loss = loss_fn(tf.squeeze(predict), label)\n eval_loss.append(loss.numpy())\n print(eval_loss[-1])\n\"\"\"\n","repo_name":"mcgill-cpslab/spiral","sub_path":"examples/tf/citation_prediction_sliding_window_decoder_batch.py","file_name":"citation_prediction_sliding_window_decoder_batch.py","file_ext":"py","file_size_in_byte":9000,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"38001491648","text":"\"\"\"\nLoop while\n\nwhile expressao_booleana:\n //loop\n //incremento(ou decremento)\n\nenquanto for true, ele vai continuar rodando\n\nOBS: sempre se ligar no criterio de parada, senao vira um loop infinito...\n\nBreak\n\nutilizamos break para sair de um loop de maneira projetada\n\n\n\"\"\"\n\nn = 0\nwhile n < 5:\n print(n)\n n = n+1\nprint('')\nv = ''\nwhile v != 'sim':\n v = input('Ja acabou, jessica? ')\n\nc = 0\nwhile c < 10:\n c += 1\n if c == 7:\n break\n else:\n print(c)\nprint('sai do loop')\n","repo_name":"JorgeRoniel/Curso-de-Python","sub_path":"seção_6/loop_while.py","file_name":"loop_while.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"37526273556","text":"###############################\n##\n## HASH CODE ENTRY\n##\n## Usage: python main.py \n##\n###############################\nimport sys\nimport os\nimport math\nfrom .utils.car import Car\nfrom .utils.street import Street\nfrom .utils.intersection import Intersection\n\ndef main(file_location, output_location):\n print(\"Running Hash Code Entry\")\n # Hash Code here :)\n\n input_file = open(file_location, \"r\")\n\n line_num = 0\n duration = 0\n num_intersections = 0\n num_streets = 0\n num_cars = 0\n bonus = 0\n intersections = []\n streets = []\n cars = []\n for line in input_file:\n if line_num == 0:\n numbers = line.split(\" \")\n duration = int(numbers[0])\n num_intersections = int(numbers[1])\n num_streets = int(numbers[2])\n num_cars = int(numbers[3])\n bonus = int(numbers[4])\n intersections = create_intersections(num_intersections)\n elif line_num <= num_streets:\n street_info = line.split(\" \")\n a_street = Street(street_info[2], int(street_info[3]))\n streets.append(a_street)\n intersections[int(street_info[1])].add_incoming_street(a_street)\n else:\n car_info = line.split(\" \")\n cars.append(Car(int(car_info[0]), car_info[1:]))\n line_num += 1\n input_file.close()\n print(f\"Created {len(intersections)} intersections\")\n print(f\"Created {len(streets)} streets\")\n print(f\"Created {len(cars)} cars\")\n\n # Check street usage\n add_street_usage(cars, streets, file_location)\n\n # Check inter usage\n used_intersections = list(filter(lambda x: x.ever_used(), intersections))\n \n # Output\n output_file = open(output_location, \"w\")\n output_file.write(f\"{str(len(used_intersections))}\\n\")\n for inter in used_intersections:\n output_file.write(f\"{str(inter.id)}\\n\")\n used_streets = list(filter(lambda x: x.usage > 0, inter.incoming_streets))\n output_file.write(f\"{str(len(used_streets))}\\n\")\n\n used_streets.sort(key=lambda x: x.starting_cars, reverse=True)\n total_inter_usage = 0\n for street in used_streets:\n total_inter_usage += street.usage\n\n t = duration / 214\n for street in used_streets:\n fraction = street.usage / total_inter_usage\n green_time = max(1, math.floor(t * fraction))\n output_file.write(f\"{street.name} {green_time}\\n\")\n\n output_file.close()\n\n\n\ndef create_intersections(num):\n intersections = []\n for i in range(num):\n intersections.append(Intersection(i))\n return intersections\n\n\ndef add_street_usage(cars, streets, file_location):\n head_tail = os.path.split(file_location) \n file_name = os.path.join(\".\\cache\", head_tail[1])\n\n if os.path.isfile(file_name):\n print(\"Using Cache\")\n input_file = open(file_name, \"r\")\n count = 0\n for line in input_file:\n values = line.split(\" \")\n streets[count].set_usage(int(values[0]))\n streets[count].set_starting_cars(int(values[1]))\n count += 1\n else:\n print(\"Writing Cache\")\n for a_car in cars:\n first = True\n for street_name in a_car.roads:\n for a_street in streets:\n if a_street.name == street_name:\n a_street.add_usage()\n if first:\n a_street.add_starting_cars()\n break\n first = False\n\n # Write street usage to file as cache\n output_file = open(file_name, \"w\")\n for s in streets:\n output_file.write(f\"{s.usage} {s.starting_cars}\\n\")\n\n\n# When run from the terminal\nif __name__ == '__main__':\n main(sys.argv[1], sys.argv[2])","repo_name":"hexmod/hash-code-2021","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"17330746297","text":"import os\nimport numpy as np\nimport peewee\nimport astropy.io.ascii\nimport sdssdb.peewee.sdss5db.targetdb as targetdb\nimport sdssdb.peewee.sdss5db.catalogdb as catalogdb\n\nfrom sdssdb.peewee.sdss5db import database\ndatabase.set_profile('operations')\n\ntarget_dtype = [('stage', np.unicode_, 6),\n ('rsid', np.int64), # set equal to carton_to_target_pk\n ('carton_to_target_pk', np.int64), # from carton_to_target\n ('priority', np.int32),\n ('value', np.float32),\n ('lambda_eff', np.float32),\n ('delta_ra', np.float64),\n ('delta_dec', np.float64),\n ('can_offset', bool),\n ('ra', np.float64), # from target\n ('dec', np.float64),\n ('epoch', np.float32),\n ('pmra', np.float32),\n ('pmdec', np.float32),\n ('parallax', np.float32),\n ('catalogid', np.int64),\n ('catalogdb_plan', str, 12),\n ('target_pk', np.int64),\n ('magnitude', np.float32, 10), # from magnitude\n ('carton', np.unicode_, 60), # from carton\n ('carton_pk', np.int32),\n ('program', np.unicode_, 15), \n ('mapper', np.unicode_, 3), # from mapper\n ('category', np.unicode_, 15), # from category\n ('cadence', np.unicode_, 26), # from cadence\n ('fiberType', np.unicode_, 6), # from instrument\n ('plan', np.unicode_, 8), # from version\n ('tag', np.unicode_, 8)]\n\n\ndef read_cartons(version=None, filename=None):\n \"\"\"Read in cartons\n\n Parameters\n ----------\n\n version : str\n version of carton file\n\n filename : str\n explicit file name of carton file\n\n Returns\n -------\n\n cartons : Table\n table with carton information\n\n\n Notes\n -----\n\n Reads file as fixed_width, |-delimited file with astropy.io.ascii\n\n If filename is specified, reads in that file.\n\n If not, and version is specified, reads in $RSCONFIG_DIR/etc/cartons-[version].txt\n\"\"\"\n if((version is None) and (filename is None)):\n print(\"Must specify either version or filename!\")\n return\n\n if(filename is None):\n filename = os.path.join(os.getenv('RSCONFIG_DIR'),\n 'etc', 'cartons-{version}.txt')\n filename = filename.format(version=version)\n\n cartons = astropy.io.ascii.read(filename, format='fixed_width',\n delimiter='|')\n return(cartons)\n\n\ndef get_targets(carton=None, version=None, justcount=False, c2c=None):\n \"\"\"Pull targets from the targetdb\n\n Parameters\n ----------\n\n cartons : str\n label of carton to pull\n\n version : str\n plan of carton to pull\n\n justcount : bool\n if True, just return the count (default False)\n\n c2c : config\n if not None, maps cartons to fiber type and cadences (default None)\n\"\"\"\n if(justcount):\n print(\"Counting carton {p}, version {v}\".format(p=carton,\n v=version))\n else:\n print(\"Extracting carton {p}, version {v}\".format(p=carton,\n v=version))\n\n # First look at all targets in this carton/version\n ntall = (targetdb.Target.select(targetdb.Target.pk)\n .join(targetdb.CartonToTarget)\n .join(targetdb.Carton)\n .join(targetdb.Version)\n .where((targetdb.Carton.carton == carton) &\n (targetdb.Version.plan == version))).count()\n\n if(justcount):\n print(\" ... {ntall} targets\".format(ntall=ntall), flush=True)\n return(ntall)\n\n # Now look at those with a cadence, instrument, and magnitude not null\n nt = (targetdb.Target.select(targetdb.Target.pk)\n .join(targetdb.CartonToTarget)\n .join(targetdb.Instrument, peewee.JOIN.LEFT_OUTER).switch(targetdb.CartonToTarget)\n .join(targetdb.Cadence, peewee.JOIN.LEFT_OUTER).switch(targetdb.CartonToTarget)\n .join(targetdb.Magnitude, peewee.JOIN.LEFT_OUTER).switch(targetdb.CartonToTarget)\n .join(targetdb.Carton)\n .join(targetdb.Version)\n .where((targetdb.Carton.carton == carton) &\n (targetdb.Version.plan == version))).count()\n\n if(nt != ntall):\n print(\"WARNING: only {nt} of {ntall} targets in carton {carton} have cadence, instrument, and magnitude non-null\".format(nt=nt, ntall=ntall, carton=carton))\n\n print(\" ... {nt} targets\".format(nt=nt), flush=True)\n tmp_targets = None\n if(nt > 0):\n tmp_targets = np.zeros(nt, dtype=target_dtype)\n\n ts = (targetdb.Target.select(targetdb.Target.ra,\n targetdb.Target.dec,\n targetdb.Target.pmra,\n targetdb.Target.pmdec,\n targetdb.Target.epoch,\n targetdb.Target.parallax,\n targetdb.Target.pk.alias('target_pk'),\n targetdb.Target.catalogid,\n targetdb.CartonToTarget.pk.alias('carton_to_target_pk'),\n targetdb.CartonToTarget.priority,\n targetdb.CartonToTarget.value,\n targetdb.CartonToTarget.lambda_eff,\n targetdb.CartonToTarget.delta_ra,\n targetdb.CartonToTarget.delta_dec,\n targetdb.CartonToTarget.can_offset,\n targetdb.Magnitude.g,\n targetdb.Magnitude.r,\n targetdb.Magnitude.i,\n targetdb.Magnitude.bp,\n targetdb.Magnitude.gaia_g,\n targetdb.Magnitude.rp,\n targetdb.Magnitude.h,\n targetdb.Magnitude.z,\n targetdb.Magnitude.j,\n targetdb.Magnitude.k,\n targetdb.Carton.carton,\n targetdb.Carton.pk.alias('carton_pk'),\n targetdb.Carton.program,\n targetdb.Mapper.label.alias('mapper'),\n targetdb.Category.label.alias('category'),\n targetdb.Cadence.label_root.alias('cadence'),\n targetdb.Instrument.label.alias('fiberType'),\n catalogdb.Version.plan.alias('catalogdb_plan'),\n targetdb.Version.plan,\n targetdb.Version.tag)\n .join(targetdb.CartonToTarget)\n .join(targetdb.Instrument, peewee.JOIN.LEFT_OUTER).switch(targetdb.CartonToTarget)\n .join(targetdb.Cadence, peewee.JOIN.LEFT_OUTER).switch(targetdb.CartonToTarget)\n .join(targetdb.Magnitude, peewee.JOIN.LEFT_OUTER).switch(targetdb.CartonToTarget)\n .join(targetdb.Carton)\n .join(targetdb.Mapper, peewee.JOIN.LEFT_OUTER).switch(targetdb.Carton)\n .join(targetdb.Version).switch(targetdb.Carton)\n .join(targetdb.Category).switch(targetdb.Target)\n .join(catalogdb.Catalog, on=(catalogdb.Catalog.catalogid == targetdb.Target.catalogid))\n .join(catalogdb.Version)\n .where((targetdb.Carton.carton == carton) &\n (targetdb.Version.plan == version))).dicts()\n\n castn = dict()\n for n in tmp_targets.dtype.names:\n castn[n] = np.cast[type(tmp_targets[n][0])]\n \n problems = []\n for indx, t in enumerate(ts):\n for n in tmp_targets.dtype.names:\n if((n != 'rsid') & (n != 'stage') & (n != 'magnitude')):\n if(t[n] is not None):\n tmp_targets[n][indx] = castn[n](t[n])\n else:\n if(n not in problems):\n print(\"problem with {n}\".format(n=n))\n problems.append(n)\n elif(n == 'magnitude'):\n tmp_targets['magnitude'][indx, 0] = np.float32(t['g'])\n tmp_targets['magnitude'][indx, 1] = np.float32(t['r'])\n tmp_targets['magnitude'][indx, 2] = np.float32(t['i'])\n tmp_targets['magnitude'][indx, 3] = np.float32(t['z'])\n tmp_targets['magnitude'][indx, 4] = np.float32(t['bp'])\n tmp_targets['magnitude'][indx, 5] = np.float32(t['gaia_g'])\n tmp_targets['magnitude'][indx, 6] = np.float32(t['rp'])\n tmp_targets['magnitude'][indx, 7] = np.float32(t['j'])\n tmp_targets['magnitude'][indx, 8] = np.float32(t['h'])\n tmp_targets['magnitude'][indx, 9] = np.float32(t['k'])\n\n tmp_targets['rsid'] = tmp_targets['carton_to_target_pk']\n\n if(c2c is not None):\n inofibertype = np.where(tmp_targets['fiberType'] == '')[0]\n if(len(inofibertype) > 0):\n msg = \"WARNING: {n} targets in {c} with no fiberType\".format(n=len(inofibertype), c=carton)\n if(carton in c2c['CartonToFiberType']):\n fiberType = c2c.get('CartonToFiberType', carton)\n print(\"{msg}, SETTING TO {fiberType}\".format(msg=msg, fiberType=fiberType))\n tmp_targets['fiberType'][inofibertype] = fiberType\n else:\n print(\"{msg}, NOT FIXING\".format(msg=msg))\n\n inocadence = np.where(tmp_targets['cadence'] == '')[0]\n if(len(inocadence) > 0):\n msg = \"WARNING: {n} targets in {c} with no cadence\".format(n=len(inocadence), c=carton)\n if(carton in c2c['CartonToCadence']):\n cadence = c2c.get('CartonToCadence', carton)\n print(\"{msg}, SETTING TO {cadence}\".format(msg=msg, cadence=cadence))\n tmp_targets['cadence'][inocadence] = cadence\n if(cadence == 'dark_174x8'):\n ii = np.where((np.abs(tmp_targets['ra'][inocadence] - 90.) < 6.) &\n (np.abs(tmp_targets['dec'][inocadence] + 66.56) < 2.))[0]\n if(len(ii) > 0):\n tmp_targets['cadence'][inocadence[ii]] = 'dark_100x8'\n else:\n print(\"{msg}, NOT FIXING\".format(msg=msg))\n\n return(tmp_targets)\n\n\ndef match_v1_to_v0p5(catalogids_v1=None, all=False):\n \"\"\"Find catalogids in v0.5 corresponding to v1\n \n Parameters\n ----------\n\n catalogids_v1 : ndarray of np.int64\n input catalogids in v1\n\n all : bool\n if set True, return all v0.5 catalogids (not just one)\n\n Returns\n -------\n\n catalogids_v1 : ndarray of np.int64\n catalogids in v1\n\n catalogids_v0p5 : ndarray of np.int64\n catalogids in v0.5 (-1 if not found)\n\n Notes\n -----\n\n If all is False, then the two arrays are in the same\n order as the input list, and have the same length.\n\n If all is True, then only matches are included in the \n output lists, and repeats are included\n\n Hard-coded between these two versions because the db\n has the version names hard-coded into tables\n\"\"\"\n if(len(catalogids_v1) == 0):\n return(np.zeros(0, dtype=np.int64),\n np.zeros(0, dtype=np.int64))\n \n # Construct query\n sql_template = \"\"\"SELECT catalogid1, catalogid2 FROM catalogdb.catalog_ver25_to_ver31_full_unique JOIN (VALUES {v}) AS ver31(catalogid) ON catalogdb.catalog_ver25_to_ver31_full_unique.catalogid2 = ver31.catalogid;\n\"\"\"\n values = \"\"\n ucatalogids_v1 = np.unique(catalogids_v1)\n for value in ucatalogids_v1:\n values = values + \"({v}),\".format(v=value)\n values = values[0:-1]\n sql_command = sql_template.format(v=values)\n\n if(all is False):\n # Set up output\n out_catalogids_v1 = catalogids_v1\n out_catalogids_v0p5 = np.zeros(len(catalogids_v1), dtype=np.int64) - 1\n indxs = dict()\n for cid_v1 in ucatalogids_v1:\n indxs[cid_v1] = np.where(catalogids_v1 == cid_v1)[0]\n\n # Run query\n cursor = database.execute_sql(sql_command)\n for row in cursor.fetchall():\n catalogid_v1 = row[1]\n catalogid_v0p5 = row[0]\n out_catalogids_v0p5[indxs[catalogid_v1]] = catalogid_v0p5\n else:\n cursor = database.execute_sql(sql_command)\n out_catalogids_v1 = np.zeros(len(catalogids_v1), dtype=np.int64)\n out_catalogids_v0p5 = np.zeros(len(catalogids_v1), dtype=np.int64)\n i = 0\n for row in cursor.fetchall():\n out_catalogids_v1[i] = row[1]\n out_catalogids_v0p5[i] = row[0]\n i = i + 1\n if(i >= len(out_catalogids_v1)):\n out_catalogids_v1 = np.append(out_catalogids_v1,\n np.zeros(len(out_catalogids_v1),\n dtype=np.int64) - 1)\n out_catalogids_v0p5 = np.append(out_catalogids_v0p5,\n np.zeros(len(out_catalogids_v0p5),\n dtype=np.int64) - 1)\n out_catalogids_v1 = out_catalogids_v1[0:i]\n out_catalogids_v0p5 = out_catalogids_v0p5[0:i]\n \n return(out_catalogids_v1, out_catalogids_v0p5)\n\n\ndef catalogids_are_targets(catalogids=None):\n \"\"\"Check if catalogids are in target table\n\n Parameters\n ----------\n\n catalogids : ndarray of np.int64\n catalogids \n\n Returns\n -------\n\n istarget : ndarray of bool\n whether present\n\"\"\"\n # Construct query\n sql_template = \"\"\"SELECT targetdb.target.catalogid FROM targetdb.target\nJOIN (VALUES {v}) AS input(catalogid) ON targetdb.target.catalogid = input.catalogid;\n\"\"\"\n\n values = \"\"\n ucatalogids = np.unique(catalogids)\n for value in ucatalogids:\n values = values + \"({v}),\".format(v=value)\n values = values[0:-1]\n sql_command = sql_template.format(v=values)\n\n # Set up output\n istarget = np.zeros(len(catalogids), dtype=bool)\n indxs = dict()\n for cid in ucatalogids:\n indxs[cid] = np.where(catalogids == cid)[0]\n \n # Run query\n cursor = database.execute_sql(sql_command)\n for row in cursor.fetchall():\n catalogid = row[0]\n istarget[indxs[catalogid]] = True\n\n return(istarget)\n\n\ndef catalogids_to_target_ids(catalogids=None, input_catalog=None):\n \"\"\"Return target_ids for input catalog for catalogid\n\n Parameters\n ----------\n\n catalogids : ndarray of np.int64\n catalogids \n\n input_catalog : str\n name of input catalog (like 'tic_v8')\n\n Returns\n -------\n\n target_ids : ndarray of np.int64\n input catalog IDs\n\"\"\"\n # Construct query\n sql_template = \"\"\"SELECT catalogdb.catalog.catalogid, catalogdb.catalog_to_{s}.target_id FROM catalogdb.catalog\nJOIN catalogdb.catalog_to_{s} ON catalogdb.catalog.catalogid = catalogdb.catalog_to_{s}.catalogid\nJOIN (VALUES {v}) AS desired(catalogid) ON catalogdb.catalog.catalogid = desired.catalogid;\n\"\"\"\n\n values = \"\"\n ucatalogids = np.unique(catalogids)\n for value in ucatalogids:\n values = values + \"({v}),\".format(v=value)\n values = values[0:-1]\n sql_command = sql_template.format(v=values, s=input_catalog)\n\n # Set up output\n target_ids = np.zeros(len(catalogids), dtype=np.int64) - 1\n indxs = dict()\n for cid in ucatalogids:\n indxs[cid] = np.where(catalogids == cid)[0]\n \n # Run query\n cursor = database.execute_sql(sql_command)\n for row in cursor.fetchall():\n catalogid = row[0]\n target_id = row[1]\n target_ids[indxs[catalogid]] = target_id\n\n return(target_ids)\n\n\ndef target_ids_to_catalogids(target_ids=None, input_catalog=None,\n crossmatch=None):\n \"\"\"Map target_id to a catalogids from a particular version\n\n Parameters\n ----------\n\n target_ids : ndarray of np.int64\n IDs from input catalog\n\n crossmatch : str\n cross match version\n\n input_catalog : str\n name of input catalog (like 'tic_v8')\n\n Returns\n -------\n\n catalogids : ndarray of np.int64\n catalogids \n\"\"\"\n # Construct query\n sql_template = \"\"\"SELECT catalogdb.catalog_to_{s}.target_id, catalogdb.catalog.catalogid FROM catalogdb.catalog_to_{s}\nJOIN (VALUES {v}) AS desired(target_id) ON catalogdb.catalog_to_{s}.target_id = desired.target_id\nJOIN catalogdb.catalog ON catalogdb.catalog.catalogid = catalogdb.catalog_to_{s}.catalogid\nJOIN catalogdb.version ON catalogdb.version.id = catalogdb.catalog.version_id\nWHERE catalogdb.version.plan = '{c}';\n\"\"\"\n\n values = \"\"\n utarget_ids = np.unique(target_ids)\n for value in utarget_ids:\n values = values + \"({v}),\".format(v=value)\n values = values[0:-1]\n sql_command = sql_template.format(v=values, c=crossmatch, s=input_catalog)\n\n # Set up output\n catalogids = np.zeros(len(target_ids), dtype=np.int64) - 1\n indxs = dict()\n for tid in utarget_ids:\n indxs[tid] = np.where(target_ids == tid)[0]\n \n # Run query\n cursor = database.execute_sql(sql_command)\n for row in cursor.fetchall():\n target_id = row[0]\n catalogid = row[1]\n catalogids[indxs[target_id]] = catalogid\n\n return(catalogids)\n","repo_name":"sdss/robostrategy","sub_path":"python/robostrategy/targets.py","file_name":"targets.py","file_ext":"py","file_size_in_byte":17970,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"26898656592","text":"import subprocess\nfrom pathlib import Path\n\nfrom cmake_language_server.api import API\n\n\ndef test_query_with_cache(cmake_build: Path) -> None:\n api = API(\"cmake\", cmake_build)\n assert api.query()\n\n query = cmake_build / \".cmake\" / \"api\" / \"v1\" / \"query\"\n assert query.exists()\n\n reply = cmake_build / \".cmake\" / \"api\" / \"v1\" / \"reply\"\n assert reply.exists()\n\n\ndef test_query_without_cache(cmake_build: Path) -> None:\n api = API(\"cmake\", cmake_build)\n (cmake_build / \"CMakeCache.txt\").unlink()\n\n assert not api.query()\n\n\ndef test_read_variable(cmake_build: Path) -> None:\n api = API(\"cmake\", cmake_build)\n assert api.query()\n assert api.read_reply()\n\n assert api.get_variable_doc(\"testproject_BINARY_DIR\")\n\n\ndef test_read_cmake_files(cmake_build: Path) -> None:\n api = API(\"cmake\", cmake_build)\n api.parse_doc()\n assert api.query()\n api.read_reply()\n\n import platform\n\n system = platform.system()\n cxx = api.get_variable_doc(\"CMAKE_CXX_COMPILER_ID\")\n assert cxx is not None\n if system == \"Linux\":\n assert \"GNU\" in cxx\n elif system == \"Windows\":\n assert \"MSVC\" in cxx\n elif system == \"Darwin\":\n assert \"Clang\" in cxx\n else:\n raise RuntimeError(\"Unexpected system\")\n\n\ndef test_parse_commands(cmake_build: Path) -> None:\n api = API(\"cmake\", cmake_build)\n api.parse_doc()\n\n p = subprocess.run(\n [\"cmake\", \"--help-command-list\"],\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n commands = p.stdout.strip().split(\"\\n\")\n\n for command in commands:\n assert api.get_command_doc(command) is not None, f\"{command} not found\"\n\n break_doc = api.get_command_doc(\"break\")\n assert break_doc is not None and \"break()\" in break_doc\n assert api.get_command_doc(\"not_existing_command\") is None\n\n\ndef test_parse_variables(cmake_build: Path) -> None:\n api = API(\"cmake\", cmake_build)\n api.parse_doc()\n\n p = subprocess.run(\n [\"cmake\", \"--help-variable-list\"],\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n variables = p.stdout.strip().split(\"\\n\")\n\n for variable in variables:\n if \"<\" in variable:\n continue\n assert api.get_variable_doc(variable) is not None, f\"{variable} not found\"\n\n assert api.get_variable_doc(\"BUILD_SHARED_LIBS\") is not None\n assert api.get_variable_doc(\"not_existing_variable\") is None\n\n\ndef test_parse_modules(cmake_build: Path) -> None:\n api = API(\"cmake\", cmake_build)\n api.parse_doc()\n\n p = subprocess.run(\n [\"cmake\", \"--help-module-list\"],\n universal_newlines=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n modules = p.stdout.strip().split(\"\\n\")\n\n for module in modules:\n if module.startswith(\"Find\"):\n assert (\n api.get_module_doc(module[4:], True) is not None\n ), f\"{module} not found\"\n else:\n assert api.get_module_doc(module, False) is not None, f\"{module} not found\"\n\n assert api.get_module_doc(\"GoogleTest\", False) is not None\n assert api.get_module_doc(\"GoogleTest\", True) is None\n assert api.search_module(\"GoogleTest\", False) == [\"GoogleTest\"]\n assert api.search_module(\"GoogleTest\", True) == []\n assert api.get_module_doc(\"Boost\", False) is None\n assert api.get_module_doc(\"Boost\", True) is not None\n assert api.search_module(\"Boost\", False) == []\n assert api.search_module(\"Boost\", True) == [\"Boost\"]\n","repo_name":"regen100/cmake-language-server","sub_path":"tests/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","stars":274,"dataset":"github-code","pt":"61"}
+{"seq_id":"13409210430","text":"import ctypes\nimport ctypes.wintypes\n\n# Define necessary Windows API functions and types\nuser32 = ctypes.windll.user32\n\n# FindWindowA function\nFindWindowA = user32.FindWindowA\nFindWindowA.argtypes = [ctypes.c_char_p, ctypes.c_char_p]\nFindWindowA.restype = ctypes.wintypes.HWND\n\n# SetWindowTextW function\nSetWindowTextW = user32.SetWindowTextW\nSetWindowTextW.argtypes = [ctypes.wintypes.HWND, ctypes.c_wchar_p]\nSetWindowTextW.restype = ctypes.c_bool\n\ndef change_paint_title(new_title):\n # Find the Paint window by its class name (\"Paint\")\n paint_window = FindWindowA(b\"MSPaintApp\", None)\n\n if paint_window:\n # Change the title of the Paint window\n success = SetWindowTextW(paint_window, new_title)\n\n if success:\n print(f\"Title of Paint window changed to: {new_title}\")\n else:\n print(\"Failed to change the title of the Paint window.\")\n else:\n print(\"Paint window not found.\")\n\nif __name__ == \"__main__\":\n new_title = \"Hello from Python!\"\n change_paint_title(new_title)\n","repo_name":"mhmd-azeez/c-ffi","sub_path":"hwnd/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"61"}
+{"seq_id":"12389218988","text":"from itertools import permutations\n\ndef list_to_int(arr):\n string = \"\"\n for l in arr:\n string += l\n return int(string)\n\ndef calc(num1, num2, sign):\n if sign == \"+\":\n return num1+num2\n if sign == \"-\":\n return num1-num2\n if sign == \"*\":\n return num1*num2\n \ndef calc_with_operator(operands, operators, prior_opr):\n operators.reverse()\n operators.append(\"\")\n operators.reverse()\n\n stack = []\n num_stack = []\n opr_stack = []\n \n for operand, operator in zip(operands, operators):\n if not num_stack:\n num_stack.append(operand)\n continue\n \n if operator == prior_opr:\n num_stack.append(calc(num_stack.pop(), operand, operator))\n continue\n else:\n num_stack.append(operand)\n opr_stack.append(operator)\n \n return num_stack, opr_stack\n \ndef seperator(expression):\n signs = [\"+\", \"-\", \"*\"]\n \n number = []\n num_stack = []\n opr_stack = []\n for e in expression:\n if e in signs:\n num_stack.append(list_to_int(number))\n opr_stack.append(e)\n number = []\n else:\n number.append(e)\n num_stack.append(list_to_int(number))\n \n return num_stack, opr_stack\n\ndef calc_with_priority(operands, operators, priority):\n tmp_operands = [operand for operand in operands]\n tmp_operators = [operator for operator in operators]\n\n for p in priority:\n tmp_operands, tmp_operators = calc_with_operator(tmp_operands, tmp_operators, p)\n \n return int(tmp_operands[0])\n \n \n\ndef solution(expression):\n operands, operators = seperator(expression)\n \n priorities = list(permutations(list(set(operators))))\n print(priorities)\n \n max_val = 0\n for priority in priorities:\n max_val = max(max_val, abs(calc_with_priority(operands, operators, priority)))\n \n return max_val","repo_name":"hana-algorithm-study/coding-test","sub_path":"상준/프로그래머스/lv2/67257. [카카오 인턴] 수식 최대화/[카카오 인턴] 수식 최대화.py","file_name":"[카카오 인턴] 수식 최대화.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"14123884186","text":"from flask import *\r\nimport pandas as pd\r\nimport os\r\nfrom flask_cors import CORS\r\nfrom flask_jsonpify import jsonpify\r\nimport matplotlib.pyplot as plt\r\n\r\napp=Flask(\"__name__\")\r\nCORS(app)\r\n\r\n@app.route('/upload', methods = ['POST']) \r\ndef upload(): \r\n if request.method == 'POST': \r\n f = request.files['file'] \r\n f.save(f.filename) \r\n # print(request.get_data())\r\n\r\n # print(\"fine\")\r\n try:\r\n df=pd.read_csv(f.filename)\r\n except:\r\n try:\r\n df=pd.read_excel(f.filename)\r\n except:\r\n return jsonify(\"Please upload a valid file. i.e the file should be CSV or Xlsx\")\r\n print(df)\r\n return jsonify(\"File uploaded sucessfully\")\r\n\r\n\r\n@app.route('//head')\r\ndef head(filename):\r\n try:\r\n df=pd.read_csv(filename, header=None)\r\n except:\r\n df=pd.read_excel(filename, header=None)\r\n\r\n print(\"---------------------------------\")\r\n \r\n head = df.head().values.tolist()\r\n print(head)\r\n JSONP_data = jsonpify(head)\r\n return JSONP_data\r\n\r\n@app.route('//describe')\r\ndef desc(filename):\r\n try:\r\n df=pd.read_csv(filename, header=None)\r\n except:\r\n df=pd.read_excel(filename, header=None)\r\n print(\"---------------------------------\")\r\n desc = df.describe().values.tolist()\r\n print(desc)\r\n JSONP_data = jsonpify(desc)\r\n return JSONP_data\r\n\r\n@app.route('//plot//')\r\ndef plotgraph (filename,x,y):\r\n try:\r\n df=pd.read_csv(filename, header=None)\r\n except:\r\n df=pd.read_excel(filename, header=None)\r\n \r\n X= df[int(x)].values.tolist() \r\n Y= df[int(y)].values.tolist() \r\n plt.scatter(X,Y)\r\n plt.title(\"distribution\")\r\n plt.xlabel(x)\r\n plt.ylabel(y)\r\n print(\"---------------------------------\")\r\n # print(type(image))\r\n # return render_template('untitled1.html', name = plt.show())\r\n plt.savefig(\"plotimage.png\")\r\n return jsonify(\"okay\")\r\n\r\n@app.route('//shape')\r\ndef shape(filename):\r\n try:\r\n df=pd.read_csv(filename, header=None)\r\n except:\r\n df=pd.read_excel(filename, header=None)\r\n\r\n print(\"---------------------------------\")\r\n\r\n x,y= df.shape\r\n print(x,y)\r\n dictin={\"rows\":x,\"columns\":y}\r\n return jsonify(dictin)\r\n\r\n\r\n@app.route('///linearregnovice')\r\ndef linearregnovice(filename,predfile):\r\n try:\r\n data=pd.read_csv(filename, header=None)\r\n except:\r\n data=pd.read_excel(filename, header=None)\r\n \r\n print(\"---------------------------------\")\r\n\r\n try:\r\n pred=pd.read_csv(predfile, header=None)\r\n except:\r\n pred=pd.read_excel(predfile, header=None)\r\n \r\n \r\n from sklearn.model_selection import train_test_split\r\n from sklearn.linear_model import LinearRegression\r\n import numpy as np\r\n\r\n X = np.array(data.iloc[:,:-1].values) \r\n y = np.array(data.iloc[:,-1].values)\r\n # X=data.iloc[:,:-1].values # print(len(X)) y=df.iloc[:,-1].values\r\n \r\n \r\n dictin={}\r\n # Splitting the data into training and testing data\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25) \r\n print(\"*************************\")\r\n\r\n regr = LinearRegression()\r\n\r\n regr.fit(X_train, y_train)\r\n \r\n # X_pred=np.array([[8],[6],[5]])\r\n X_pred = np.array(pred.iloc[:,:].values) \r\n # X_pred=np.array([[8,2],[6,5],[5,6]])\r\n\r\n y_pred = regr.predict(X_pred)\r\n # print(X_test,y_pred)\r\n print()\r\n print(regr.score(X_test, y_test))\r\n dictin[\"r2_value\"]=regr.score(X_test, y_test)\r\n dictin[\"X_pred\"]=X_pred.tolist()\r\n dictin[\"y_pred\"]=y_pred.tolist()\r\n\r\n return jsonify(dictin)\r\n\r\n\r\nif __name__==\"__main__\":\r\n port=int(os.environ.get(\"PORT\",5000))\r\n app.run(host= \"0.0.0.0\", port=port)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"HarideepSriperumbooduru/MLToolBox","sub_path":"upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23760774213","text":"#!/usr/bin/env python\nfrom __future__ import with_statement\nimport os\nfrom setuptools import setup\n\nreadme = 'README.md'\nif os.path.exists('README.rst'):\n readme = 'README.rst'\nwith open(readme) as f:\n long_description = f.read()\n\nsetup(\n name='stacktracer',\n version='0.1.2',\n author='messense',\n author_email='messense@icloud.com',\n url='https://github.com/messense/stacktracer',\n keywords='stack, tracer, multi-threaded, threading',\n description='Stack tracer for multi-threaded applications',\n long_description=long_description,\n py_modules=['stacktracer'],\n install_requires=[\n 'pygments',\n ],\n include_package_data=True,\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: MacOS',\n 'Operating System :: POSIX',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Intended Audience :: Developers',\n 'Topic :: Software Development :: Libraries',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n 'Topic :: Utilities',\n ],\n)\n","repo_name":"messense/stacktracer","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"26031325335","text":"import streamlit as st\nimport pandas as pd\n\n# credentials\npage_title = \"CricStars - Dashboard\"\n\n# streamlit\nst.set_page_config(\n '{}'.format(page_title),\n '🏏',\n layout='wide',\n initial_sidebar_state='collapsed',\n menu_items={\n \"Get Help\": \"https://cricstars.streamlit.app\",\n \"About\": \"CrickStars App\",\n },\n)\n\nplayers_list_upload = st.sidebar.file_uploader(\"Upload Players List\", type=[\"csv\"])\nif players_list_upload is not None:\n players_list = pd.read_csv(players_list_upload)\n st.dataframe(players_list)\nelse:\n st.info(\"Upload players list to continue\")\n\n","repo_name":"hirawatt/cricstars","sub_path":"dashboard.py","file_name":"dashboard.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"34094038060","text":"from machine import PWM, Pin, I2C, ADC\nfrom utime import sleep_ms\nfrom ssd1306 import SSD1306_I2C\nimport framebuf\nfrom ultrasonics import *\n\nPROPORCION=0.8\nVELOCITY_R=int((0.805)*65536)\nVELOCITY_L=int((0.75)*65536)\nfrequency=(10000)\nWIDTH = 128\nHEIGHT = 64\n\n\nclass Bot:\n def __init__(self, Ultra):\n self.l1 = PWM(Pin(18))\n self.l1.freq(frequency)\n self.l2 = PWM(Pin(19))\n self.l2.freq(frequency)\n self.step1=0\n self.step2=0\n \n self.Ultra=Ultra\n \n \n self.r1 = PWM(Pin(20))\n self.r1.freq(frequency)\n self.r2 = PWM(Pin(21))\n self.r2.freq(frequency)\n self.stop()\n \n #self.i2c= I2C(1, scl = Pin(15), sda= Pin(14), freq = 200000) \n #self.oled = SSD1306_I2C(WIDTH, HEIGHT, self.i2c)\n #self.erase_oled()\n \n self.encoder2 = Pin(0, Pin.IN)\n self.encoder2.irq(trigger=Pin.IRQ_RISING, handler=self.en2_handler)\n \n self.encoder1 = Pin(2, Pin.IN)\n self.encoder1.irq(trigger=Pin.IRQ_RISING, handler=self.en1_handler)\n \n def en2_handler(self,Pin):\n self.det1=True\n self.step1 += 1\n print(self.step1)\n \n def en1_handler(self,Pin):\n self.det2=True\n self.step2 += 1\n print(self.step2)\n \n \n def left_direction(self):\n self.l1.duty_u16(0)\n self.l2.duty_u16(VELOCITY_L)\n self.r1.duty_u16(VELOCITY_R)\n self.r2.duty_u16(0)\n #sleep_ms(410)\n self.det2=False\n self.step2=0\n while self.step2 < 55:\n if self.det2:\n self.det2=False\n\n def right_direction(self):\n self.l1.duty_u16(VELOCITY_L)\n self.l2.duty_u16(0)\n self.r1.duty_u16(0)\n self.r2.duty_u16(VELOCITY_R)\n #sleep_ms(410)\n self.det1=False\n self.step1=0\n while self.step1 < 58:\n if self.det1:\n self.det1=False\n\n def front_direction(self):\n self.l1.duty_u16(VELOCITY_L)\n self.l2.duty_u16(0)\n self.r1.duty_u16(VELOCITY_R)\n self.r2.duty_u16(0)\n self.det1=False\n self.step1=0\n while self.step1 < 20:\n front=self.Ultra.measure_front()\n if front< 5:\n print(front)\n self.stop()\n break\n if self.det1:\n self.det1=False\n \n def stop(self):\n self.l1.duty_u16(0)\n self.l2.duty_u16(0)\n self.r1.duty_u16(0)\n self.r2.duty_u16(0)\n sleep_ms(500)\n \n def run(self):\n self.front_direction()\n self.left_direction()\n self.right_direction()\n self.stop()\n \n def listener(self, turns):\n negative = True if turns < 0 else False\n while turns != 0:\n turns = turns - 1 if turns > 0 else turns + 1\n if negative:\n #self.print_oled(\"DERECHA\")\n self.right_direction()\n self.stop()\n #self.erase_oled()\n self.stop()\n sleep_ms(500) \n \n else:\n #self.print_oled(\"IZQUIERDA\")\n self.left_direction()\n self.stop()\n #self.erase_oled()\n sleep_ms(500) \n #self.print_oled(\"AVANZA\")\n #self.front_direction()\n #self.stop()\n #self.erase_oled()\n sleep_ms(500)\n \n #def print_oled(self, text):\n # self.oled.text(str(text), 0, 0) \n # self.oled.show()\n\n \n #def erase_oled(self):\n # self.oled.fill(0)\n \n\ndef main():\n bot=Bot(Ultrasonics())\n bot.front_direction()\n bot.stop()\n \nif __name__ == '__main__':\n main()","repo_name":"Valent-in-GIT/Computer-Vision-Personal","sub_path":"Mazebot/Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":3778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"14355961308","text":"# -*- coding: utf-8 -*-\n# web2py/applications//controllers\nfrom cart import Cart\nfrom cart import OrderError\n\n\n\ndef add():\n product = db(db.product.id == request.args(0)).select().first()\n cart = Cart()\n if product.id in cart:\n try:\n # product.qty should be an int that represents\n # the amount avaiable of the product.\n # If amount of the order > amount_avaiable, an exception\n # will be raised.\n # If amount_avaiable is not set, the module won't check\n # the avaiable.\n cart.AddAmount(product.id, amount_avaiable=product.qty)\n except OrderError as e:\n return e\n else:\n carrinho.NewOrder(produto.id)\n return locals()\n\n\ndef remove():\n product = db(db.product.id == request.args(0)).select().first()\n cart = Cart()\n try:\n # If the order is not found, an exception will be raised.\n cart.DecreaseAmount(product.id)\n except OrderError as e:\n return e\n return locals()\n\n\ndef show():\n cart = Cart()\n cart_dict = cart.ShowCart() # A dict with all orders.\n for id, amount in cart:\n # Do something or\n pass\n return locals()\n\n\n","repo_name":"Marcelo-Theodoro/web2py_cart","sub_path":"example_controller.py","file_name":"example_controller.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"30156496699","text":"import numpy as np\nfrom scipy.optimize import minimize\nfrom pandas.core.frame import DataFrame\nfrom pandas.core.series import Series\nfrom scipy.optimize import OptimizeResult\n\nclass DualSVM():\n def gaussKernel(self, xi: np.ndarray):\n xi = np.asmatrix(xi)\n return np.exp(-((np.sum(np.multiply(xi, xi), axis = 1) + np.sum(np.multiply(xi.T, xi.T) , axis = 0) - 2 * xi.T * xi) / self.gamma))\n #return np.exp(-((np.sum(xi.T.dot(xi), axis = 1) + np.sum(np.multiply(xi.T, xi.T) , axis = 0) + 2 * xi.T @ xi) / self.gamma))\n\n def gaussKernelDual(self, xi: np.ndarray, xj: np.ndarray):\n return np.exp(- (((xi-xj)**2).sum())/self.gamma)\n\n def gaussObjective(self, alphas: np.ndarray):\n #return 0.5 * (self.gaussKernel(self.x) * np.dot( (alphas * self.y).T, (alphas*self.y) ) ).sum() - alphas.sum()\n return 0.5 * (self.xg * np.dot((alphas * self.y).T, (alphas*self.y)) ).sum() - alphas.sum()\n\n def constraints(self, alphas: np.ndarray):\n return (alphas * self.yarr).sum()\n\n def objective(self,alphas: np.ndarray):\n return 0.5 * (np.dot(self.x, self.x.T) * np.dot((alphas * self.y).T, (alphas*self.y)) ).sum() - alphas.sum()\n\n def __init__(self, training_data: DataFrame, output_column: str, C = 0.5, useGaussKernel=False, gamma = 1) -> None:\n self.training_data = training_data.copy(deep=True)\n #Let's wrap in a bias term as the last column before the labels\n self.training_data.insert(len(self.training_data.columns) - 1, \"bias\", 1)\n\n self.y = np.array([self.training_data[output_column].to_numpy()])\n self.yarr = self.training_data[output_column].to_numpy()\n self.gamma = gamma\n self.useGaussKernel = useGaussKernel\n \n self.yarr = self.training_data[output_column].to_numpy()\n self.x = self.training_data.drop([output_column], axis=1).to_numpy()\n self.alphas = np.random.rand(len(self.x))\n self.bounds = [(0,C)] * len(self.alphas)\n\n self.output_column = output_column\n self.C = C\n\n cons = ({'type':'eq', 'fun':self.constraints})\n if useGaussKernel:\n print(\"building kernel\")\n self.xg = np.zeros((len(self.x), len(self.x)))\n for i in range(len(self.x)):\n xi = self.x[i]\n for j in range(len(self.x)):\n self.xg[i][j] = self.gaussKernelDual(xi, self.x[j])\n\n #self.xg = self.x.T.dot(np.sum(self.x.dot(self.x), axis=1))\n print(\"optimizing\")\n solution: OptimizeResult = minimize(fun=self.gaussObjective, x0=self.alphas, constraints=cons, bounds=self.bounds, method='SLSQP')\n else:\n solution: OptimizeResult = minimize(fun=self.objective, x0=self.alphas, constraints=cons, bounds=self.bounds, method='SLSQP')\n\n self.alphas = solution.x\n print(solution.message)\n self.w: np.ndarray = np.zeros(len(self.training_data.columns) - 1) \n \n # this part is slow but we only need to do it once!\n if not useGaussKernel:\n for a,yi,x in zip(self.alphas, self.training_data[output_column].to_numpy(), self.x):\n if a == 0:\n continue\n self.w = self.w + (a * yi) * x\n\n #self.w = (self.alphas * self.y * self.x).sum(axis=1)\n \n\n\n def get_label(self, row: Series):\n # row needs to be augmented to support the bias.\n rowArr = row.drop(self.output_column).to_numpy()\n rowArr = np.append(rowArr, 1)\n \n\n if self.useGaussKernel:\n #rowArr = np.asmatrix(rowArr)\n prediction = 0.0\n for i in range(len(self.alphas)):\n if self.alphas[i] == 0: \n continue\n prediction = prediction + self.alphas[i] * self.yarr[i] * self.C * self.gaussKernelDual(self.x[i], rowArr)\n\n output = prediction\n else:\n output = self.w.T.dot(rowArr)\n\n if output >= 0:\n return 1\n else:\n return -1","repo_name":"Atomic-Johnson/mllib","sub_path":"SVM/dualSVM.py","file_name":"dualSVM.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"37313884667","text":"from rest_framework import filters, status\nfrom rest_framework import generics\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.parsers import MultiPartParser\nfrom rest_framework.response import Response\n\nfrom reefsource.apps.albums.models import UploadedFile, Album\nfrom reefsource.core.rest_framework.permissions import CustomPermission\nfrom .serializers import UploadedFileSerializer, AlbumSerializer, AlbumDetailSerializer, EmptyUploadedFileSerializer\n\n\nclass FileUploadView(generics.CreateAPIView):\n queryset = UploadedFile.objects.all()\n serializer_class = UploadedFileSerializer\n parser_classes = (MultiPartParser,)\n\n def __init__(self):\n super(__class__, self).__init__()\n self.albumId = None\n\n def get_queryset(self):\n queryset = super(__class__, self).get_queryset()\n queryset = queryset.filter(album__user=self.request.user)\n\n return queryset\n\n def create(self, request, albumId, *args, **kwargs):\n self.albumId = albumId\n return super(__class__, self).create(request, *args, **kwargs)\n\n def perform_create(self, serializer):\n params = {'album_id': self.albumId,\n 'original_filename': serializer.validated_data['file'].name,\n 'filesize': serializer.validated_data['file'].size,\n 'mime_type': serializer.validated_data['file'].content_type}\n\n serializer.save(**params)\n\n\nclass FileUploadViewDetailView(generics.RetrieveDestroyAPIView):\n queryset = UploadedFile.objects.all()\n serializer_class = UploadedFileSerializer\n\n def get_queryset(self):\n queryset = super(__class__, self).get_queryset()\n queryset = queryset.filter(album__user=self.request.user)\n\n return queryset\n\n\nclass FileUploadReanalyzePermission(CustomPermission):\n required_perms = ('reanalyze_result',)\n\n\nclass FileUploadReanalyzeView(GenericAPIView):\n queryset = UploadedFile.objects.all()\n serializer_class = EmptyUploadedFileSerializer\n permission_classes = (FileUploadReanalyzePermission,)\n\n def post(self, request, *args, **kwargs):\n instance = self.get_object()\n\n from reefsource.apps.results.models import Result\n Result.objects.filter(uploaded_file=instance).delete()\n\n instance.start_stage1()\n\n serializer = self.get_serializer(instance=instance)\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n\n\nclass AlbumApiMixin(object):\n queryset = Album.objects.all()\n serializer_class = AlbumSerializer\n\n def get_queryset(self):\n queryset = super(__class__, self).get_queryset()\n\n if not self.request.user.is_staff:\n queryset = queryset.filter(user=self.request.user)\n\n return queryset\n\n\nclass AlbumListView(AlbumApiMixin, generics.ListCreateAPIView):\n filter_backends = (filters.OrderingFilter, filters.SearchFilter,)\n ordering_fields = ('name', 'created', 'modified', 'date',)\n ordering = ('-date',)\n search_fields = ('name',)\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass AlbumDetailView(AlbumApiMixin, generics.RetrieveUpdateDestroyAPIView):\n serializer_class = AlbumDetailSerializer\n","repo_name":"reefsource/reefsource","sub_path":"reefsource/apps/albums/api/v1/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"74080421314","text":"from flask import flash, make_response, render_template, redirect, request, session, url_for\nfrom acomp import app, db, loginmanager, sessions\nfrom flask_login import current_user, login_required, logout_user\nfrom urllib.parse import urlparse, urljoin\nfrom acomp.glUser import GLUser\nfrom acomp.auth import auth\n\nfrom acomp.forms import Captcha, Classic, Signup, Signin, SettingsUserName, SettingsChangePassword, \\\n SettingsDeleteAccount\nimport json\n\nloginmanager.login_view = 'login'\n\n\ndef is_safe_url(target):\n \"\"\" https://web.archive.org/web/20120517003641/http://flask.pocoo.org/snippets/62/ \"\"\"\n ref_url = urlparse(request.host_url)\n test_url = urlparse(urljoin(request.host_url, target))\n return test_url.scheme in ('http', 'https') and \\\n ref_url.netloc == test_url.netloc\n\n\n@app.route('/classic')\n@login_required\ndef classic():\n form = Classic()\n usr = GLUser(current_user.get_id())\n user_name = usr.getName()\n img = usr.startClassic()\n return render_template('classic.html', source=img['images'], form=form, username=user_name)\n\n\n@app.route('/classic/data', methods=['GET'])\n@login_required\ndef classic_data_get():\n usr = GLUser(current_user.get_id())\n try:\n data = usr.startClassic()\n app.logger.debug(data)\n res = make_response(json.dumps(data))\n except Exception as e:\n return bad_request(e)\n else:\n res.headers.set('Content-Type', 'application/json')\n return res\n\n\n@app.route('/classic/data', methods=['POST'])\n@login_required\ndef classic_data_post():\n data = request.get_json()\n if data is None:\n return bad_request('Invalid JSON.')\n if 'tag' not in data:\n return bad_request('Missing key in JSON.')\n else:\n usr = GLUser(current_user.get_id())\n try:\n tag = usr.tagImage(data['tag'])\n except Exception as e:\n return bad_request(e)\n else:\n res_data = {'accepted': tag[0], 'message': tag[1], 'score': tag[2]}\n res = make_response(res_data)\n res.headers.set('Content-Type', 'application/json')\n return res\n\n\n@app.route('/captcha')\n@login_required\ndef captcha():\n form = Captcha()\n usr = GLUser(current_user.get_id())\n user_name = usr.getName()\n try:\n images = usr.startCaptcha()\n return render_template('captcha.html', source=images['images'], form=form, username=user_name)\n except Exception as e:\n flash('Currently there are not enough tagged images in our DB to play Captcha.'\n 'Please play the classic mode and try again later.')\n return render_template('captcha.html', source=images['images'], form=form, username=user_name)\n\n\n@app.route('/captcha/data', methods=['GET'])\n@login_required\ndef captcha_get():\n usr = GLUser(current_user.get_id())\n try:\n data = usr.startCaptcha()\n app.logger.debug(data)\n res = make_response(json.dumps(data))\n except Exception as e:\n return bad_request(e)\n else:\n res.headers.set('Content-Type', 'application/json')\n return res\n\n\n@app.route('/captcha/data', methods=['POST'])\n@login_required\ndef captcha_post():\n data = request.get_json()\n if data is None:\n return bad_request('Invalid JSON.')\n if 'joker' in data:\n usr = GLUser(current_user.get_id())\n try:\n wrng_images = usr.jokerCaptcha()\n except Exception as e:\n return bad_request(e)\n else:\n res_data = {\"message\": wrng_images}\n res = make_response(json.dumps(res_data))\n res.headers.set('Content-Type', 'application/json')\n return res\n if 'captcha' in data:\n usr = GLUser(current_user.get_id())\n try:\n captcha = usr.capCaptcha(data['captcha'])\n except Exception as e:\n return bad_request(e)\n else:\n res_data = {'accepted': captcha[0], 'message': captcha[1], 'score': captcha[2]}\n res = make_response(res_data)\n res.headers.set('Content-Type', 'application/json')\n return res\n else:\n return bad_request('Missing key in JSON.')\n\n\n@app.route('/quiz')\ndef quiz():\n if current_user.is_authenticated:\n return redirect(url_for('tutorial'))\n if 'quiz' not in session:\n session['quiz'] = 0\n if session['quiz'] >= app.config['ACOMP_QUIZ_POINTS']:\n flash('Congrats, you have reached enough points!')\n form = Captcha()\n usr = GLUser(-1)\n try:\n images = usr.startCaptcha()\n app.logger.debug('Current quiz score: {}'.format(session['quiz']))\n return render_template('captcha.html', source=images['images'], form=form)\n except:\n session['quiz'] = app.config['ACOMP_QUIZ_POINTS']\n flash('There are currently not enough tagged images in the database for the entry quiz. You may signup directly.')\n return redirect(url_for('signup'))\n\n\n@app.route('/quiz/data', methods=['GET'])\ndef quiz_get():\n if 'quiz' not in session:\n return forbidden('Not authorized.')\n if session['quiz'] >= app.config['ACOMP_QUIZ_POINTS']:\n flash('Congrats, you have reached enough points!')\n\n usr = GLUser(-1)\n try:\n data = usr.startCaptcha()\n app.logger.debug(data)\n res = make_response(json.dumps(data))\n except Exception as e:\n return bad_request(e)\n else:\n res.headers.set('Content-Type', 'application/json')\n return res\n\n\n@app.route('/quiz/data', methods=['POST'])\ndef quiz_post():\n if 'quiz' not in session:\n return forbidden('Not authorized.')\n\n data = request.get_json()\n if data is None:\n return bad_request('Invalid JSON.')\n if 'captcha' not in data:\n return bad_request('Missing key in JSON.')\n else:\n usr = GLUser(-1)\n try:\n challange, captcha = usr.capEntryQuiz(data['captcha'])\n except Exception as e:\n return bad_request(e)\n else:\n session['quiz'] += 1 if challange == 1 else -1\n signup_permission = int(session['quiz'] >= app.config['ACOMP_QUIZ_POINTS'])\n\n data = {'OK': signup_permission, 'message': captcha[0]}\n res = make_response(data)\n res.headers.set('Content-Type', 'application/json')\n return res\n\n\n@app.route('/tutorial')\ndef tutorial():\n form = Classic()\n return render_template('tutorial.html', source='../static/img/tutorial_1.jpg', form=form)\n\n\n@app.route('/signup', methods=['GET', 'POST'])\ndef signup():\n if current_user.is_authenticated:\n return redirect(url_for('settings'))\n form = Signup()\n if 'quiz' not in session:\n return redirect('quiz')\n elif session['quiz'] < app.config['ACOMP_QUIZ_POINTS']:\n return redirect('quiz')\n elif form.validate_on_submit():\n auth.register(form.loginname.data, form.loginpswd.data, form.loginpswdConfirm.data)\n auth.login(form.loginname.data, form.loginpswd.data)\n return redirect(url_for('tutorial'))\n app.logger.debug('Current quiz score: {}'.format(session['quiz']))\n return render_template('signup.html', form=form)\n\n\n@app.route('/signup/data', methods=['POST'])\n@app.route('/settings/data', methods=['POST'])\ndef signup_post():\n data = request.get_json()\n if data is None:\n return bad_request('Invalid JSON.')\n if 'name' not in data:\n return bad_request('Missing key in JSON.')\n else:\n if (auth.exists(data['name'])):\n res = make_response('{\"available\":\"0\", \"message\":\"Username not available\"}')\n else:\n res = make_response('{\"available\":\"1\", \"message\":\"Username available\"}')\n res.headers.set('Content-Type', 'application/json')\n return res\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n if current_user.is_authenticated:\n return redirect(url_for('settings'))\n form = Signin()\n if form.validate_on_submit():\n try:\n app.logger.debug('Login user name {}'.format(form.loginname.data))\n usr_id = auth.login(form.loginname.data, form.loginpswd.data)\n if usr_id > 0:\n app.logger.debug('Login user id {}'.format(usr_id))\n app.logger.debug('Current user id {}'.format(current_user.get_id()))\n target = request.args.get('next')\n if not is_safe_url(target):\n return bad_request('Could not redirect to ' + target)\n else:\n return redirect(url_for('classic'))\n except Exception as e:\n flash(e)\n return render_template('login.html', form=form)\n\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n return redirect(url_for('login'))\n\n\n@app.route('/settings', methods=['GET', 'POST'])\n@login_required\ndef settings():\n nameform = SettingsUserName()\n passwordform = SettingsChangePassword()\n deleteform = SettingsDeleteAccount()\n usr = GLUser(current_user.get_id())\n user_name = usr.getName()\n\n if nameform.validate_on_submit():\n try:\n app.logger.debug('Change name to {}'.format(nameform.newloginname.data))\n usrname = auth.changename(current_user.get_id(), nameform.newloginname.data, nameform.loginpswd.data)\n flash('Name change successful.')\n app.logger.debug('Current user id {}'.format(current_user.get_id()))\n app.logger.debug('Name change for {}'.format(usrname))\n except Exception as e:\n flash(e)\n\n if passwordform.validate_on_submit():\n try:\n usr_id = auth.changetoken(current_user.get_id(), passwordform.oldpswd.data, passwordform.newpswd.data,\n passwordform.newpswdConfirm.data)\n if usr_id > 0:\n flash('Password change successful.')\n app.logger.debug('Current user id {}'.format(current_user.get_id()))\n app.logger.debug('Change password for {}'.format(usr_id))\n except Exception as e:\n flash(e)\n\n if deleteform.validate_on_submit():\n try:\n app.logger.debug('Delete user id {}'.format(current_user.get_id()))\n usrname = auth.delete(current_user.get_id(), deleteform.loginpswddelform.data)\n app.logger.debug('Deleted user {}'.format(usrname))\n flash('User deleted.')\n return redirect(url_for('login'))\n except Exception as e:\n flash(e)\n\n return render_template('settings.html', nameform=nameform, deleteform=deleteform, passwordform=passwordform,\n username=user_name)\n\n\n@app.route('/settings/data', methods=['GET'])\n@login_required\ndef opendata():\n usr = GLUser(current_user.get_id())\n try:\n data = usr.getOpenData()\n app.logger.debug(data)\n res = make_response(json.dumps(data))\n except Exception as e:\n return bad_request(e)\n else:\n res.headers.set('Content-Type', 'application/json')\n return res\n\n\n@app.route('/help')\ndef help():\n return render_template('help.html')\n\n\n@app.route('/highscore')\n@login_required\ndef highscore():\n usr = GLUser(current_user.get_id())\n user_name = usr.getName()\n return render_template('highscore.html', data=usr.getHighscore(), username=user_name)\n\n\n@app.errorhandler(400)\ndef bad_request(e):\n return render_template('4xx.html', error_msg=e), 400\n\n\n@app.errorhandler(401)\ndef forbidden(e):\n return render_template('4xx.html', error_msg=e), 401\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n return render_template('4xx.html', error_msg=e), 404\n","repo_name":"muesal/annotation-competition","sub_path":"src/acomp/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":11669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38437721001","text":"import json\n\nfrom flask import Blueprint, current_app\nfrom flask_jwt_extended import create_refresh_token, create_access_token, get_jwt_identity, jwt_required\nfrom flask import request, jsonify\nfrom app.handlers import APIException\nfrom app.database.db import cursor, lastrowid\nimport requests\n\nbp = Blueprint(\"new_enrollment\", __name__, url_prefix=\"/enrollments\")\n\n\n@bp.route(\"/enrollment\", methods=[\"POST\"])\n@jwt_required(optional=True)\ndef create_new_enrollment():\n body = request.json\n user_id = get_jwt_identity()\n\n # Check if user is already signed to that tour\n if user_id:\n cursor().execute(f\"SELECT id FROM enrollments WHERE tour_id=%s AND user_id=%s\", (body[\"tour_id\"], user_id))\n res = cursor().fetchall()\n if res:\n raise APIException(msg=\"Ta wycieczka została już przez Ciebie wykupiona\", code=400)\n\n\n # Check if tour enrollment process is active\n cursor().execute(f\"SELECT * FROM tours WHERE id=%s AND NOW() < enrollment_deadline\", (body[\"tour_id\"], ))\n res = cursor().fetchall()\n if not res:\n raise APIException(msg=\"Okres zapisów tej wycieczki zakończył się\", code=400)\n tour_data = res[0]\n\n # Check if tour has available number of places\n cursor().execute(f\"SELECT sum(tickets) FROM enrollments WHERE tour_id=%s\", (body[\"tour_id\"], ))\n current_tickets = cursor().fetchone()[\"sum(tickets)\"]\n if current_tickets is None:\n current_tickets = 0\n person_limit = tour_data[\"person_limit\"]\n if current_tickets >= person_limit: # <-- checking if there are any available tickets\n raise APIException(msg=\"Ilość miejsc w ofercie została wyczerpana\", code=400)\n\n # Check if user's amount of tickets will exceed the person limit\n if current_tickets+len(body[\"participants\"]) > person_limit:\n raise APIException(msg=f\"W ofercie pozostało tylko {person_limit-current_tickets} miejsc\", code=400)\n\n\n\n # Create new enrollment\n columns = f\"f_name, l_name, phone_number, email, user_id, tour_id, city, postcode, street, house_number, apartment_number, comment, amount_payable\"\n insert = {\n \"f_name\": body[\"f_name\"],\n \"l_name\": body[\"l_name\"],\n \"phone_number\": body[\"phone_number\"],\n \"email\": body[\"email\"],\n \"user_id\": user_id if user_id else None,\n \"tour_id\": body[\"tour_id\"],\n \"city\": body[\"city\"],\n \"postcode\": body[\"postcode\"],\n \"street\": body[\"street\"],\n \"house_number\": body[\"house_number\"],\n \"apartment_number\": body[\"apartment_number\"],\n \"comment\": body[\"comment\"],\n \"amount_payable\": body[\"amount_payable\"]\n }\n cursor().execute(f\"INSERT INTO enrollments ({columns}) VALUES (%(f_name)s, %(l_name)s, %(phone_number)s, %(email)s, %(user_id)s, %(tour_id)s, %(city)s, %(postcode)s, %(street)s, %(house_number)s, %(apartment_number)s, %(comment)s, %(amount_payable)s)\", insert)\n enrollment_id = lastrowid()\n\n # Add participants to enrollment_participants table\n for full_name in body[\"participants\"]:\n cursor().execute(f\"INSERT INTO enrollment_participants (enrollment_id, full_name) VALUES (%s, %s)\", (enrollment_id, full_name))\n\n\n\n ### Make request to bitpay API ###\n url = \"https://test.bitpay.com/invoices\"\n token = current_app.config[\"BITPAY_SECRET_KEY\"]\n body = {\n \"token\": token,\n \"price\": body[\"amount_payable\"], # TODO change it to body[\"amount_payable\"], low value for now, for testing\n \"currency\": \"PLN\",\n \"itemDesc\": \"Zakup wycieczki\", #TODO It can be modified to tour's title\n \"notificationURL\": \"https://figlus.pl/api/payment/bitpay\",\n \"redirectURL\": \"https://figlus.pl/payment/success\",\n \"closeURL\": \"https://figlus.pl/payment/revoked\",\n \"posData\": json.dumps({\n \"enrollment_id\": enrollment_id,\n \"amount_payable\": body[\"amount_payable\"]\n }),\n \"transactionSpeed\": \"high\",\n \"fullNotifications\": False\n }\n headers = {\n \"Content-Type\": \"application/json\",\n \"X-Accept-Version\": \"2.0.0\"\n }\n\n response = requests.post(url, body, headers)\n res = response.json()\n\n payload = {\n \"url\": res[\"data\"][\"url\"]\n }\n\n response = jsonify(msg=f\"Zapis przebiegł pomyslnie + {current_tickets} \", payload=payload)\n return response, 200","repo_name":"navuyi/Praca-Inzynierska-2022","sub_path":"BACKEND/API/endpoints/enrollments/enrollment_post.py","file_name":"enrollment_post.py","file_ext":"py","file_size_in_byte":4337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72489898434","text":"import sys\ninput = sys.stdin.readline\n\n# 파싱\na, b = map(int, input().split())\na -= 1\nb -= 1\n\n# 계산\nax, ay = a // 4, a % 4\nbx, by = b // 4, b % 4\n\n# 결과 출력\nprint(abs(ax - bx) + abs(ay - by))\n","repo_name":"Lairin-pdj/coding_test","sub_path":"baekjoon/1598_꼬리를 무는 숫자 나열.py","file_name":"1598_꼬리를 무는 숫자 나열.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7381251298","text":"\nfrom tkinter import *\nfrom functools import partial\nimport tictactoe as ttt\n\nwindow = Tk()\n\nfield = [\n['_','_','_'],\n['_','_','_'],\n['x','_','0']]\n\n#todo убрать отладочную печать из другого файла и изменить цвет кнопок или текста \n\n# погуглить hello world на c и как его скомпилировать \n# погуглить про вим, базовый синтаксис C \n# занятие в вим \n\n\n# после mainloop выполняется только эта штука \ndef click(i,j):\n\tglobal field\n\tfield[i][j]='x'\n\tdraw_new_turn(field)\n\tfield = ttt.next_turn(field, '0')\n\tdraw_new_turn(field)\n\n\tprint(ttt.state(field))\n\n\n\n# drawing field\nbuttons_list = []\nfor i in range(3):\n buttons_list.append([])\n for j in range(3):\n button = Button(master=window, text=field[i][j], \n \tcommand = partial(click, i, j), \n \thighlightbackground = 'white',\n \tstate = DISABLED if (field[i][j] == 'x' or field[i][j] == '0') else NORMAL)\n button.grid(row=i, column=j)\n buttons_list[i].append(button)\n\nprint(buttons_list)\ndef draw_new_turn(field):\n\tfor i in range(3):\n\t\tfor j in range(3):\n\t\t\tbuttons_list[i][j]['text']=field[i][j]\n\t\t\tbuttons_list[i][j]['state']= DISABLED if (field[i][j] == 'x' or field[i][j] == '0') else NORMAL\n\n\n\n\n\n# отрисовка новой кнопки после нажатия \n# draw_new_turn([\n# ['x','x','0'],\n# ['0','x','_'],\n# ['x','_','0']])\n\n\n\n \n\n# def click(i,j):\n# \tdef indexes():\n# \t\tprint('indexes', i, j)\n# \treturn indexes\n\n\n# # drawing field\n# for i in range(3):\n# for j in range(3):\n# button = Button(master=window, text=field[i][j], command = click(i,j))\n# button.grid(row=i, column=j)\n\n\n# \ndef handle_click(event): # here should be indexes\n\tpass\n\n# button = tk.Button(text=\"Click me!\")\n\n# button.bind(\"\", handle_click)\n\nnew_field = None \n# changing element of field according indexes of pushed button\n\n\nwindow.mainloop()\n\n\n# for i in range(3):\n# for j in range(3):\n# frame = Frame( \n# master=window,\n# #relief = 'groove',\n# borderwidth=1,\n# # height = 4\n# )\n# frame.grid(row=i, column=j)\n# button = Button(master=frame, text=f\"Row {i}\\nColumn {j}\")\n# button.pack()\n\n\n# btn2 = Button()\n# btn2.pack\n\n\n# field = Label(text = 'Tic Tac Toe', \n# \tfg=\"white\",\n# bg=\"black\",\n# width=60,\n# height=60)\n\n# # frame1 = Frame(master=window, width=100, height=100, bg=\"red\")\n# # frame1.pack()\n\n# button = Button(\n# text=\"Click me!\",\n# width=25,\n# height=5,\n# bg='black',\n# fg=\"white\",\n# )\n\n# field.pack()\n# button.pack()\n\n\n\n\n# b=Button(t,text=\"hello\")\n\n# window = t.mainloop()\n\n","repo_name":"rudykas/edu","sub_path":"interface_ttt.py","file_name":"interface_ttt.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"22175869384","text":"import numpy as np\nimport numpy.linalg as la\nimport argparse\nimport csv\nnp.version.version\ntrain_data \t= np.genfromtxt('propublicaTrain.csv', usecols=(1,2,3,4,5,6,7,8,9),skip_header = 1, dtype = 'int8',delimiter=',')\ntrain_label\t= np.genfromtxt('propublicaTrain.csv', usecols=(0), skip_header = 1, dtype = 'int8',delimiter=',')\n\ntest_data \t= np.genfromtxt('propublicaTest.csv', usecols=(1,2,3,4,5,6,7,8,9),skip_header = 1, dtype = 'int8',delimiter=',')\ntest_label \t= np.genfromtxt('propublicaTest.csv', usecols=(0), skip_header = 1, dtype = 'int8',delimiter=',')\n\ntrain_num,_ = train_data.shape\ntest_num,_ = test_data.shape\ntest_data_0 = test_data[test_data[:,2] == 0]\ntest_data_1 = test_data[test_data[:,2] == 1]\nprint(test_data_0.shape)\nprint(test_data_1.shape)\n\n\nparser = argparse.ArgumentParser(description = 'knn classifier')\nparser.add_argument('-k', '--k', type = int, default =3, help = \"Hyper parameter k\")\nparser.add_argument('-n', '--norm', type = int, default =2, help = \"Hyper parameter norm\")\nargs = parser.parse_args()\n\n\n\n# print(train_data.shape,train_label.shape, test_data.shape,test_label.shape)\nk=args.k\nif args.norm<0:\n\tnorm_order = np.inf\nelse:\n\tnorm_order = args.norm\nhalf = int(k/2)\n\n\n\nm,n = test_data_0.shape\ncount_0 = [0,0,0]\nfor i in range(m):\n\tdiff = np.subtract(train_data,test_data_0[i])\n\tnorm = la.norm(diff, ord = norm_order, axis = 1)\n\ttemp = np.argsort(norm)\n\ttemp = temp[0:k]\n\n\tlabel_1 = 0\n\tfor x in temp:\n\t\tif train_label[x].item(0)>0:\n\t\t\tlabel_1+=1\n\tpredict_label = 0\n\tif label_1> half:\n\t\tpredict_label = 1\n\tif predict_label==0:\n\t\tcount_0[0]+=1\n\tif test_label[i].item(0) ==0:\n\t\tcount_0[2]+=1\n\tif test_label[i].item(0) == 0 and predict_label ==0:\n\t\tcount_0[1]+=1\n\nDP_0 = count_0[0]/m\nEO_0 = count_0[1]/count_0[2]\nPP_0 = count_0[1]/count_0[0]\nprint(\"DP a=0:\",DP_0)\nprint(\"EO a=0:\",EO_0)\nprint(\"PP a=0:\",PP_0)\nprint(count_0)\n\n\nm,n = test_data_1.shape\ncount_1 = [0,0,0]\nfor i in range(m):\n\tdiff = np.subtract(train_data,test_data_1[i])\n\tnorm = la.norm(diff, ord = norm_order, axis = 1)\n\ttemp = np.argsort(norm)\n\ttemp = temp[0:k]\n\n\tlabel_1 = 0\n\tfor x in temp:\n\t\tif train_label[x].item(0)>0:\n\t\t\tlabel_1+=1\n\tpredict_label = 0\n\tif label_1> half:\n\t\tpredict_label = 1\n\tif predict_label==0:\n\t\tcount_1[0]+=1\n\tif test_label[i].item(0) ==0:\n\t\tcount_1[2]+=1\n\tif test_label[i].item(0) == 0 and predict_label ==0:\n\t\tcount_1[1]+=1\n\nDP_1 = count_1[0]/m\nEO_1 = count_1[1]/count_1[2]\nPP_1 = count_1[1]/count_1[0]\nprint(\"DP a=0:\",DP_1)\nprint(\"EO a=0:\",EO_1)\nprint(\"PP a=0:\",PP_1)\nprint(count_1)\n\nDP_fair = abs(DP_1-DP_0)\nEO_fair = abs(EO_1-EO_0)\nPP_fair = abs(PP_1-PP_0)\nprint(\"DP_fair: \",DP_fair)\nprint(\"EO_fair: \",EO_fair)\nprint(\"PP_fair: \",PP_fair)\n\nwith open('DP_result.csv', 'a') as f:\n\twriter = csv.writer(f)\n\twriter.writerow(['knn',DP_fair])\n\nwith open('EO_result.csv', 'a') as f:\n\twriter = csv.writer(f)\n\twriter.writerow(['knn',EO_fair])\n\nwith open('PP_result.csv', 'a') as f:\n\twriter = csv.writer(f)\n\twriter.writerow(['knn',PP_fair])\n\n\n\n","repo_name":"ChengShen1996/MachineLearning","sub_path":"hw1/knn-fair.py","file_name":"knn-fair.py","file_ext":"py","file_size_in_byte":2961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"8394905236","text":"# https://leetcode.com/problems/maximum-units-on-a-truck\n# Oleg Belov\n\nclass Solution:\n def maximumUnits(self, boxTypes: List[List[int]], truckSize: int) -> int:\n boxTypes.sort(key=lambda x: x[1], reverse=True)\n units = 0\n for box_t in boxTypes:\n if box_t[0] <= truckSize:\n truckSize -= box_t[0]\n units += box_t[0] * box_t[1]\n else:\n units += truckSize * box_t[1]\n break\n return units","repo_name":"bgelov/python","sub_path":"built-ins/lambda/1710. Maximum Units on a Truck.py","file_name":"1710. Maximum Units on a Truck.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"61"}
+{"seq_id":"5261714156","text":"import cherrypy\nimport pywapi\nfrom mako.template import Template\n\ncherrypy.config.update({'server.socket_host': '0.0.0.0',\n 'server.socket_port': 8080,\n })\n\nclass HelloWorld:\n def index(self):\n tmpl = Template(filename='index.html')\n return tmpl.render(username=\"berg\")\n index.exposed = True\n\n def berg(self, area):\n the_weather = pywapi.get_weather_from_yahoo(area, \"\")\n \n tmpl = Template(filename='weather.html')\n tmpl_render = tmpl.render(\n conditions=the_weather['condition']['title'],\n cur_condition=the_weather['condition']['text'],\n cur_temp=the_weather['condition']['temp'],\n humidity=the_weather['atmosphere']['humidity'],\n pressure=the_weather['atmosphere']['pressure'],\n forecast_high=the_weather['forecasts'][1]['high'],\n forecast_low=the_weather['forecasts'][1]['low'], \n forecast_text = the_weather['forecasts'][1]['text'])\n\n return tmpl_render\n berg.exposed = True\n\ncherrypy.quickstart(HelloWorld())\n","repo_name":"mattinator/cherrypy-test","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"72489201794","text":"def hanoi(n, start, temp, end):\n global answer\n \n # 1개 일경우 바로 옮김\n if n == 1:\n answer.append([start, end])\n # 그렇지 않을 경우 3단계로 나누어 옮김\n else:\n # 나머지를 임시 저장소로 옮김\n hanoi(n - 1, start, end, temp)\n # 제일 큰 기둥을 목적지로 옮김\n hanoi(1, start, temp, end)\n # 임시 저장소에 있는 기둥을 목적지로 옮김 \n hanoi(n - 1, temp, start, end)\n \n\ndef solution(n):\n global answer\n answer = []\n \n hanoi(n, 1, 2, 3)\n \n return answer\n","repo_name":"Lairin-pdj/coding_test_practice_programmers","sub_path":"하노이의 탑.py","file_name":"하노이의 탑.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"31834473096","text":"from random import randint\nimport random\nimport math\n#print(random.sample(range(1, 18), 4) ) --→ [1, 7, 3, 11]\n\n\n# 1 список целых чисел от 0 до 999999\nspisok1 = [random.randint(0, 999999) for i in range(999999)]\n\n# 2 список из 99999 случайных вещественных чисел в диапазоне [-1, 1];\nspisok2 = [random.uniform(-1, 1) for i in range(999999)]\n\n# 3 42000 разных точки комплексной плоскости, лежащие в пределах окружности радиуса radius=20/2=10\nparam = 2 * math.pi / 42000\nplane_of_points = []\nfor i in range(42000):\n r1 = 10 * math.cos(i * param)\n r2 = 10 * math.sin(i * param)\n plane_of_points.append((r1, r2))\n\n\n# 4 книга\nwith open('elegance.txt', 'r', encoding = 'utf-8') as doc:\n book = doc.read().lower()\nlist_of_text = book.split()\n\n# 1 сортировка перемешиванием\ndef shaker_sort(arr):\n\n for i in range(1, len(arr)):\n shake = arr[i]\n j = i - 1\n while (j >= 0) and (arr[j] > shake):\n arr[j + 1] = arr[j]\n j = j - 1\n arr[j + 1] = shake\n return arr\n#print(shaker_sort(spisok1))\n\n# 7 гномья сортировка\ndef gnom(arr):\n i, size = 1, len(arr)\n while i < size:\n if arr[i - 1] <= arr[i]:\n i += 1\n else:\n arr[i], arr[i-1] = arr[i-1], arr[i]\n if i > 1:\n i -= 1\n return arr\n#print(gnom(spisok2))\n\n# 3 сортировка расчесткой\ndef rascheska(arr):\n first = len(arr) - 1\n while first > 0:\n for i in range(0, len(arr) - first):\n if (arr[i] > arr[i + first]):\n arr[i], arr[i + first] = arr[i + first], arr[i]\n step = int(first // 1.25)\n return arr\n#print(rascheska(plane_of_points))\n\n\n# 11 сортировка слиянием\ndef merge_sort (arr):\n if len(arr) < 2:\n return arr\n result = []\n midlle = int(len(arr) / 2)\n one = merge_sort(arr[:midlle])\n two = merge_sort(arr[midlle:])\n i = 0\n j = 0\n while i < len(one) and j < len(two):\n if one[i] > two[j]:\n result.append(two[j])\n j += 1\n else:\n result.append(one[i])\n i += 1\n result += one[i:]\n result += two[j:]\n return result\n#print(merge_sort(list_of_text))\n\n\n\n\n\n","repo_name":"kit8nino/2023-python","sub_path":"ИС34/Монцева Екатерина/[2].py","file_name":"[2].py","file_ext":"py","file_size_in_byte":2461,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"35516189951","text":"__author__ = 'Daksh Patel'\n\nimport os\n\nfrom flask import *\nfrom werkzeug.utils import secure_filename\n\nfrom project import auth\nfrom project.model.tweetModel import *\nfrom utils.utils import *\n\n\n@app.route('/admin/fetch_annotation_overview', methods=['GET'])\n@auth.login_required\ndef fetch_annotation_overview():\n user = g.user\n if \"admin\" in user.roles:\n admin = Admin()\n language = request.args.get('language')\n response = admin.fetch_annotation_by_users(lang=language)\n # print(response)\n code = 200\n status = True\n msg = f'{len(response)} users'\n result = {\n 'annotation_info': response\n }\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n resp = unauthorized_access()\n return resp\n\n\n@app.route('/admin/fetch_reported_tweets', methods=['GET'])\n@auth.login_required\ndef fetch_reported_tweets_admin():\n user = g.user\n if \"admin\" in user.roles:\n user_id = user.id\n language = request.args.get('language')\n reported_tweets = ReportedTweets.getAllReportedTweets(lang=language)\n status = True\n code = 200\n msg = f'{len(reported_tweets)} tweets found!'\n if len(reported_tweets) == 0:\n msg = 'User has not reported any tweets yet!'\n msg = msg\n result = {\n 'reported_tweets': reported_tweets\n }\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n resp = unauthorized_access()\n return resp\n\n\n@app.route('/admin/fetch_all_annotated_tweets', methods=['GET'])\n@auth.login_required\ndef fetch_all_annotated_tweets():\n user = g.user\n if 'admin' in user.roles:\n language = request.args.get('language')\n tweets = Tweets.objects(Q(total_annotation__gt=0) & Q(lang=language))\n tweets = json.loads(tweets.to_json())\n # print(tweets)\n # print(language, len(tweets))\n code = 200\n status = True\n msg = f'{len(tweets)} tweets found!'\n if len(tweets) == 0:\n msg = 'Annotations not started yet!'\n msg = msg\n result = {\n 'tweets': tweets\n }\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n resp = unauthorized_access()\n return resp\n\n\n@app.route('/admin/fetch_statistics', methods=['GET'])\n@auth.login_required\ndef fetch_statistics():\n user = g.user\n if 'admin' in user.roles:\n language = request.args.get('language')\n statistics = Admin.fetch_statistics(lang=language)\n code = 200\n status = True\n msg = f'Data received!'\n # if len(tweets) == 0:\n # msg = 'Annotations not started yet!'\n msg = msg\n result = {\n 'statistics': statistics\n }\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n resp = unauthorized_access()\n return resp\n\n\n@app.route('/admin/fetch_users', methods=['GET'])\n@auth.login_required\ndef fetch_users():\n user = g.user\n print(user)\n if \"admin\" in user.roles:\n users = Admin.fetch_all_user()\n code = 200\n status = True\n msg = f'{len(users)} users found!'\n # if len(tweets) == 0:\n # msg = 'Annotations not started yet!'\n msg = msg\n result = {\n 'users': users\n }\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n resp = unauthorized_access()\n return resp\n\n\n@app.route('/admin/add_more_tweets', methods=['POST'])\n@auth.login_required\ndef add_more_tweets():\n user = g.user\n if 'admin' in user.roles:\n admin = Admin()\n username = request.form.get('username')\n count = int(request.form.get('count'))\n language = request.form.get('language')\n # if not language:\n # language='en'\n # print(count, type(count))\n statuses = []\n msgs = []\n result = {}\n # for username in usernames:\n # # result[]\n status, msg = admin.add_more_tweets(username, count, lang=language)\n #\n if status:\n code = 200\n result = {}\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n code = 400\n result = {}\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n resp = unauthorized_access()\n return resp\n\n\n@app.route('/admin/remove_tweets', methods=['POST'])\n@auth.login_required\ndef remove_tweets():\n user = g.user\n if 'admin' in user.roles:\n username = request.form.get('username')\n count = int(request.form.get('count'))\n language = request.form.get('language')\n admin = Admin()\n status, msg = admin.remove_tweets(\n username=username,\n count=count,\n lang=language\n )\n if status:\n code = 200\n result = {}\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n code = 400\n result = {}\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n resp = unauthorized_access()\n return resp\n\n\n@app.route('/admin/add_user', methods=['POST'])\n@auth.login_required\ndef add_user():\n user = g.user\n if 'admin' in user.roles:\n name = request.form.get('name')\n username = request.form.get('username')\n password = request.form.get('password')\n langs = json.loads(request.form.get('languages'))\n query_set = User.objects(username=username)\n resp = None\n print(type(langs))\n print(request.data)\n print(request.get_data())\n if query_set.count() != 0:\n status = False\n code = 400\n msg = 'Username already exists!'\n result = {}\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n else:\n admin = Admin()\n status = admin.create_user(\n name=name,\n username=username,\n password=password,\n lang=langs\n )\n if status:\n code = 200\n result = {}\n msg = 'User added successfully!'\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n else:\n code = 400\n result = {}\n msg = 'Something went wrong'\n resp = createResponse(\n status_value=status,\n code=code,\n message=msg,\n result=result\n )\n return resp\n else:\n resp = unauthorized_access()\n return resp\n\n\n@app.route('/admin/upload_more_tweets', methods=['POST'])\n@auth.login_required\ndef upload_more_tweets():\n user = g.user\n if \"admin\" in user.roles:\n file_ = request.files['fileName']\n filename = secure_filename(file_.filename)\n data = file_.read().decode('utf-8')\n tmp_file_ptr = open(\"./tmp/{}\".format(filename), 'w')\n tmp_file_ptr.write(data)\n tmp_file_name = tmp_file_ptr.name\n tmp_file_ptr.close()\n stat, write_file_name = csvToJson(tmp_file_name)\n if stat == True:\n # print(\"erererer\")\n # print(write_file_name)\n data = json.load(open(write_file_name))\n admin = Admin()\n # print(datetime.datetime.now())\n resp = admin.upload_more_tweets(data)\n # print(datetime.datetime.now())\n if resp!=0:\n code = 200\n result = {}\n msg = f'{resp} rows added successfully!'\n resp = createResponse(\n status_value=True,\n code=code,\n message=msg,\n result=result\n )\n # print(resp)\n else:\n os.remove(write_file_name)\n code = 201\n result = {}\n msg = \"No new tweets found in the file: {}\".format(filename)\n resp = createResponse(\n status_value=True,\n code=code,\n message=msg,\n result=result\n )\n # print(resp)\n\n return resp\n else:\n code = 500\n result = {}\n msg = \"Invalid file type or format\"\n resp = createResponse(\n status_value=False,\n code=code,\n message=msg,\n result=result\n )\n return resp\n\n else:\n resp = unauthorized_access()\n return resp\n","repo_name":"daksh2298/annotation-platform","sub_path":"project/controller/adminController.py","file_name":"adminController.py","file_ext":"py","file_size_in_byte":10112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11931563840","text":"from nepi.execution.attribute import Attribute, Flags, Types\nfrom nepi.execution.resource import clsinit_copy, ResourceState \nfrom nepi.resources.linux.ns3.ccn.ns3ccndceapplication import LinuxNS3CCNDceApplication\n\n@clsinit_copy\nclass LinuxNS3DceCCNR(LinuxNS3CCNDceApplication):\n _rtype = \"linux::ns3::dce::CCNR\"\n\n @classmethod\n def _register_attributes(cls):\n max_fanout = Attribute(\"maxFanout\",\n \"Sets the CCNR_BTREE_MAX_FANOUT environmental variable. \",\n flags = Flags.Design)\n\n max_leaf_entries = Attribute(\"maxLeafEntries\",\n \"Sets the CCNR_BTREE_MAX_LEAF_ENTRIES environmental variable. \",\n flags = Flags.Design)\n\n max_node_bytes = Attribute(\"maxNodeBytes\",\n \"Sets the CCNR_BTREE_MAX_NODE_BYTES environmental variable. \",\n flags = Flags.Design)\n\n max_node_pool = Attribute(\"maxNodePool\",\n \"Sets the CCNR_BTREE_MAX_NODE_POOL environmental variable. \",\n flags = Flags.Design)\n\n content_cache = Attribute(\"contentCache\",\n \"Sets the CCNR_CONTENT_CACHE environmental variable. \",\n flags = Flags.Design)\n\n debug = Attribute(\"debug\",\n \"Sets the CCNR_DEBUG environmental variable. \"\n \"Logging level for ccnr. Defaults to WARNING.\",\n type = Types.Enumerate,\n allowed = [\n \"NONE\",\n \"SEVERE\",\n \"ERROR\",\n \"WARNING\",\n \"INFO\",\n \"FINE, FINER, FINEST\"],\n flags = Flags.Design)\n\n directory = Attribute(\"directory\",\n \"Sets the CCNR_DIRECTORY environmental variable. \",\n flags = Flags.Design)\n\n global_prefix = Attribute(\"globalPrefix\",\n \"Sets the CCNR_GLOBAL_PREFIX environmental variable. \",\n flags = Flags.Design)\n\n listen_on = Attribute(\"listenOn\",\n \"Sets the CCNR_LISTEN_ON environmental variable. \",\n flags = Flags.Design)\n\n min_send_bufsize = Attribute(\"minSendBufsize\",\n \"Sets the CCNR_MIN_SEND_BUFSIZE environmental variable. \",\n flags = Flags.Design)\n\n proto = Attribute(\"proto\",\n \"Sets the CCNR_PROTO environmental variable. \",\n flags = Flags.Design)\n\n status_port = Attribute(\"statusPort\",\n \"Sets the CCNR_STATUS_PORT environmental variable. \",\n flags = Flags.Design)\n\n start_write_scope_limit = Attribute(\"startWriteScopeLimit\",\n \"Sets the CCNR_START_WRITE_SCOPE_LIMIT environmental variable. \",\n flags = Flags.Design)\n\n ccns_debug = Attribute(\"ccnsDebug\",\n \"Sets the CCNS_DEBUG environmental variable. \",\n flags = Flags.Design)\n\n ccns_enable = Attribute(\"ccnsEnable\",\n \"Sets the CCNS_ENABLE environmental variable. \",\n flags = Flags.Design)\n\n ccns_faux_error = Attribute(\"ccnsFauxError\",\n \"Sets the CCNS_FAUX_ERROR environmental variable. \",\n flags = Flags.Design)\n\n ccns_heartbeat_micros = Attribute(\"ccnsHeartBeatMicros\",\n \"Sets the CCNS_HEART_BEAT_MICROS environmental variable. \",\n flags = Flags.Design)\n\n ccns_max_compares_busy = Attribute(\"ccnsMaxComparesBusy\",\n \"Sets the CCNS_MAX_COMPARES_BUSY environmental variable. \",\n flags = Flags.Design)\n\n ccns_max_fetch_busy = Attribute(\"ccnsMaxFetchBusy\",\n \"Sets the CCNS_MAX_FETCH_BUSY environmental variable. \",\n flags = Flags.Design)\n\n ccns_node_fetch_lifetime = Attribute(\"ccnsNodeFetchLifetime\",\n \"Sets the CCNS_NODE_FETCH_LIFETIME environmental variable. \",\n flags = Flags.Design)\n\n ccns_note_err = Attribute(\"ccnsNoteErr\",\n \"Sets the CCNS_NOTE_ERR environmental variable. \",\n flags = Flags.Design)\n\n ccns_repo_store = Attribute(\"ccnsRepoStore\",\n \"Sets the CCNS_REPO_STORE environmental variable. \",\n flags = Flags.Design)\n\n ccns_root_advise_fresh = Attribute(\"ccnsRootAdviseFresh\",\n \"Sets the CCNS_ROOT_ADVISE_FRESH environmental variable. \",\n flags = Flags.Design)\n\n ccns_root_advise_lifetime = Attribute(\"ccnsRootAdviseLifetime\",\n \"Sets the CCNS_ROOT_ADVISE_LIFETIME environmental variable. \",\n flags = Flags.Design)\n\n ccns_stable_enabled = Attribute(\"ccnsStableEnabled\",\n \"Sets the CCNS_STABLE_ENABLED environmental variable. \",\n flags = Flags.Design)\n\n ccns_sync_scope = Attribute(\"ccnsSyncScope\",\n \"Sets the CCNS_SYNC_SCOPE environmental variable. \",\n flags = Flags.Design)\n\n repo_file = Attribute(\"repoFile1\",\n \"The Repository uses $CCNR_DIRECTORY/repoFile1 for \"\n \"persistent storage of CCN Content Objects\",\n flags = Flags.Design)\n\n cls._register_attribute(max_fanout)\n cls._register_attribute(max_leaf_entries)\n cls._register_attribute(max_node_bytes)\n cls._register_attribute(max_node_pool)\n cls._register_attribute(content_cache)\n cls._register_attribute(debug)\n cls._register_attribute(directory)\n cls._register_attribute(global_prefix)\n cls._register_attribute(listen_on)\n cls._register_attribute(min_send_bufsize)\n cls._register_attribute(proto)\n cls._register_attribute(status_port)\n cls._register_attribute(start_write_scope_limit)\n cls._register_attribute(ccns_debug)\n cls._register_attribute(ccns_enable)\n cls._register_attribute(ccns_faux_error)\n cls._register_attribute(ccns_heartbeat_micros)\n cls._register_attribute(ccns_max_compares_busy)\n cls._register_attribute(ccns_max_fetch_busy)\n cls._register_attribute(ccns_node_fetch_lifetime)\n cls._register_attribute(ccns_note_err)\n cls._register_attribute(ccns_repo_store)\n cls._register_attribute(ccns_root_advise_fresh)\n cls._register_attribute(ccns_root_advise_lifetime)\n cls._register_attribute(ccns_stable_enabled)\n cls._register_attribute(ccns_sync_scope)\n cls._register_attribute(repo_file)\n\n def _instantiate_object(self):\n if not self.get(\"binary\"):\n self.set(\"binary\", \"ccnr\")\n\n if not self.get(\"environment\"):\n self.set(\"environment\", self._environment)\n \n repoFile1 = self.get(\"repoFile1\")\n if repoFile1:\n env = \"CCNR_DIRECTORY=/REPO/\" \n environment = self.get(\"environment\")\n if environment:\n env += \";\" + environment\n self.set(\"environment\", env)\n self.set(\"files\", \"%s=/REPO/repoFile1\" % repoFile1) \n\n super(LinuxNS3DceCCNR, self)._instantiate_object()\n\n @property\n def _environment(self):\n envs = dict({\n \"maxFanout\": \"CCNR_BTREE_MAX_FANOUT\",\n \"maxLeafEntries\": \"CCNR_BTREE_MAX_LEAF_ENTRIES\",\n \"maxNodeBytes\": \"CCNR_BTREE_MAX_NODE_BYTES\",\n \"maxNodePool\": \"CCNR_BTREE_MAX_NODE_POOL\",\n \"contentCache\": \"CCNR_CONTENT_CACHE\",\n \"debug\": \"CCNR_DEBUG\",\n \"directory\": \"CCNR_DIRECTORY\",\n \"globalPrefix\": \"CCNR_GLOBAL_PREFIX\",\n \"listenOn\": \"CCNR_LISTEN_ON\",\n \"minSendBufsize\": \"CCNR_MIN_SEND_BUFSIZE\",\n \"proto\": \"CCNR_PROTO\",\n \"statusPort\": \"CCNR_STATUS_PORT\",\n \"startWriteScopeLimit\": \"CCNR_START_WRITE_SCOPE_LIMIT\",\n \"ccnsDebug\": \"CCNS_DEBUG\",\n \"ccnsEnable\": \"CCNS_ENABLE\",\n \"ccnsFauxError\": \"CCNS_FAUX_ERROR\",\n \"ccnsHeartBeatMicros\": \"CCNS_HEART_BEAT_MICROS\",\n \"ccnsMaxComparesBusy\": \"CCNS_MAX_COMPARES_BUSY\",\n \"ccnsMaxFetchBusy\": \"CCNS_MAX_FETCH_BUSY\",\n \"ccnsNodeFetchLifetime\": \"CCNS_NODE_FETCH_LIFETIME\",\n \"ccnsNoteErr\": \"CCNS_NOTE_ERR\",\n \"ccnsRepoStore\": \"CCNS_REPO_STORE\",\n \"ccnsRootAdviseFresh\": \"CCNS_ROOT_ADVISE_FRESH\",\n \"ccnsRootAdviseLifetime\": \"CCNS_ROOT_ADVISE_LIFETIME\",\n \"ccnsStableEnabled\": \"CCNS_STABLE_ENABLED\",\n \"ccnsSyncScope\": \"CCNS_SYNC_SCOPE\",\n })\n\n env = \";\".join(map(lambda k: \"%s=%s\" % (envs.get(k), str(self.get(k))), \n [k for k in envs.keys() if self.get(k)]))\n\n return env\n\n\n","repo_name":"phiros/nepi","sub_path":"src/nepi/resources/linux/ns3/ccn/ns3ccnrdceapplication.py","file_name":"ns3ccnrdceapplication.py","file_ext":"py","file_size_in_byte":8447,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"21912738967","text":"#### https://github.com/ageitgey/face_recognition/tree/master\n#### https://pypi.org/project/face-recognition/\n#### https://viso.ai/computer-vision/deepface/\n#### https://pyimagesearch.com/2021/04/19/face-detection-with-dlib-hog-and-cnn/\nimport face_recognition\nimport cv2\nimport numpy as np\nimport os\n\n# This is a demo of running face recognition on live video from your webcam. It's a little more complicated than the\n# other example, but it includes some basic performance tweaks to make things run a lot faster:\n# 1. Process each video frame at 1/4 resolution (though still display it at full resolution)\n# 2. Only detect faces in every other frame of video.\n\n# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.\n# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this\n# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.\n\n###Load sample images and train(recognize) them one by one\n## Load a sample picture and learn how to recognize it.\n# jitu_image = face_recognition.load_image_file(\"./DataScience/OpenCV/CSE-15-Final/1702028_Jitu.png\")\n# jitu_face_encoding = face_recognition.face_encodings(jitu_image)[0]\n\n# ## Load a second sample picture and learn how to recognize it.\n# najmul_image = face_recognition.load_image_file(\"./DataScience/OpenCV/CSE-15-Final/1702069_Najmul.png\")\n# najmul_face_encoding = face_recognition.face_encodings(najmul_image)[0]\n\n# ## Load a second sample picture and learn how to recognize it.\n# akash_image = face_recognition.load_image_file(\"./DataScience/OpenCV/CSE-15-Final/1702013_Akash.jpg\")\n# akash_face_encoding = face_recognition.face_encodings(akash_image)[0]\n\n# ## Load a second sample picture and learn how to recognize it.\n# shaikat_image = face_recognition.load_image_file(\"./DataScience/OpenCV/CSE-15-Final/1702030_Shaikat.jpg\")\n# shaikat_face_encoding = face_recognition.face_encodings(shaikat_image)[0]\n\n\n# ## Create arrays of known face encodings and their names\n# known_face_encodings = [\n# najmul_face_encoding,\n# jitu_face_encoding,\n# akash_face_encoding,\n# shaikat_face_encoding\n# ]\n# known_face_names = [\n# \"Najmul\",\n# \"Jitu\",\n# \"Akash\",\n# \"Shaikat\"\n# ]\n\n###Load sample images and train(recognize) them by a folder\n## Load a sample picture and learn how to recognize it.\n\ndef load_images_from_folder_and_recognize(folder):\n \"this function loads images from a folder and train with their name\"\n known_face_names=[]\n known_face_encodings=[]\n images = []\n for filename in os.listdir(folder):\n img = cv2.imread(os.path.join(folder,filename))\n img_path = os.path.join(folder,filename)\n if img_path is not None:\n #filename with extension\n #print(filename)\n #filename without extension\n indexoflastdot = filename.rfind(\".\")\n onlyfilename=filename[:indexoflastdot]\n\n # Load a sample picture and learn how to recognize it.\n image = face_recognition.load_image_file(img_path)\n image_encoding = face_recognition.face_encodings(image)[0]\n known_face_names.append(onlyfilename)\n known_face_encodings.append(image_encoding)\n print(filename+\" recognizing complete\")\n images.append(img)\n return known_face_names,known_face_encodings\n\nknown_face_names,known_face_encodings=load_images_from_folder_and_recognize('./DataScience/OpenCV/CSE-15-Final/')\n\n## Initialize some variables\nface_locations = []\nface_encodings = []\nface_names = []\nprocess_this_frame = True\n\n## Get a reference to webcam #0 or ipcam (the default one)\nvideo_capture = cv2.VideoCapture(0)\n#video_capture = cv2.VideoCapture('rtsp://foscamr2:foscamr2@192.168.1.2:88/videoMain')\n#video_capture = cv2.VideoCapture('rtsp://visitor1:visitor1@192.168.1.2:88/videoMain')\n\nwhile True:\n # Grab a single frame of video\n ret, frame = video_capture.read()\n\n # Only process every other frame of video to save time\n if process_this_frame:\n # Resize frame of video to 1/4 size for faster face recognition processing\n small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)\n\n # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n #rgb_small_frame = small_frame[:, :, ::-1] #not works\n #rgb_small_frame = cv2.cvtColor(small_frame, cv2.COLOR_BGR2RGB)\n rgb_small_frame = np.ascontiguousarray(small_frame[:, :, ::-1])\n \n # Find all the faces and face encodings in the current frame of video\n face_locations = face_recognition.face_locations(rgb_small_frame)\n face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)\n\n face_names = []\n for face_encoding in face_encodings:\n # See if the face is a match for the known face(s)\n matches = face_recognition.compare_faces(known_face_encodings, face_encoding)\n name = \"Unknown\"\n\n # # If a match was found in known_face_encodings, just use the first one.\n # if True in matches:\n # first_match_index = matches.index(True)\n # name = known_face_names[first_match_index]\n\n # Or instead, use the known face with the smallest distance to the new face\n face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)\n best_match_index = np.argmin(face_distances)\n if matches[best_match_index]:\n name = known_face_names[best_match_index]\n\n face_names.append(name)\n\n process_this_frame = not process_this_frame\n\n\n # Display the results\n for (top, right, bottom, left), name in zip(face_locations, face_names):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n top *= 4\n right *= 4\n bottom *= 4\n left *= 4\n\n # Draw a box around the face\n cv2.rectangle(frame, (left, top), (right, bottom), (255, 115, 115), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 25), (right, bottom), (255, 0, 0), cv2.FILLED)\n #font = cv2.FONT_HERSHEY_DUPLEX\n #font = cv2.FONT_HERSHEY_TRIPLEX\n font = cv2.FONT_HERSHEY_COMPLEX_SMALL\n cv2.putText(frame, name, (left + 6, bottom - 6), font, 0.53, (255, 255, 255), 1)\n\n # Display the resulting image\n cv2.imshow('Video', frame)\n\n # Hit 'q' on the keyboard to quit!\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Release handle to the webcam\nvideo_capture.release()\ncv2.destroyAllWindows()\n\n#########Using Multi-processing############\n# import face_recognition\n# import cv2\n# from multiprocessing import Process, Manager, cpu_count, set_start_method\n# import time\n# import numpy as np\n# import threading\n# import platform\n\n\n# # This is a little bit complicated (but fast) example of running face recognition on live video from your webcam.\n# # This example is using multiprocess.\n\n# # PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.\n# # OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this\n# # specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.\n\n\n# # Get next worker's id\n# def next_id(current_id, worker_num):\n# if current_id == worker_num:\n# return 1\n# else:\n# return current_id + 1\n\n\n# # Get previous worker's id\n# def prev_id(current_id, worker_num):\n# if current_id == 1:\n# return worker_num\n# else:\n# return current_id - 1\n\n\n# # A subprocess use to capture frames.\n# def capture(read_frame_list, Global, worker_num):\n# # Get a reference to webcam #0 (the default one)\n# #video_capture = cv2.VideoCapture(0)\n# video_capture = cv2.VideoCapture('rtsp://foscamr2:foscamr2@192.168.1.2:88/videoMain')\n# # video_capture.set(3, 640) # Width of the frames in the video stream.\n# # video_capture.set(4, 480) # Height of the frames in the video stream.\n# # video_capture.set(5, 30) # Frame rate.\n# print(\"Width: %d, Height: %d, FPS: %d\" % (video_capture.get(3), video_capture.get(4), video_capture.get(5)))\n\n# while not Global.is_exit:\n# # If it's time to read a frame\n# if Global.buff_num != next_id(Global.read_num, worker_num):\n# # Grab a single frame of video\n# ret, frame = video_capture.read()\n# read_frame_list[Global.buff_num] = frame\n# Global.buff_num = next_id(Global.buff_num, worker_num)\n# else:\n# time.sleep(0.01)\n\n# # Release webcam\n# video_capture.release()\n\n\n# # Many subprocess use to process frames.\n# def process(worker_id, read_frame_list, write_frame_list, Global, worker_num):\n# known_face_encodings = Global.known_face_encodings\n# known_face_names = Global.known_face_names\n# while not Global.is_exit:\n\n# # Wait to read\n# while Global.read_num != worker_id or Global.read_num != prev_id(Global.buff_num, worker_num):\n# # If the user has requested to end the app, then stop waiting for webcam frames\n# if Global.is_exit:\n# break\n\n# time.sleep(0.01)\n\n# # Delay to make the video look smoother\n# time.sleep(Global.frame_delay)\n\n# # Read a single frame from frame list\n# frame_process = read_frame_list[worker_id]\n\n# # Expect next worker to read frame\n# Global.read_num = next_id(Global.read_num, worker_num)\n\n# # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)\n# #rgb_frame = frame_process[:, :, ::-1] not works\n# rgb_frame = np.ascontiguousarray(frame_process[:, :, ::-1])\n\n# # Find all the faces and face encodings in the frame of video, cost most time\n# face_locations = face_recognition.face_locations(rgb_frame)\n# face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)\n\n# # Loop through each face in this frame of video\n# for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):\n# # See if the face is a match for the known face(s)\n# matches = face_recognition.compare_faces(known_face_encodings, face_encoding)\n\n# name = \"Unknown\"\n\n# # If a match was found in known_face_encodings, just use the first one.\n# if True in matches:\n# first_match_index = matches.index(True)\n# name = known_face_names[first_match_index]\n\n# # Draw a box around the face\n# cv2.rectangle(frame_process, (left, top), (right, bottom), (0, 0, 255), 2)\n\n# # Draw a label with a name below the face\n# cv2.rectangle(frame_process, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n# font = cv2.FONT_HERSHEY_DUPLEX\n# cv2.putText(frame_process, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n\n# # Wait to write\n# while Global.write_num != worker_id:\n# time.sleep(0.01)\n\n# # Send frame to global\n# write_frame_list[worker_id] = frame_process\n\n# # Expect next worker to write frame\n# Global.write_num = next_id(Global.write_num, worker_num)\n\n\n# if __name__ == '__main__':\n\n# # Fix Bug on MacOS\n# if platform.system() == 'Darwin':\n# set_start_method('forkserver')\n\n# # Global variables\n# Global = Manager().Namespace()\n# Global.buff_num = 1\n# Global.read_num = 1\n# Global.write_num = 1\n# Global.frame_delay = 0\n# Global.is_exit = False\n# read_frame_list = Manager().dict()\n# write_frame_list = Manager().dict()\n\n# # Number of workers (subprocess use to process frames)\n# if cpu_count() > 2:\n# worker_num = cpu_count() - 1 # 1 for capturing frames\n# else:\n# worker_num = 2\n\n# # Subprocess list\n# p = []\n\n# # Create a thread to capture frames (if uses subprocess, it will crash on Mac)\n# p.append(threading.Thread(target=capture, args=(read_frame_list, Global, worker_num,)))\n# p[0].start()\n\n# # Load a sample picture and learn how to recognize it.\n# jitu_image = face_recognition.load_image_file(\"./DataScience/OpenCV/CSE-15-Final/1702028_Jitu.png\")\n# jitu_face_encoding = face_recognition.face_encodings(jitu_image)[0]\n\n# # Load a second sample picture and learn how to recognize it.\n# najmul_image = face_recognition.load_image_file(\"./DataScience/OpenCV/CSE-15-Final/1702069_Najmul.png\")\n# najmul_face_encoding = face_recognition.face_encodings(najmul_image)[0]\n\n# # Load a second sample picture and learn how to recognize it.\n# akash_image = face_recognition.load_image_file(\"./DataScience/OpenCV/CSE-15-Final/1702013_Akash.jpg\")\n# akash_face_encoding = face_recognition.face_encodings(akash_image)[0]\n\n# # Load a second sample picture and learn how to recognize it.\n# shaikat_image = face_recognition.load_image_file(\"./DataScience/OpenCV/CSE-15-Final/1702030_Shaikat.jpg\")\n# shaikat_face_encoding = face_recognition.face_encodings(shaikat_image)[0]\n\n\n# # Create arrays of known face encodings and their names\n# Global.known_face_encodings = [\n# najmul_face_encoding,\n# jitu_face_encoding,\n# akash_face_encoding,\n# shaikat_face_encoding\n# ]\n# Global.known_face_names = [\n# \"Najmul\",\n# \"Jitu\",\n# \"Akash\",\n# \"Shaikat\"\n# ]\n\n# # Create workers\n# for worker_id in range(1, worker_num + 1):\n# p.append(Process(target=process, args=(worker_id, read_frame_list, write_frame_list, Global, worker_num,)))\n# p[worker_id].start()\n\n# # Start to show video\n# last_num = 1\n# fps_list = []\n# tmp_time = time.time()\n# while not Global.is_exit:\n# while Global.write_num != last_num:\n# last_num = int(Global.write_num)\n\n# # Calculate fps\n# delay = time.time() - tmp_time\n# tmp_time = time.time()\n# fps_list.append(delay)\n# if len(fps_list) > 5 * worker_num:\n# fps_list.pop(0)\n# fps = len(fps_list) / np.sum(fps_list)\n# print(\"fps: %.2f\" % fps)\n\n# # Calculate frame delay, in order to make the video look smoother.\n# # When fps is higher, should use a smaller ratio, or fps will be limited in a lower value.\n# # Larger ratio can make the video look smoother, but fps will hard to become higher.\n# # Smaller ratio can make fps higher, but the video looks not too smoother.\n# # The ratios below are tested many times.\n# if fps < 6:\n# Global.frame_delay = (1 / fps) * 0.75\n# elif fps < 20:\n# Global.frame_delay = (1 / fps) * 0.5\n# elif fps < 30:\n# Global.frame_delay = (1 / fps) * 0.25\n# else:\n# Global.frame_delay = 0\n\n# # Display the resulting image\n# cv2.imshow('Video', write_frame_list[prev_id(Global.write_num, worker_num)])\n\n# # Hit 'q' on the keyboard to quit!\n# if cv2.waitKey(1) & 0xFF == ord('q'):\n# Global.is_exit = True\n# break\n\n# time.sleep(0.01)\n\n# # Quit\n# cv2.destroyAllWindows()\n","repo_name":"Ayad-Mihidabi-Khan-Jitu/Workspace-Learning","sub_path":"DataScience/OpenCV/Face_Recognition_IP_Cam_with_face-recognition_1_3_0.py","file_name":"Face_Recognition_IP_Cam_with_face-recognition_1_3_0.py","file_ext":"py","file_size_in_byte":15645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"8908046879","text":"n = int(input())\n\nR_tbl = dict() # Create a dictionary to store the resitor\n\nfor i in range(n):\n name, r = input().split()\n R_tbl[name] = int(r)\n\ncircuit = input().split(\" \")\n\nlist = []\nfor c in circuit:\n if c == ')':\n i = list.index('(')\n r = sum(R_tbl[x] for x in list[0:i])\n del list[0:i+1]\n R_tbl[r]=r\n list.insert(0,r)\n elif c == ']':\n i = list.index('[')\n r = 1/sum(1/R_tbl[x] for x in list[0:i])\n del list[0:i+1]\n R_tbl[r]=r\n list.insert(0,r)\n else:\n list.insert(0,c)\n\nprint(\"%.1f\" % list[0])\n","repo_name":"AnnickWONG/CodinGame","sub_path":"EASY/Equivalent Resistance, Circuit Building/Equivalent_Resistance.py","file_name":"Equivalent_Resistance.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"39220400650","text":"# Implement all CRUD elements\n# Reference this: https://github.com/jacobtie/itsc-3155-module-10-demo/blob/main/blueprints/book_blueprint.py\nfrom flask import Blueprint, abort, redirect, render_template, request, session\nfrom models import Comment, Follower, Post, Userprofile, db\n\nrouter = Blueprint('user_profile_router', __name__, url_prefix='/user_profile')\n\n# Hirdhay\n@router.get('')\ndef get_all_user_profile():\n # if the user is not logged in it aborts to 401\n if not 'user' in session:\n abort(401)\n\n all_users = Userprofile.query.all()\n return render_template('all_users.html', users = all_users, user_in_session = session['user']['user_id'])\n\n# Haley\n@router.get('/')\ndef get_single_user_profile(user_id):\n # if the user is not logged in it aborts to 401\n if not 'user' in session:\n abort(401)\n followercount = Follower.query.filter_by(following_id=user_id).count()\n single_user_profile = Userprofile.query.get_or_404(user_id)\n \n isFollowing = False\n x = Follower.query.filter_by(follower_id=session['user']['user_id'], following_id=user_id).first()\n if x is not None:\n isFollowing = True\n \n postnum = Post.query.filter_by(user_id=user_id).count()\n followingcount = Follower.query.filter_by(follower_id=user_id).count()\n\n return render_template('single_user_profile.html', user = single_user_profile, user_in_session = session['user']['user_id'], followercount = followercount, postnum = postnum, followingcount = followingcount, isFollowing = isFollowing)\n\n# Hirdhay\n@router.get('//edit')\ndef get_edit_user_profile_form(user_id):\n user_to_edit = Userprofile.query.get_or_404(user_id)\n return render_template('editprofile.html', user = user_to_edit, user_in_session = session['user']['user_id'])\n\n# Hirdhay\n@router.post('/')\ndef update_user_profile(user_id):\n user_to_update = Userprofile.query.get_or_404(user_id)\n name = request.form.get('name', '')\n location = request.form.get('location', '')\n biography = request.form.get('biography', '')\n\n if location == '' or biography == '':\n abort(400)\n\n\n user_to_update.user_location = location\n user_to_update.user_biography = biography\n\n db.session.commit()\n\n #return redirect(f'/user_profile/{user_id}', user_in_session = session['user']['user_id'])\n return redirect(f'/user_profile/{user_id}')\n \n# Hirdhay\n@router.post('//delete')\ndef delete_user_profile(user_id):\n print(\"here\" + user_id)\n user_to_endit = Userprofile.query.get_or_404(user_id)\n\n #must delete all posts made by user and all comments related to post made by said user\n posts_to_delete = Post.query.filter_by(user_id=user_to_endit.user_id).all() \n for post in posts_to_delete: #you have to delete all comments related to that post before deleting the post\n comments_to_delete = Comment.query.filter_by(post_id=post.post_id).all()\n for comment in comments_to_delete: #you have to delete all comments related to that post before deleting the post\n db.session.delete(comment)\n db.session.delete(post)\n \n comments_by_user = Comment.query.filter_by(user_id=user_to_endit.user_id).all()\n\n #have to delete all comments made by said user\n for comment in comments_by_user:\n db.session.delete(comment)\n\n follow1 = Follower.query.filter_by(follower_id=user_to_endit.user_id).all()\n follow2 = Follower.query.filter_by(following_id=user_to_endit.user_id).all()\n #delete from follower-follower\n for follow in follow1:\n db.session.delete(follow)\n for follow in follow2:\n db.session.delete(follow)\n\n #sign user out\n if 'user' not in session:\n abort(401)\n\n # delete the user session\n del session['user']\n #finally delete user\n db.session.delete(user_to_endit)\n db.session.commit()\n return redirect('/')\n\n@router.post('//follow')\ndef follow_user(user_id):\n follower_id = session['user']['user_id']\n following_id = user_id\n\n already = Follower.query.filter_by(follower_id=follower_id, following_id=following_id).first()\n print(already)\n\n\n if already is not None:\n db.session.delete(already)\n else:\n new = Follower(follower_id=follower_id, following_id=following_id)\n db.session.add(new)\n\n db.session.commit()\n\n\n return redirect(f'/user_profile/{user_id}')\n\n","repo_name":"thompaw/3155Project","sub_path":"blueprints/user_profile_blueprint.py","file_name":"user_profile_blueprint.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23454391411","text":"#!python\r\n#shyness.py\r\nimport sys\r\n\r\ndef main(argv):\r\n file = open(\"A-large.in\", 'r')\r\n out = open(\"ouputshyness.txt\", 'w')\r\n \r\n cases = int(file.readline())\r\n on_case = 1\r\n \r\n for line in file:\r\n case = line.split(' ')\r\n max = int(case[0])\r\n standing = 0\r\n friends = 0\r\n for i in range(0, max + 1):\r\n if standing < i:\r\n friends += i - standing\r\n standing = i\r\n standing += int(case[1][i])\r\n \r\n out.write('Case #' + str(on_case) + ': ' + str(friends) + '\\n')\r\n on_case += 1\r\n\r\nif __name__ == \"__main__\":\r\n main(sys.argv)","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_155/3221.py","file_name":"3221.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"19029559304","text":"\"\"\"\nGiven a list of words like so:\nwords = [\n 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',\n 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',\n 'eyes', \"don't\", 'look', 'around', 'the', 'eyes', 'look', 'into',\n 'my', 'eyes', \"you're\", 'under'\n]\nWrite a python snippet to find the words that occur most often. You output should look something like the following:\n[('eyes', 8), ('the', 5), ('look', 4)]\n\"\"\"\n\nimport operator\n\nclass WordCounter(object):\n\n def __init__(self, wordList):\n self.workList = sorted(wordList)\n self.wordLister()\n\n def wordLister(self):\n self.counted = {}\n for word in self.workList:\n if not word in self.counted:\n self.counted[word] = 0\n self.counted[word] += 1 \n self.summaryList = sorted(self.counted.items(), key = operator.itemgetter[1], reverse = True)\n\n print(self.summaryList)\n\nwords = [\n 'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',\n 'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',\n 'eyes', \"don't\", 'look', 'around', 'the', 'eyes', 'look', 'into',\n 'my', 'eyes', \"you're\", 'under'\n]\n\nrezo = WordCounter(words)\n\n","repo_name":"shoe61/2143-OOP-Schumacher","sub_path":"scraps/underDog.py","file_name":"underDog.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"23569854281","text":"from math import ceil\n\ndef solve(a, b, mans):\n if mans == 1:\n return (int((b-a)/2) + (b-a)%2 - 1, int((b-a)/2 - 1))\n else:\n if (b-a)%2:\n t = mans%2\n t = 0 if t == 1 else 1\n return solve(a, int(b/2) + t, int(mans/2))\n else:\n return solve(a, int(b/2) + 1, int(mans/2))\n\n\nt = int(input())\n\nfor i in range(1, t + 1):\n n, k = [int(s) for s in input().split(\" \")]\n\n l = solve(1, n+2, k)\n print (\"Case #{0}: {1} {2}\".format(i, l[0], l[1]))\n\n\n\n \n","repo_name":"dr-dos-ok/Code_Jam_Webscraper","sub_path":"solutions_python/Problem_201/2278.py","file_name":"2278.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"25447877658","text":"from PIL import Image\n\nASCII_CHARS = \"MNHQ$OC?7>!:-;. \"\nNUM_ASCII_CHARS = len(ASCII_CHARS)\n\n\ndef render_frame(frame, width, height):\n scaled_image = frame.resize((width, height), Image.BILINEAR)\n pixels = scaled_image.load()\n\n string = \"\"\n for row in range(height):\n for col in range(width):\n pixel = pixels[col, row] # RGB\n rgb = pixel[:3]\n avg_rgb = sum(rgb) / 3.0\n string += ASCII_CHARS[int(avg_rgb / 256.0 * NUM_ASCII_CHARS)]\n\n string += \"\\n\"\n return string\n\n\ndef render_ascii_art(image, width, height):\n while True:\n try:\n yield render_frame(image.convert(\"RGB\"), width, height)\n image.seek(image.tell() + 1)\n except EOFError:\n break\n\n\ndef get_image_duration(image):\n return image.info.get(\"duration\", 1000)\n\n","repo_name":"kabisa/falcon_ascii_renderer","sub_path":"app/ascii/renderer.py","file_name":"renderer.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40097354034","text":"import torch\nimport torch.nn as nn\nfrom torch.utils.data import Dataset\nfrom torchvision import datasets\nimport numpy as np\n\nimport os\nfrom glob import glob\n\nimport gdown\nimport nibabel as nib\nfrom zipfile import ZipFile\nfrom tqdm import tqdm\nfrom skimage.transform import resize\n\n\n\nclass Brats2020Dataset2020(Dataset):\n\n URL = 'https://drive.google.com/uc?id=1fjhJKi6Cs71MpbTa_u4oHHKF3rO41F97&export=download'\n OUT_FILE = 'micca_train_2.zip'\n UNZIP_FOLDER = 'dataset/miccai_train'\n\n def __init__(self, root, train=True, transform=None, download=False, resize_=True, normalize_ = True):\n self.root = os.path.expanduser(root)\n self.transform = transform\n self.train = train # training set or test set\n self.UNZIP_FOLDER = os.path.join(self.root, self.UNZIP_FOLDER)\n self.resize_ = resize_\n self.normalize_ = normalize_\n # Creating necessary Directories\n self.make_dirs()\n\n if download and not self._check_exists():\n self.download()\n self.extract()\n self.arrange()\n\n if not self._check_exists():\n raise RuntimeError('Dataset not found.' +\n ' You can use download=True to download it')\n\n self.folder_prefix = \"BraTS20_Training\"\n self.all_files = glob(os.path.join(\n self.UNZIP_FOLDER) + \"/{instance_folder}*/{instance_folder}*.gz\".format(instance_folder=self.folder_prefix))\n self.images_t1c = np.array(\n sorted([file for file in self.all_files if file.endswith('t1ce.nii.gz')]))\n self.images_seg = np.array(\n sorted([file for file in self.all_files if file.endswith('seg.nii.gz')]))\n # np.random.seed(42)\n self.perm = np.random.permutation(len(self.images_t1c))\n self.split = int(0.8 * len(self.perm))\n\n if self.train:\n self.images_t1c = self.images_t1c[self.perm[:self.split]]\n self.images_seg = self.images_seg[self.perm[:self.split]]\n else:\n self.images_t1c = self.images_t1c[self.perm[self.split:]]\n self.images_seg = self.images_seg[self.perm[self.split:]]\n\n def _check_exists(self):\n return os.path.exists(self.UNZIP_FOLDER)\n\n def make_dirs(self):\n dirslist = [self.UNZIP_FOLDER]\n for dir_ in dirslist:\n if not os.path.exists(dir_):\n os.mkdir\n\n def download(self):\n print(\"Dwonload Started !!!\")\n gdown.download(self.URL, output=None, quiet=False)\n print(\"Dwonload Finished !!!\")\n\n def extract(self):\n print(\"Unzipping the File\")\n with ZipFile(file=os.path.join(self.root, self.OUT_FILE)) as zip_file:\n for file in tqdm(iterable=zip_file.namelist(), total=len(zip_file.namelist())):\n zip_file.extract(\n member=file, path=os.path.join(self.root, 'dataset'))\n print(\"Done\")\n\n def arrange(self):\n # Removing the Zipped File\n print(\"Removing the Zipped File\")\n self.zipfile_ = os.path.join(self.root, self.OUT_FILE)\n if os.path.exists(self.zipfile_):\n os.remove(self.zipfile_)\n print(\"Removing the unwated files\")\n\n self.folder_prefix = \"BraTS20_Training\"\n self.all_files = glob(os.path.join(\n self.UNZIP_FOLDER) + \"/{instance_folder}*/{instance_folder}*.gz\".format(instance_folder=self.folder_prefix))\n for i in self.all_files:\n if not i.endswith('t1ce.nii.gz') and not i.endswith('seg.nii.gz'):\n os.remove(i)\n\n def resize(self, data: np.ndarray):\n data = resize(data, (80, 120, 120), preserve_range=True)\n return data\n\n def normalize(self, data: np.ndarray):\n data_min = np.min(data)\n return (data - data_min) / (np.max(data) - data_min)\n\n def __len__(self):\n return len(self.images_t1c)\n\n def __getitem__(self, index):\n\n img, target = nib.load(self.images_t1c[index]), nib.load(self.images_seg[index])\n \n img, target = img.get_fdata(), target.get_fdata()\n\n target = ((target == 1) | (target == 4)).astype('float32')\n\n # target = np.clip(target.astype(np.uint8), 0, 1).astype(np.float32)\n # target = np.clip(target, 0, 1)\n\n if self.normalize_:\n img = self.normalize(img)\n\n if self.transform:\n img = self.transform(img)\n target = self.transform(target)\n\n if self.resize_:\n img = self.resize(img)\n target = self.resize(target)\n\n \n # Creating channels as single channels \n img = torch.FloatTensor(img).unsqueeze(0)\n target = torch.FloatTensor(target).unsqueeze(0)\n return img, target\n \n","repo_name":"rohitkuk/Brain_Tumour_Segmentation_3D_MRI","sub_path":"src/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4740,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"20829440997","text":"def reverse_string(str1): \r\n rev_str = \"\"\r\n for i in range(len(str1)-1,-1,-1):\r\n rev_str+=a[i]\r\n return rev_str\r\n\r\nprint(\"***** REVERSE A STRING *****\")\r\nch = 'y'\r\nwhile(ch=='y' or ch=='Y'):\r\n a = input(\"\\nEnter a String: \")\r\n print(\"Reverse of \", a,\" is: \", reverse_string(a))\r\n\r\n ch = input(\"\\nWant to continue?(y/n): \")\r\ninput()\r\n","repo_name":"BhoomikaSingh20/Python","sub_path":"curves_using_matplotlib_numpy.py","file_name":"curves_using_matplotlib_numpy.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"3615851167","text":"class Search(object):\n \"\"\"description of class\"\"\"\n @staticmethod\n def BS(list, key):\n low = 0\n high = len(list) - 1\n while (low <= high):\n mid = int((low + high) / 2)\n guess = list[mid]\n if (guess == key):\n return mid\n if (guess < key):\n low = mid + 1\n else:\n high = mid - 1\n return None","repo_name":"Mohamed-Gnana/Grokking-Algorithms","sub_path":"ChapterOne/BinarySearchPython/BinarySearchPython/Common.py","file_name":"Common.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"22022388613","text":"#!/usr/bin/env python3\n\n\"\"\"Wrapper that adds exclusive locks, timeouts, timestamp accounting,\nmax frequency, logging, etc... to running cron jobs.\n\"\"\"\n\nimport datetime\nimport logging\nimport os\nimport sys\nfrom typing import Optional\n\nfrom pyutils import bootstrap, config, exec_utils, stopwatch\nfrom pyutils.datetimes import datetime_utils\nfrom pyutils.exceptions import PyUtilsLockfileException\nfrom pyutils.files import file_utils, lockfile\n\nlogger = logging.getLogger(__name__)\n\ncfg = config.add_commandline_args(\n f\"Python Cron Runner ({__file__})\",\n \"Wrapper for cron commands with locking, timeouts, and accounting.\",\n)\ncfg.add_argument(\n \"--lockfile\",\n default=None,\n metavar=\"LOCKFILE_PATH\",\n help=\"Path to the lockfile to use to ensure that two instances of a command do not execute contemporaneously.\",\n)\ncfg.add_argument(\n \"--lockfile_audit_record\",\n default=None,\n metavar=\"LOCKFILE_AUDIT_RECORD_FILENAME\",\n help=\"Path to a record of when the logfile was held/released and for what reason\",\n)\ncfg.add_argument(\n \"--timeout\",\n type=str,\n metavar=\"TIMEOUT\",\n default=None,\n help='Maximum time for lock acquisition + command execution. Undecorated for seconds but \"3m\" or \"1h 15m\" work too.',\n)\ncfg.add_argument(\n \"--timestamp\",\n type=str,\n metavar=\"TIMESTAMP_FILE\",\n default=None,\n help=\"The /timestamp/TIMESTAMP_FILE file tracking the work being done; files' mtimes will be set to the last successful run of a command for accounting purposes.\",\n)\ncfg.add_argument(\n \"--max_frequency\",\n type=str,\n metavar=\"FREQUENCY\",\n default=None,\n help='The maximum frequency with which to do this work; even if the wrapper is invoked more often than this it will not run the command. Requires --timestamp. Undecorated for seconds but \"3h\" or \"1h 15m\" work too.',\n)\ncfg.add_argument(\n \"--command\",\n nargs=\"*\",\n required=True,\n type=str,\n metavar=\"COMMANDLINE\",\n help=\"The commandline to run under a lock.\",\n)\nconfig.overwrite_argparse_epilog(\n \"\"\"\ncron.py's exit value:\n\n -1000 = some internal error occurred (see exception log).\n 0 = we exited early due to not enough time passage since the last\n invocation of --command.\n 1000 = we could not obtain the lockfile; someone else owns it.\n else = if the --command was run successfully, cron.py will exit with\n the same code that the subcommand exited with.\n\"\"\"\n)\n\n\ndef run_command(timeout: Optional[int], timestamp_file: Optional[str]) -> int:\n \"\"\"Run cron command\"\"\"\n cmd = \" \".join(config.config[\"command\"])\n logger.info('cron cmd = \"%s\"', cmd)\n logger.debug(\"shell environment:\")\n for var in os.environ:\n val = os.environ[var]\n logger.debug(\"%s = %s\", var, val)\n logger.debug(\"____ (↓↓↓ output from the subprocess appears below here ↓↓↓) ____\")\n try:\n with stopwatch.Timer() as t:\n ret = exec_utils.cmd_exitcode(cmd, timeout)\n logger.debug(\n \"____ (↑↑↑ subprocess finished in %.2fss, exit value was %d ↑↑↑) ____\",\n t(),\n ret,\n )\n if ret == 0 and timestamp_file is not None and os.path.exists(timestamp_file):\n logger.debug(\"Touching %s\", timestamp_file)\n file_utils.touch_file(timestamp_file)\n return ret\n except Exception:\n msg = \"Cron subprocess failed; giving up.\"\n logger.exception(msg)\n print(\"Cron subprocess failed, giving up.\", file=sys.stderr)\n return -1000\n\n\n@bootstrap.initialize\ndef main() -> int:\n \"\"\"Entry point\"\"\"\n if config.config[\"timestamp\"]:\n timestamp_file = f\"/timestamps/{config.config['timestamp']}\"\n if not file_utils.does_file_exist(timestamp_file):\n logger.error(\n \"--timestamp argument's target file (%s) must already exist.\",\n timestamp_file,\n )\n sys.exit(-1)\n else:\n timestamp_file = None\n if config.config[\"max_frequency\"]:\n config.error(\n \"The --max_frequency argument requires the --timestamp argument.\"\n )\n\n now = datetime.datetime.now()\n if timestamp_file is not None and os.path.exists(timestamp_file):\n max_frequency = config.config[\"max_frequency\"]\n if max_frequency is not None:\n max_delta = datetime_utils.parse_duration(max_frequency)\n if max_delta > 0:\n mtime = file_utils.get_file_mtime_as_datetime(timestamp_file)\n delta = now - mtime\n if delta.total_seconds() < max_delta:\n logger.info(\n \"It's only been %s since we last ran successfully; bailing out.\",\n datetime_utils.describe_duration_briefly(delta.total_seconds()),\n )\n sys.exit(0)\n\n timeout = config.config[\"timeout\"]\n if timeout is not None:\n timeout = datetime_utils.parse_duration(timeout)\n assert timeout > 0\n logger.debug(\"Timeout is %ss\", timeout)\n lockfile_expiration = datetime.datetime.now().timestamp() + timeout\n else:\n logger.warning(\"Timeout not specified; no lockfile expiration.\")\n lockfile_expiration = None\n\n lockfile_path = config.config[\"lockfile\"]\n if lockfile_path is not None:\n logger.debug(\"Attempting to acquire lockfile %s...\", lockfile_path)\n try:\n with lockfile.LockFile(\n lockfile_path,\n do_signal_cleanup=True,\n override_command=\" \".join(config.config[\"command\"]),\n expiration_timestamp=lockfile_expiration,\n ) as lf:\n record = config.config[\"lockfile_audit_record\"]\n cmd = \" \".join(config.config[\"command\"])\n if record:\n start = lf.locktime\n with open(record, \"a\") as wf:\n print(f\"{lockfile_path}, ACQUIRE, {start}, {cmd}\", file=wf)\n retval = run_command(timeout, timestamp_file)\n if record:\n end = datetime.datetime.now().timestamp()\n duration = datetime_utils.describe_duration_briefly(end - start)\n with open(record, \"a\") as wf:\n print(\n f\"{lockfile_path}, RELEASE({duration}), {end}, {cmd}\",\n file=wf,\n )\n return retval\n except PyUtilsLockfileException:\n msg = f\"Failed to acquire {lockfile_path}, giving up.\"\n logger.exception(msg)\n print(msg, file=sys.stderr)\n return 1000\n else:\n logger.debug(\"No lockfile indicated; not locking anything.\")\n return run_command(timeout, timestamp_file)\n\n\nif __name__ == \"__main__\":\n # Insist that our logger.whatever('messages') make their way into\n # syslog with a facility=LOG_CRON, please. Yes, this is hacky.\n sys.argv.append(\"--logging_syslog\")\n sys.argv.append(\"--logging_syslog_facility=CRON\")\n main()\n","repo_name":"scottgasch/pyutils","sub_path":"examples/cron/cron.py","file_name":"cron.py","file_ext":"py","file_size_in_byte":7115,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"61"}
+{"seq_id":"17822470101","text":"import math, random\nfrom simulation import *\n#import gym\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.autograd as autograd \nimport torch.nn.functional as F\n\nfrom common.layers import NoisyLinear\nfrom common.replay_buffer import ReplayBuffer\nfrom gen_dataset import *\nUSE_CUDA = torch.cuda.is_available()\nVariable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)\n\n\nclass RainbowDQN(nn.Module):\n def __init__(self, num_inputs, num_actions, num_atoms, Vmin, Vmax):\n super(RainbowDQN, self).__init__()\n \n self.num_inputs = num_inputs\n self.num_actions = num_actions\n self.num_atoms = num_atoms\n self.Vmin = Vmin\n self.Vmax = Vmax\n # Markovian\n numNodes = 16\n # NonMarkovian\n # numNodes = 48\n\n self.linear1 = nn.Linear(num_inputs, numNodes)\n self.linear2 = nn.Linear(numNodes, numNodes)\n \n # numNodes = 16\n\n self.noisy_value1 = NoisyLinear(numNodes, numNodes, use_cuda=USE_CUDA)\n self.noisy_value2 = NoisyLinear(numNodes, self.num_atoms, use_cuda=USE_CUDA)\n \n self.noisy_advantage1 = NoisyLinear(numNodes, numNodes, use_cuda=USE_CUDA)\n self.noisy_advantage2 = NoisyLinear(numNodes, self.num_atoms * self.num_actions, use_cuda=USE_CUDA)\n \n def forward(self, x):\n batch_size = x.size(0)\n \n x = F.relu(self.linear1(x))\n x = F.relu(self.linear2(x))\n \n value = F.relu(self.noisy_value1(x))\n value = self.noisy_value2(value)\n \n advantage = F.relu(self.noisy_advantage1(x))\n advantage = self.noisy_advantage2(advantage)\n \n value = value.view(batch_size, 1, self.num_atoms)\n advantage = advantage.view(batch_size, self.num_actions, self.num_atoms)\n \n x = value + advantage - advantage.mean(1, keepdim=True)\n x = F.softmax(x.view(-1, self.num_atoms)).view(-1, self.num_actions, self.num_atoms)\n \n return x\n \n def reset_noise(self):\n self.noisy_value1.reset_noise()\n self.noisy_value2.reset_noise()\n self.noisy_advantage1.reset_noise()\n self.noisy_advantage2.reset_noise()\n \n def act(self, state):\n state = Variable(torch.FloatTensor(state).unsqueeze(0), volatile=True)\n dist = self.forward(state).data.cpu()\n dist = dist * torch.linspace(self.Vmin, self.Vmax, self.num_atoms)\n action = dist.sum(2).max(1)[1].numpy()[0]\n return action\n\n\n\ndef update_target(current_model, target_model):\n target_model.load_state_dict(current_model.state_dict())\n\ndef projection_distribution(next_state, rewards, dones,Vmax,Vmin,num_atoms,target_model,batch_size):\n batch_size = next_state.size(0)\n \n delta_z = float(Vmax - Vmin) / (num_atoms - 1)\n support = torch.linspace(Vmin, Vmax, num_atoms)\n \n next_dist = target_model(next_state).data.cpu() * support\n next_action = next_dist.sum(2).max(1)[1]\n next_action = next_action.unsqueeze(1).unsqueeze(1).expand(next_dist.size(0), 1, next_dist.size(2))\n next_dist = next_dist.gather(1, next_action).squeeze(1)\n \n rewards = rewards.unsqueeze(1).expand_as(next_dist)\n dones = dones.unsqueeze(1).expand_as(next_dist)\n support = support.unsqueeze(0).expand_as(next_dist)\n \n Tz = rewards + (1 - dones) * 0.99 * support\n Tz = Tz.clamp(min=Vmin, max=Vmax)\n b = (Tz - Vmin) / delta_z\n l = b.floor().long()\n u = b.ceil().long()\n \n offset = torch.linspace(0, (batch_size - 1) * num_atoms, batch_size).long()\\\n .unsqueeze(1).expand(batch_size, num_atoms)\n\n proj_dist = torch.zeros(next_dist.size()) \n proj_dist.view(-1).index_add_(0, (l + offset).view(-1), (next_dist * (u.float() - b)).view(-1))\n proj_dist.view(-1).index_add_(0, (u + offset).view(-1), (next_dist * (b - l.float())).view(-1))\n \n return proj_dist\n\ndef compute_td_loss(batch_size,replay_buffer,Vmax,Vmin,num_atoms,current_model,target_model,optimizer):\n state, action, reward, next_state, done = replay_buffer.sample(batch_size) \n #print('Vmax = ',Vmax)\n \n state = Variable(torch.FloatTensor(np.float32(state)))\n next_state = Variable(torch.FloatTensor(np.float32(next_state)), volatile=True)\n action = Variable(torch.LongTensor(action))\n reward = torch.FloatTensor(reward)\n done = torch.FloatTensor(np.float32(done))\n #print(state)\n proj_dist = projection_distribution(next_state, reward, done,Vmax,Vmin,num_atoms,target_model,batch_size)\n \n dist = current_model(state)\n action = action.unsqueeze(1).unsqueeze(1).expand(batch_size, 1, num_atoms)\n dist = dist.gather(1, action).squeeze(1)\n dist.data.clamp_(0.01, 0.99)\n loss = -(Variable(proj_dist) * dist.log()).sum(1)\n loss = loss.mean()\n #print(loss) \n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n current_model.reset_noise()\n target_model.reset_noise()\n \n return loss\n\nif __name__ == \"__main__\":\n path = './model/modelps1.pt'\n ps = 1\n n = 10\n dict1 = gen_data(n)\n\n num_input = 3\n \n action_dict = dict()\n actions = [32,48,64,80,96,112,128]\n for i in range(len(actions)):\n action_dict[i]=actions[i]\n\n other_action_dict = dict()\n other_action_dict[0] = 32\n other_action_dict[1] = 128\n\n num_states = 3\n num_action = len(actions)\n eplen = 20\n\n env = commEnv(ps,dict1,action_dict,other_action_dict,eplen)\n \n\n # env = commEnv(ps,dict1,action_dict)\n\n\n num_atoms = 5\n Vmin = 16\n Vmax = 20\n\n current_model = RainbowDQN(num_input, num_action, num_atoms, Vmin, Vmax)\n target_model = RainbowDQN(num_input, num_action, num_atoms, Vmin, Vmax)\n\n if USE_CUDA:\n current_model = current_model.cuda()\n target_model = target_model.cuda()\n \n optimizer = optim.Adam(current_model.parameters(), 0.0001)\n\n replay_buffer = ReplayBuffer(10000)\n\n update_target(current_model, target_model)\n\n num_frames = 10000\n batch_size = 32\n gamma = 1\n\n losses = []\n all_rewards = []\n episode_reward = 0\n\n state = env.reset()\n # print(state)\n for frame_idx in range(1, num_frames + 1):\n action = current_model.act(state)\n # print('action = ',action) \n next_state, reward, done, _= env.step(action)\n replay_buffer.push(state, action, reward, next_state, done)\n \n #print(reward)\n state = next_state\n #print(cw_min)\n episode_reward += reward\n if episode_reward > 195:\n break \n if done:\n print('Frame = ',frame_idx,'Reward = ',episode_reward)\n state= env.reset()\n all_rewards.append(episode_reward)\n episode_reward = 0\n \n if len(replay_buffer) > batch_size:\n #print('======================================= Start Training =========================================')\n loss = compute_td_loss(batch_size,replay_buffer,Vmax,Vmin,num_atoms,current_model,target_model,optimizer)\n #print(loss)\n losses.append(loss.data)\n #if frame_idx % 200 == 0:\n # plot(frame_idx, all_rewards, losses)\n \n if frame_idx % 500 == 0:\n update_target(current_model, target_model)\n #print(all_rewards)\n torch.save(current_model.state_dict(),path)","repo_name":"kumarabhish3k/Rainbow-DQN-for-Contention-Window-design","sub_path":"rainbow.py","file_name":"rainbow.py","file_ext":"py","file_size_in_byte":7505,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"61"}
+{"seq_id":"11679007807","text":"'''\n\tPython learning \n\tday1.py\n'''\nfrom tkinter import *\nfrom tkinter.ttk import *\n########################################################################\n'''\nevent\n'''\n# def display(event):\n# \tglobal root\n# \tw2=Label(root,text=\"Hello,World!\")\n# \tw2.pack()\n\n\n# root =Tk()\n# b1=Button(root,text=\"请点击!\")\n# b1['width']=20\n# b1['height']=4\n# # b1['background']='red'\n# b1.bind(\"\",display)\n# b1.pack()\n\n# root.mainloop()\n########################################################################\n'''\npack()\n'''\n# root =Tk()\n# Button(root,text='A').pack(side=LEFT,expand=YES,fill=Y)\n# Button(root,text='B').pack(side=TOP,expand=NO,fill=BOTH)\n# Button(root,text='C').pack(side=RIGHT,expand=YES,fill=NONE,anchor=NE)\n# Button(root,text='D').pack(side=LEFT,expand=NO,fill=Y,anchor=NW)\n# Button(root,text='E').pack(side=TOP,expand=NO,fill=NONE,anchor=NW)\n# Button(root,text='F').pack(side=BOTTOM,expand=NO,fill=NONE,anchor=NW)\n# Button(root,text='G').pack(anchor=SE)\n# root.mainloop()\n########################################################################\n'''\ngrid() password LoginBox()\n'''\nroot=Tk()\ne=StringVar()\nu=StringVar()\n\ndef cls1(event):\n\tglobal e\n\te.set(\"\")\n\n\ndef cls2(event):\n\tglobal u\n\tu.set(\"\")\n\n\nLabel(root,text=\"账号:\").grid(row=0,sticky=W)\nentry1=Entry(root,textvariable=e)\ne.set(\"input your name here\")\nentry1.bind('',cls1)\n# entry1.selection_clear()\nentry1.grid(row=0,column=1,sticky=E)\n\n\n\nLabel(root,text=\"密码:\").grid(row=1,sticky=W)\nentry2=Entry(root,textvariable=u,show='*')\nentry2.bind('',cls2)\nentry2.grid(row=1,column=1,sticky=E)\ndef callback():\n\tt1 = entry1.get()\n\tt2 = entry2.get()\n\tt3=StringVar()\n\tif (t1 == \"admin\") & (t2 == \"admin\"):\n\t\tt3.set(\"登录成功\")\n\telse:\n\t\tt3.set(\"登录失败\")\n\t\tentry1.delete(0,len(t1))\n\t\tentry2.delete(0,len(t2))\n\tLabel(root,textvariable=t3).grid(row=3,column=0,sticky=EW)\n\t\n\nButton(root,text=\"登录\",command=callback).grid(row=2,column=1,sticky=EW)\n\nroot.mainloop()\n\n'''\ne.delete()删除内容\n-- 删除参数 first 到 last 范围内(包含 first 和 last)的所有内容\n-- 如果忽略 last 参数,表示删除 first 参数指定的选项\n-- 使用 delete(0, END) 实现删除输入框的所有内容\n'''\n\n'''\n************tkinter 的布局 ****************\n1. 其实我们已经接触过 tkinter 的一种布局,就是 pack 布局,它非常简单,我们不用做过多的设置,直接使用一个pack 函数就可以了。\n2.grid 布局: grid 可以理解为网格,或者表格,它可以把界面设置为几行几列的网格,我们在网格里插入我们想要的元素。这种布局的好处\n是不管我们如何拖动窗口,相对位置是不会变化的,而且这种布局也超简单。\n3.place 布局:它直接使用死板的位置坐标来布局,这样做的最大的问题在于当我们向窗口添加一个新部件的时候,又得重新测一遍数据,且\n我们不能随便地变大或者缩小窗口,否则,可能会导致混乱。\n**************pack 布局 *************\n1. 我们使用 pack 函数的时候,默认先使用的放到上面,然后 依次向下排,它会给我们的组件一个自认为合适的位置和大小,这是默认方式,\n也是我们上面一直采用的方式。\n2. pack 函数也可以接受几个参数, side 参数指定了它停靠在哪个方向,可以为 LEFT,TOP,RIGHT,BOTTOM, 分别代表左,上,右,下,它的 \nfill 参数可以是 X,Y,BOTH 和 NONE,即在水平方向填充,竖直方向填充,水平和竖直方向填充和不填充。\n3. 它的 expand 参数可以是 YES和 NO,它的 anchor 参数可以是 N,E,S,W(这里的 NESW分别表示北东南西,这里分别表示上右下左)以及\n他们的组合或者是 CENTER(表示中间)。\n4. 它的 ipadx 表示的是内边距的 x 方向,它的 ipady 表示的是内边距的 y 方向, padx 表示的是外边距的 x 方向,pady 表示的是外边距\n的 y 方向。\n**************grid 布局 *************\n1. 由于我们的程序大多数都是矩形,因此特别适合于网格布局,也就是 grid 布局。\n2. 使用 grid 布局的时候,我们使用 grid 函数,在里面指定两个参数,用 row 表示行,用 column 表示列,其中值得注意的是 row 和 column \n的编号都从 0 开始。\n3.grid 函数还有个 sticky 参数,它可以用 N, E, S, W表示上右下左,它决定了这个组件是从哪个方向开始的,下面的例子可以很好的解释这一点。\n4.grid 布局直接用后面的行和列的数字来指定了它位于哪个位置,而不必使用其他参数。\n5.grid 函数也支持诸如 ipadx , ipady , padx, pady,它们的意思和 pack 函数是一样的,默认边距是 0。\n6. 它还支持参数比如 rowspan ,表示跨越的行数,columnspan 表示跨越的列数。\n *************place 布局 *************\n1. 关于 place 布局,可能是最有东西好讲的,但是,也是我最不愿意讲的。\n2. 它使用 place 函数,它分为绝对布局和相对布局,绝对布局使用 x 和 y 参数,相对布局使用 relx , rely ,relheight 和 relwidth 参数。\n3. 由于该方法我极度不推荐大家用,因此也就不继续说了。\n*************** 总结 **************\n1. 由于 place 我不推荐大家用,也就 pack 和 grid 布局好一些。\n2. 但是 pack 和 grid 不能同时用,通常对于较为复杂点的,我还是建议大家用 gird 。\n''' \n","repo_name":"RJocket/lerning","sub_path":"day1_LoginBox.py","file_name":"day1_LoginBox.py","file_ext":"py","file_size_in_byte":5472,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"40852429094","text":"from django.contrib.auth.mixins import LoginRequiredMixin\nfrom django.db.models import Count, Q\nfrom django.http import JsonResponse\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import redirect\nfrom django.urls.base import reverse, reverse_lazy\nfrom django.utils import timezone\nfrom django.views.generic import ListView, DetailView, FormView, TemplateView\nfrom django.views.generic.detail import SingleObjectMixin\nfrom django.views import View\n\nfrom .models import People, Genre, Movie, CastAndCrew, Review\nfrom .forms import ReviewForm\n\n\nclass MovieListView(ListView):\n\n model = Genre\n context_object_name = 'genre_list'\n template_name = 'movie_list.html'\n\n def get_queryset(self):\n\n return Genre.objects.annotate(review_count=Count('movies__reviews')).order_by('-review_count')[:10]\n\nclass GenreListView(ListView):\n\n model = Genre\n context_object_name = 'genre_list'\n template_name = 'genre_list.html'\n ordering = ['genre']\n\nclass GenreDetailView(DetailView):\n\n model = Genre\n context_object_name = 'genre'\n template_name = 'genre_detail.html'\n\nclass MovieDetailView(DetailView):\n\n model = Movie\n context_object_name = 'movie'\n template_name = 'movie_detail.html'\n\n def get_context_data(self, **kwargs): \n context = super(MovieDetailView, self).get_context_data(**kwargs)\n if self.request.user.is_authenticated:\n context['user_review'] = self.get_object().reviews.all().filter(author=self.request.user).first()\n context['review_form'] = ReviewForm()\n context['reviews'] = self.get_object().reviews.all().order_by('-date_posted')\n return context\n\nclass ReviewFormView(SingleObjectMixin, FormView):\n\n template_name = 'movie_detail.html'\n form_class = ReviewForm\n model = Movie\n\n def post(self, request, *args, **kwargs):\n \n if not request.user.is_authenticated:\n return HttpResponse('You must be logged in to review.')\n self.object = self.get_object()\n return super().post(request, *args, **kwargs)\n\n def form_valid(self, form):\n \n form.instance.author = self.request.user\n form.instance.movie = self.object\n form.save()\n return super().form_valid(form)\n\n def get_success_url(self):\n \n return reverse('movie_detail', args=[str(self.object.id)])\n\nclass MovieHybridView(View):\n\n def get(self, request, *args, **kwargs):\n \n view = MovieDetailView.as_view()\n return view(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n \n view = ReviewFormView.as_view()\n return view(request, *args, **kwargs)\n\nclass PeopleDetailView(DetailView):\n\n model = People\n context_object_name = 'people'\n template_name = 'people_detail.html'\n\ndef fetch_get_search(request):\n\n movies = Movie.objects.annotate(review_count=Count('reviews')).order_by('-review_count')\n people = People.objects.all().order_by('name')\n genres = Genre.objects.all().order_by('genre')\n data = {\n 'movies': [],\n 'people': [],\n 'genres': []\n }\n for movie in movies:\n avg_review = movie.avg_review\n data['movies'].append({\n 'title': movie.title,\n 'link': movie.get_absolute_url(),\n 'cover': movie.cover.url,\n 'date_released': movie.date_released,\n 'avg_review': avg_review,\n 'movie_rated':movie.movie_rated,\n 'distribution_company':movie.distribution_company\n })\n for person in people:\n data['people'].append({\n 'name': person.name,\n 'link': person.get_absolute_url(),\n 'picture': person.picture.url,\n 'birth_date': person.birth_date,\n 'birth_place': person.birth_place\n })\n for genre in genres:\n data['genres'].append({\n 'genre': genre.genre,\n 'link': genre.get_absolute_url()\n })\n return JsonResponse(data)\n\nclass SearchView(TemplateView):\n\n template_name = 'search_list.html'\n\n def get_context_data(self, **kwargs):\n \n context = {}\n search = self.request.GET.get('search')\n context['search_string'] = search\n context['movie_list'] = Movie.objects.filter(\n Q(title__icontains=search) |\n Q(distribution_company__icontains=search) |\n Q(crew__person__name__icontains=search) |\n Q(crew__role__icontains=search) |\n Q(genre__genre__icontains=search)\n ).distinct().order_by('title')\n context['people_list'] = People.objects.filter(\n Q(name__icontains=search) |\n Q(roles__role__icontains=search) |\n Q(roles__movie__title__icontains=search)\n ).distinct().order_by('name')\n context['genre_list'] = Genre.objects.filter(\n Q(genre__icontains=search) |\n Q(movies__title__icontains=search)\n ).distinct().order_by('genre')\n return context\n\ndef fetch_get_reviews(request):\n\n reviews = Review.objects.all().filter(author=request.user)\n data = {\n 'reviews': []\n }\n for review in reviews:\n \n data['reviews'].append({\n 'id': review.id,\n 'title': review.title,\n 'movie': review.movie.title,\n 'viewer_rating': review.viewer_rating,\n 'comment': review.comment,\n 'date_posted': review.date_posted.strftime('%d %B %Y, %-I:%M %p'),\n })\n return JsonResponse(data)\n\nclass ReviewUpdateView(LoginRequiredMixin, TemplateView):\n\n def post(self, request, *args, **kwargs):\n\n review = Review.objects.filter(author=request.user, movie=request.POST['movie_id']).first()\n review.title = request.POST['title']\n review.viewer_rating = request.POST['user_viewer_rating'] if 'user_viewer_rating' in request.POST else 0\n review.comment = request.POST['comment']\n review.date_posted = timezone.now()\n review.save()\n return redirect('movie_detail', str(review.movie.id))\n\nclass ReviewDeleteView(LoginRequiredMixin, TemplateView):\n\n def post(self, request, *args, **kwargs):\n\n review = Review.objects.filter(author=request.user, movie=request.POST['movie_id']).first()\n review.delete()\n\n return redirect('movie_detail', str(review.movie.id))\n","repo_name":"andydandy21/movie_review_app","sub_path":"movies/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"11536752541","text":"def main():\n l1=float(input(\"Digite o primeiro comprimento: \"))\n l2=float(input(\"Digite o segundo comprimento: \"))\n l3=float(input(\"Digite o terceiro comprimento: \"))\n calculo=determinar_triangulo(l1,l2,l3)\n if(calculo):\n print(\"Pode formar um triangulo\")\n else:\n print(\"Não pode formar um triangulo\")\n\ndef determinar_triangulo(l1,l2,l3):\n if (l1+l2)>l3:\n return False\n if(l2+l3)>l1:\n return False\n if(l1+l3)>l2:\n return False\n return True\n\nmain()","repo_name":"Gzanella1/BCC-Bacharelado-Ciencia-da-computacao","sub_path":"Algoritimos/ALG-Lista-5/GZM-ALM-05-EX-07.py","file_name":"GZM-ALM-05-EX-07.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"61"}
+{"seq_id":"2832431774","text":"import random\nimport math\nimport time\nimport threading\n\nteam_name = input(\"Please enter your team name: \")\nfish_repo_rate = 100\nfish_in_lake = 0\n\n\ndef addFish():\n global fish_in_lake\n threading.Timer(10.0, addFish).start() # called every minute\n fish_in_lake += fish_repo_rate\n\naddFish()\n\n\nclass fishBanks:\n def __init__(self, teamName):\n self.teamName = teamName\n self.balance = 500\n self.shipLevel = 1\n self.boost_ship_lv = 1\n self.waitTime = 8\n self.pricePerFish = 6.25\n self.pricePerShip = 18.75\n self.revenue = 100 - (self.pricePerFish + self.pricePerShip)\n self.shipUpgradeCost = 50\n self.maxShipsSent = 5\n self.fishCaptureAmount = 75\n self.fish_repo_rate = fish_repo_rate\n self.fleet_num = 1\n self.netWorth = 0\n\n def send_ships(self):\n global fish_in_lake\n fish_in_lake -= self.fishCaptureAmount\n\n if fish_in_lake <= 0:\n print(\"All fish have been captured, please wait for more.\")\n return\n\n if self.balance < 0:\n print(\"Note: You are now in debt by \" + \"$\", str(self.balance))\n\n if self.maxShipsSent > self.fleet_num:\n self.revenue *= self.fleet_num\n\n elif self.maxShipsSent < self.fleet_num:\n self.revenue *= self.maxShipsSent\n\n print(\"You have $\", str(self.balance), \"in your account\")\n print(\"sending max amount of level\", self.shipLevel, \"ships(s)...\") # sends ships\n time.sleep(self.waitTime) # wait time depending on the level of ship\n self.balance += self.revenue # paycheck\n print(\"$\", str(self.balance), \"In your account. You made \" + str(self.revenue) + \"\\n\")\n\n tip_chance = random.randint(1, 2) # helpful tips\n if tip_chance == 2 and self.shipLevel == 1:\n print(\"Tired of waiting? upgrade your ships buy typing 'boost tech'\")\n\n def buy_ships(self):\n quantity = int(input(\"Enter how many level \" + str(self.shipLevel) + \" ship(s) to buy: \"))\n print(\"The total cost for your \" + str(quantity) + \" level\" + str(self.shipLevel) + \" ship(s) is \" +\n str(self.shipUpgradeCost * quantity))\n\n confirm = input(\"Are you sure you want to continue? (y/n): \")\n if confirm == \"y\".lower():\n self.balance -= self.shipUpgradeCost * quantity\n self.fleet_num += quantity\n print(\"Sucessfully purchased: \" + str(quantity) + \" level\" + str(self.shipLevel) + \" ship(s)\")\n else:\n return\n\n def sell_ships(self):\n quantity = int(input(\"Enter how many ships to sell: \"))\n returned_cash = quantity * math.floor(self.shipUpgradeCost / 2) - self.balance\n print(\"+\", str(returned_cash) + \" added to your account\")\n print(\"Your bank balance is $\" + str(self.balance + returned_cash))\n\n def boost_tech(self):\n self.shipLevel += 1\n if self.shipLevel == 1:\n self.waitTime = 8\n self.pricePerFish = 6.25\n self.pricePerShip = 18.75\n self.revenue = 100 - (self.pricePerFish + self.pricePerShip)\n self.shipUpgradeCost = 50\n self.maxShipsSent = 5\n self.fishCaptureAmount = 75\n self.fish_repo_rate = 500\n self.netWorth = self.balance + (self.pricePerShip * self.fleet_num)\n\n if self.shipLevel == 2:\n self.waitTime = 5\n self.pricePerFish = 12.5\n self.pricePerShip = 37.5\n self.revenue = 200 - (self.pricePerFish + self.pricePerShip)\n self.shipUpgradeCost = 325\n self.maxShipsSent = 15\n self.fishCaptureAmount = 100\n self.fish_repo_rate = 600\n self.netWorth = self.balance + (self.pricePerShip * self.fleet_num)\n\n if self.shipLevel == 3:\n self.waitTime = 4\n self.pricePerFish = 25\n self.pricePerShip = 150\n self.revenue = 300 - (self.pricePerFish + self.pricePerShip)\n self.shipUpgradeCost = 550\n self.maxShipsSent = 25\n self.fishCaptureAmount = 150\n self.fish_repo_rate = 700\n self.netWorth = self.balance + (self.pricePerShip * self.fleet_num)\n\n if self.shipLevel == 4:\n self.waitTime = 3\n self.pricePerFish = 31.25\n self.pricePerShip = 93.75\n self.revenue = 400 - (self.pricePerFish + self.pricePerShip)\n self.shipUpgradeCost = 775\n self.maxShipsSent = 35\n self.fishCaptureAmount = 200\n self.fish_repo_rate = 800\n self.netWorth = self.balance + (self.pricePerShip * self.fleet_num)\n\n if self.shipLevel == 5:\n self.waitTime = 2\n self.pricePerFish = 37.5\n self.pricePerShip = 112.5\n self.revenue = 500 - (self.pricePerFish + self.pricePerShip)\n self.shipUpgradeCost = 1000\n self.maxShipsSent = 45\n self.fishCaptureAmount = 250\n self.fish_repo_rate = 1000\n self.netWorth = self.balance + (self.pricePerShip * self.fleet_num)\n\n if self.balance - self.pricePerShip < 0:\n print(\"Unable to proceed with your request. you need \")\n self.shipLevel -= 1\n return\n\n else:\n\n print(\"Ships boosted to level \" + str(self.shipLevel), \"$\" + str(self.shipUpgradeCost) +\n \" deducted from your account, your balance is $\", str(self.balance - self.shipUpgradeCost))\n self.balance -= self.shipUpgradeCost\n\n print(\"Fish reproduction is now at \" + str(self.fish_repo_rate + 100), \"fish every 10s.\")\n\n\nt1 = fishBanks(team_name)\n\nwhile True:\n print()\n usr_in = input(\"- \")\n if usr_in == \"send ships\".lower():\n t1.send_ships()\n\n if usr_in == \"buy ships\".lower():\n t1.buy_ships()\n\n if usr_in == \"sell ships\".lower():\n t1.sell_ships()\n\n if usr_in == \"boost tech\".lower():\n t1.boost_tech()\n\n if usr_in == \"balance\".lower():\n print(t1.balance)\n\n if usr_in == \"ship num\".lower():\n print(t1.fleet_num)\n\n if usr_in == \"\".lower():\n print(\"\\n\" * 100)\n\n if usr_in == \"fish num\".lower():\n print(fish_in_lake)\n\n if usr_in == \"frr\".lower():\n print(t1.fish_repo_rate)\n\n if usr_in == \"net worth\".lower():\n print(t1.netWorth)\n","repo_name":"Jacob406/Fishbanks-simulation","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"38064962262","text":"import os\nimport flwr\nimport numpy as np\nfrom veremi.config import Config\nfrom flwr.server.strategy.fedavg import FedAvg\nfrom flwr.server.client_proxy import ClientProxy\nfrom typing import List, Tuple, Union, Optional, Dict, Callable\n\nfrom flwr.common import FitRes, Scalar, Parameters, MetricsAggregationFn, NDArrays\n\n\nclass VeremiFedAvg(FedAvg):\n\n # pylint: disable=too-many-arguments,too-many-instance-attributes\n def __init__(\n self,\n *,\n fraction_fit: float = 1.0,\n fraction_evaluate: float = 1.0,\n min_fit_clients: int = 2,\n min_evaluate_clients: int = 2,\n min_available_clients: int = 2, evaluate_fn: Optional[\n Callable[\n [int, NDArrays, Dict[str, Scalar]],\n Optional[Tuple[float, Dict[str, Scalar]]],\n ]\n ] = None,\n on_fit_config_fn: Optional[Callable[[int], Dict[str, Scalar]]] = None,\n on_evaluate_config_fn: Optional[Callable[[int], Dict[str, Scalar]]] = None,\n accept_failures: bool = True, initial_parameters: Optional[Parameters] = None,\n fit_metrics_aggregation_fn: Optional[MetricsAggregationFn] = None,\n evaluate_metrics_aggregation_fn: Optional[MetricsAggregationFn] = None,\n output_path: str = \"\"\n ) -> None:\n\n \"\"\"VeReMi Federated Averaging Strategy.\n\n Parameters\n ----------\n fraction_fit : float, optional\n Fraction of clients used during training. Defaults to 0.1.\n fraction_evaluate : float, optional\n Fraction of clients used during validation. Defaults to 0.1.\n min_fit_clients : int, optional\n Minimum number of clients used during training. Defaults to 2.\n min_evaluate_clients : int, optional\n Minimum number of clients used during validation. Defaults to 2.\n min_available_clients : int, optional\n Minimum number of total clients in the system. Defaults to 2.\n evaluate_fn : Optional[\n Callable[\n [int, NDArrays, Dict[str, Scalar]],\n Optional[Tuple[float, Dict[str, Scalar]]]\n ]\n ]\n Optional function used for validation. Defaults to None.\n on_fit_config_fn : Callable[[int], Dict[str, Scalar]], optional\n Function used to configure training. Defaults to None.\n on_evaluate_config_fn : Callable[[int], Dict[str, Scalar]], optional\n Function used to configure validation. Defaults to None.\n accept_failures : bool, optional\n Whether or not accept rounds containing failures. Defaults to True.\n initial_parameters : Parameters, optional\n Initial global model parameters.\n fit_metrics_aggregation_fn: Optional[MetricsAggregationFn]\n Metrics aggregation function, optional.\n evaluate_metrics_aggregation_fn: Optional[MetricsAggregationFn]\n Metrics aggregation function, optional.\n \"\"\"\n\n super().__init__(fraction_fit=fraction_fit, fraction_evaluate=fraction_evaluate,\n min_fit_clients=min_fit_clients, min_evaluate_clients=min_evaluate_clients,\n min_available_clients=min_available_clients, evaluate_fn=evaluate_fn,\n on_fit_config_fn=on_fit_config_fn, on_evaluate_config_fn=on_evaluate_config_fn,\n accept_failures=accept_failures, initial_parameters=initial_parameters,\n fit_metrics_aggregation_fn=fit_metrics_aggregation_fn,\n evaluate_metrics_aggregation_fn=evaluate_metrics_aggregation_fn)\n\n self.output_path = output_path\n self.load_data()\n self.params = None\n\n def load_data(self):\n if self.initial_parameters is None:\n file = self.output_path + Config.weights_file\n if os.path.exists(file):\n npzfile = np.load(file)\n params = [npzfile[x] for x in npzfile]\n params = flwr.common.ndarrays_to_parameters(params)\n self.initial_parameters = params\n\n def aggregate_fit(\n self,\n server_round: int,\n results: List[Tuple[flwr.server.client_proxy.ClientProxy, flwr.common.FitRes]],\n failures: List[Union[Tuple[ClientProxy, FitRes], BaseException]],\n ) -> Tuple[Optional[Parameters], Dict[str, Scalar]]:\n aggregated_parameters, aggregated_metrics = super().aggregate_fit(server_round, results, failures)\n\n if aggregated_parameters is not None:\n # Convert `Parameters` to `List[np.ndarray]`\n aggregated_ndarrays: List[np.ndarray] = flwr.common.parameters_to_ndarrays(aggregated_parameters)\n self.params = aggregated_ndarrays\n\n return aggregated_parameters, aggregated_metrics\n\n def save_params(self):\n np.savez(f\"{self.output_path}{Config.weights_file}\", *self.params)\n","repo_name":"c2dc/fl-ieee-vtc2023","sub_path":"veremi_fedavg.py","file_name":"veremi_fedavg.py","file_ext":"py","file_size_in_byte":5000,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"6397117557","text":"#!/usr/bin/env python\n\"\"\"Setup module for infinitewarp_utils.\"\"\"\nfrom datetime import datetime\n\nfrom setuptools import find_packages, setup\n\nbuild_time = datetime.utcnow().strftime('%Y%m%d%H%M%S')\n\nsetup(\n name='infinitewarp_utils',\n version='1.0.{}'.format(build_time),\n description='infinitewarp_utils is a collection of Python helper modules '\n 'for infinitewarp.',\n url='https://github.com/infinitewarp/infinitewarp-python-utils',\n author='Brad Smith',\n author_email='bradster@infinitewarp.com',\n license='MIT',\n packages=find_packages(exclude=['docs', 'tests', 'tests.*']),\n install_requires=[],\n dependency_links=[],\n zip_safe=True,\n)\n","repo_name":"infinitewarp/infinitewarp-python-utils","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"7151979975","text":"\"\"\"pm42 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import include, path\nfrom .views import Init, Dev, ApiLogin, ApiRank, ApiSlot, ApiSlotMe\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', Init.as_view()),\n #path('', Dev.as_view()),\n path('api/login/', ApiLogin.as_view()),\n path('api/rank/', ApiRank.as_view()),\n path('api/slot/me/', ApiSlotMe.as_view()),\n path('api/slot/', ApiSlot.as_view()),\n #path('api/slot/all/', ApiSlot.as_view()),\n #path('api/me/', ApiMe.as_view()),\n]\n","repo_name":"bok000111/42hackathon","sub_path":"pm42/pm42/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"29837809767","text":"import re\n\nfrom fiftystates.scrape import NoDataForPeriod\nfrom fiftystates.scrape.legislators import LegislatorScraper, Legislator\n\nimport lxml.html\n\n\nclass FLLegislatorScraper(LegislatorScraper):\n state = 'fl'\n\n def scrape(self, chamber, term):\n if term != '2010':\n raise NoDataForPeriod(term)\n\n if chamber == 'upper':\n self.scrape_senators(term)\n else:\n self.scrape_reps(term)\n\n def scrape_senators(self, term):\n url = (\"http://www.flsenate.gov/Legislators/\"\n \"index.cfm?Mode=Member%20Pages&Submenu=1&Tab=legislators\")\n\n with self.urlopen(url) as page:\n page = lxml.html.fromstring(page)\n\n for link in page.xpath(\"//a[contains(@href, '/legislators')]\"):\n name = re.sub(r\"\\s+\", \" \", link.text).strip()\n\n # Special case - name_tools gets confused\n # by 'JD', thinking it is a suffix instead of a first name\n if name == 'Alexander, JD':\n name = 'JD Alexander'\n elif name == 'Vacant':\n name = 'Vacant Seat'\n\n district = link.xpath('string(../../td[2])').strip()\n party = link.xpath('string(../../td[3])').strip()\n\n leg = Legislator(term, 'upper', district, name,\n party=party)\n leg.add_source(url)\n self.save_legislator(leg)\n\n def scrape_reps(self, term):\n url = (\"http://www.flhouse.gov/Sections/Representatives/\"\n \"representatives.aspx\")\n\n with self.urlopen(url) as page:\n page = lxml.html.fromstring(page.decode('utf8'))\n\n for link in page.xpath(\"//a[contains(@href, 'MemberId')]\"):\n name = re.sub(r\"\\s+\", \" \", link.text).strip()\n\n party = link.xpath('string(../../td[3])').strip()\n if party == 'D':\n party = 'Democrat'\n elif party == 'R':\n party = 'Republican'\n\n district = link.xpath('string(../../td[4])').strip()\n\n leg = Legislator(term, 'lower', district, name,\n party=party)\n leg.add_source(url)\n self.save_legislator(leg)\n","repo_name":"runderwood/fiftystates","sub_path":"fiftystates/scrape/fl/legislators.py","file_name":"legislators.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"61"}
+{"seq_id":"71187728514","text":"import queue\r\n\r\ndef Path_search(mp, init_pos, now_pos, empty):\r\n '''输出路径\r\n \r\n '''\r\n father = ''\r\n child = now_pos\r\n path = []\r\n i = 0\r\n while(child != init_pos):\r\n father = mp.get(child)\r\n father_empty = get_empty_pos(father, empty)\r\n child_empty = get_empty_pos(child, empty)\r\n count = father_empty - child_empty\r\n if count == -3:\r\n path.append('s')\r\n elif count == -1:\r\n path.append('d')\r\n elif count == 1:\r\n path.append('a')\r\n elif count == 3:\r\n path.append('w')\r\n child = father\r\n return list(reversed(path))\r\n\r\n\r\ndef Solvable(now_pos, empty):\r\n ''' 判断有无解\r\n 通过计算逆序数,偶序列有解,奇序列无解\r\n '''\r\n lenght = 9\r\n count = 0\r\n for i in range(lenght-1):\r\n if now_pos[i] == empty:\r\n continue\r\n for j in range(i+1, lenght):\r\n if now_pos[j] == empty:\r\n continue\r\n if now_pos[i] > now_pos[j]:\r\n count += 1\r\n if count % 2 == 0:\r\n return True\r\n else:\r\n return False\r\n\r\n\r\ndef get_empty_pos(now_pos, empty):\r\n '''遍历找出空白位置'''\r\n for i in range(len(now_pos)):\r\n if now_pos[i] == empty:\r\n return i\r\n \r\ndef bfs(init_pos, empty):\r\n ''' 核心算法\r\n 通过广搜找出最优解\r\n '''\r\n dir = [2, 3, 2, 3, 4, 3, 2, 3, 2]\r\n dis = [[1, 3], [0, 2, 4], [1, 5], [0, 4, 6], [\r\n 1, 3, 5, 7], [2, 4, 8], [3, 7], [4, 6, 8], [5, 7]]\r\n mp = {}\r\n q1 = queue.Queue() # 储存序列信息\r\n q2 = queue.Queue() # 储存步数\r\n q1.put(init_pos)\r\n q2.put(0)\r\n\r\n while(not q1.empty()):\r\n father_pos = q1.get()\r\n step = q2.get()\r\n pos = get_empty_pos(father_pos, empty)\r\n if father_pos == '123456789':\r\n return Path_search(mp,init_pos, father_pos,empty)\r\n for i in range(dir[pos]):\r\n child_pos = list(father_pos)\r\n child_pos[pos], child_pos[dis[pos][i]] = child_pos[dis[pos][i]], child_pos[pos] # 移动空白\r\n child_pos = ''.join(child_pos)\r\n if child_pos not in mp: # 重复标记\r\n mp[child_pos] = father_pos \r\n elif child_pos in mp:\r\n continue\r\n q1.put(child_pos)\r\n q2.put(step+1)","repo_name":"Zhlod/Huarong_Road","sub_path":"Game/AI_Move.py","file_name":"AI_Move.py","file_ext":"py","file_size_in_byte":2390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"15332783699","text":"\"\"\"Tests for the switch entity.\"\"\"\r\nfrom homeassistant.components.sensor import SensorDeviceClass\r\nfrom homeassistant.components.switch import SwitchDeviceClass\r\nfrom homeassistant.const import (\r\n UnitOfElectricCurrent,\r\n UnitOfElectricPotential,\r\n UnitOfEnergy,\r\n UnitOfPower,\r\n UnitOfTime,\r\n)\r\n\r\nfrom ..const import GRIDCONNECT_2SOCKET_PAYLOAD\r\nfrom ..mixins.lock import BasicLockTests\r\nfrom ..mixins.number import MultiNumberTests\r\nfrom ..mixins.select import BasicSelectTests\r\nfrom ..mixins.sensor import MultiSensorTests\r\nfrom ..mixins.switch import MultiSwitchTests\r\nfrom .base_device_tests import TuyaDeviceTestCase\r\n\r\nSWITCH1_DPS = \"1\"\r\nSWITCH2_DPS = \"2\"\r\nCOUNTDOWN1_DPS = \"9\"\r\nCOUNTDOWN2_DPS = \"10\"\r\nENERGY_DPS = \"17\"\r\nCURRENT_DPS = \"18\"\r\nPOWER_DPS = \"19\"\r\nVOLTAGE_DPS = \"20\"\r\nTEST_DPS = \"21\"\r\nCALIBV_DPS = \"22\"\r\nCALIBA_DPS = \"23\"\r\nCALIBW_DPS = \"24\"\r\nCALIBE_DPS = \"25\"\r\nINITIAL_DPS = \"38\"\r\nLOCK_DPS = \"40\"\r\nMASTER_DPS = \"101\"\r\n\r\n\r\nclass TestGridConnectDoubleSwitch(\r\n BasicLockTests,\r\n BasicSelectTests,\r\n MultiNumberTests,\r\n MultiSensorTests,\r\n MultiSwitchTests,\r\n TuyaDeviceTestCase,\r\n):\r\n __test__ = True\r\n\r\n def setUp(self):\r\n self.setUpForConfig(\r\n \"grid_connect_usb_double_power_point.yaml\",\r\n GRIDCONNECT_2SOCKET_PAYLOAD,\r\n )\r\n self.setUpBasicLock(LOCK_DPS, self.entities.get(\"lock_child_lock\"))\r\n self.setUpBasicSelect(\r\n INITIAL_DPS,\r\n self.entities.get(\"select_initial_state\"),\r\n {\r\n \"on\": \"On\",\r\n \"off\": \"Off\",\r\n \"memory\": \"Last State\",\r\n },\r\n )\r\n # Master switch must go last, otherwise its tests interfere with\r\n # the tests for the other switches since it overrides them.\r\n # Tests for the specific override behaviour are below.\r\n self.setUpMultiSwitch(\r\n [\r\n {\r\n \"name\": \"switch_outlet_1\",\r\n \"dps\": SWITCH1_DPS,\r\n \"device_class\": SwitchDeviceClass.OUTLET,\r\n },\r\n {\r\n \"name\": \"switch_outlet_2\",\r\n \"dps\": SWITCH2_DPS,\r\n \"device_class\": SwitchDeviceClass.OUTLET,\r\n },\r\n {\r\n \"name\": \"switch_master\",\r\n \"dps\": MASTER_DPS,\r\n \"device_class\": SwitchDeviceClass.OUTLET,\r\n },\r\n ]\r\n )\r\n self.setUpMultiSensors(\r\n [\r\n {\r\n \"name\": \"sensor_energy\",\r\n \"dps\": ENERGY_DPS,\r\n \"unit\": UnitOfEnergy.WATT_HOUR,\r\n },\r\n {\r\n \"name\": \"sensor_current\",\r\n \"dps\": CURRENT_DPS,\r\n \"device_class\": SensorDeviceClass.CURRENT,\r\n \"unit\": UnitOfElectricCurrent.MILLIAMPERE,\r\n \"state_class\": \"measurement\",\r\n },\r\n {\r\n \"name\": \"sensor_power\",\r\n \"dps\": POWER_DPS,\r\n \"device_class\": SensorDeviceClass.POWER,\r\n \"unit\": UnitOfPower.WATT,\r\n \"state_class\": \"measurement\",\r\n \"testdata\": (1234, 123.4),\r\n },\r\n {\r\n \"name\": \"sensor_voltage\",\r\n \"dps\": VOLTAGE_DPS,\r\n \"device_class\": SensorDeviceClass.VOLTAGE,\r\n \"unit\": UnitOfElectricPotential.VOLT,\r\n \"state_class\": \"measurement\",\r\n \"testdata\": (2345, 234.5),\r\n },\r\n ]\r\n )\r\n self.setUpMultiNumber(\r\n [\r\n {\r\n \"name\": \"number_timer_1\",\r\n \"dps\": COUNTDOWN1_DPS,\r\n \"max\": 86400,\r\n \"unit\": UnitOfTime.SECONDS,\r\n },\r\n {\r\n \"name\": \"number_timer_2\",\r\n \"dps\": COUNTDOWN2_DPS,\r\n \"max\": 86400,\r\n \"unit\": UnitOfTime.SECONDS,\r\n },\r\n ]\r\n )\r\n self.mark_secondary(\r\n [\r\n \"lock_child_lock\",\r\n \"number_timer_1\",\r\n \"number_timer_2\",\r\n \"select_initial_state\",\r\n \"switch_master\",\r\n \"sensor_energy\",\r\n \"sensor_current\",\r\n \"sensor_power\",\r\n \"sensor_voltage\",\r\n ],\r\n )\r\n\r\n # Since we have attributes, override the default test which expects none.\r\n def test_multi_switch_state_attributes(self):\r\n self.dps[TEST_DPS] = 21\r\n self.assertDictEqual(\r\n self.multiSwitch[\"switch_master\"].extra_state_attributes,\r\n {\r\n \"test_bit\": 21,\r\n },\r\n )\r\n\r\n def test_multi_sensor_extra_state_attributes(self):\r\n self.dps[CALIBA_DPS] = 1\r\n self.dps[CALIBE_DPS] = 2\r\n self.dps[CALIBV_DPS] = 3\r\n self.dps[CALIBW_DPS] = 4\r\n\r\n self.assertDictEqual(\r\n self.multiSensor[\"sensor_current\"].extra_state_attributes,\r\n {\"calibration\": 1},\r\n )\r\n self.assertDictEqual(\r\n self.multiSensor[\"sensor_energy\"].extra_state_attributes,\r\n {\"calibration\": 2},\r\n )\r\n self.assertDictEqual(\r\n self.multiSensor[\"sensor_voltage\"].extra_state_attributes,\r\n {\"calibration\": 3},\r\n )\r\n self.assertDictEqual(\r\n self.multiSensor[\"sensor_power\"].extra_state_attributes,\r\n {\"calibration\": 4},\r\n )\r\n","repo_name":"make-all/tuya-local","sub_path":"tests/devices/test_grid_connect_double_power_point.py","file_name":"test_grid_connect_double_power_point.py","file_ext":"py","file_size_in_byte":5756,"program_lang":"python","lang":"en","doc_type":"code","stars":613,"dataset":"github-code","pt":"61"}
+{"seq_id":"21404912629","text":"import datetime\r\nimport math\r\n\r\nimport requests\r\nfrom google.cloud import ndb\r\n\r\nfrom backend import error\r\n\r\n\r\nclass NotFound(error.Error):\r\n pass\r\n\r\n\r\nclass Movie(ndb.Model):\r\n created = ndb.DateTimeProperty(indexed=False)\r\n title = ndb.StringProperty(required=True, indexed=True)\r\n year = ndb.StringProperty(indexed=True)\r\n imdbID = ndb.StringProperty(indexed=True)\r\n poster = ndb.StringProperty()\r\n normalized_title = ndb.ComputedProperty(\r\n lambda self: self.title and self.title.lower(), indexed=True\r\n )\r\n\r\n @classmethod\r\n def _query(cls, *filters, **kwargs):\r\n count = super()._query().count()\r\n if abs(count - 100) > 10:\r\n for page in range(1, math.ceil((100 - count) / 10) + 1):\r\n search_word = \"holiday\"\r\n movies = requests.get(\r\n f\"{cls._api_host}?s={search_word}&type=movie\"\r\n f\"&apikey={cls._apikey}&page={page}\"\r\n ).json()\r\n for item in movies.get(\"Search\", []):\r\n cls.create(\r\n title=item.get(\"Title\"),\r\n year=item.get(\"Year\"),\r\n imdbID=item.get(\"imdbID\"),\r\n poster=item.get(\"Poster\"),\r\n )\r\n count += 1\r\n if count >= 100:\r\n break\r\n # count = super()._query().count()\r\n # print(f\"{count} movies in database\")\r\n return super()._query(*filters, **kwargs)\r\n\r\n _apikey = \"3a396d25\"\r\n _api_host = \"https://www.omdbapi.com/\"\r\n query = _query\r\n\r\n @classmethod\r\n def get_by_title(cls, title):\r\n entities = cls.query(cls.title == title).fetch(1)\r\n return entities[0] if entities else None\r\n\r\n @classmethod\r\n def list(cls, offset=0, limit=10):\r\n return cls.query().order(Movie.title).fetch(offset=offset, limit=limit)\r\n\r\n @classmethod\r\n def create(cls, title: str, year=None, imdbID=None, poster=None):\r\n entity = cls(\r\n created=datetime.datetime.now(),\r\n title=title,\r\n year=year,\r\n imdbID=imdbID,\r\n poster=poster,\r\n )\r\n\r\n if all(x is None for x in (year, imdbID, poster)):\r\n resp = requests.get(\r\n f\"{cls._api_host}?t={title}&apikey={cls._apikey}\"\r\n ).json()\r\n entity.year = resp.get(\"Year\")\r\n entity.imdbID = resp.get(\"imdbID\")\r\n entity.poster = resp.get(\"Poster\")\r\n\r\n entity.put()\r\n return entity\r\n\r\n @classmethod\r\n def delete(cls, imdbID):\r\n entities = cls.query(cls.imdbID == imdbID).fetch(1)\r\n if entities:\r\n entities[0].key.delete()\r\n return True\r\n return False\r\n\r\n @property\r\n def id(self):\r\n return self.key.urlsafe().decode(\"utf-8\")\r\n\r\n def __hash__(self):\r\n return hash((self.__class__.__name__, self.id))\r\n","repo_name":"skippdot/abonea-python-test","sub_path":"backend/movie.py","file_name":"movie.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"76007474","text":"\ndef anagramMappings(A:List[int], B:List[int]) -> List[int]:\n\n\tmapdict = {}\n\n\tfor i in range(0,len(B)):\n\t\tmapdict[B[i]] = i\n\n\tprint(mapdict)\n\n\tansArray = []\n\tfor i in range(0,len(A)):\n\t\tansArray.append(mapdict[A[i]])\n\n\treturn ansArray \n\n\ndef anagramMappings_my(A:List[int], B:List[int]) -> List[int]:\n\n\tansArray = []\n\tfor i in xrange(0,len(A)):\n\t\tfor j in xrange(0,len(B)):\n\t\t\tif A[i] == B[j]:\n\t\t\t\tansArray[i] = j\n\n\treturn ansArray","repo_name":"PanJianTing/LeetCode","sub_path":"760_FindAnagramMappings.py","file_name":"760_FindAnagramMappings.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"16599749428","text":"#Smoothstaick Python Basics Day 2a\r\n#Coding Exercise 3\r\n#Patrick Hedquist\r\n#####################################\r\n\r\n#Question 1\r\n#write a string that returns the letter 'r' from 'Hello world'\r\n#For example, 'Hello World'[0] returns 'H'. It should be one line of code\r\n#dont assign a variable to the string\r\n\r\nprint('Hello world'[8])\r\n\r\n#Question 2\r\n#String slicing to grab the word 'ink' from the word 'thinker'\r\n#S='hello' what is the output of h[1]? Answer: 'e'\r\n\r\nprint('thinker'[2:5])\r\nprint('\\n')\r\n\r\n#Question 3\r\n#S='Sammy' what is the output of S[2:]? Answer: mmy\r\n\r\nprint('Sammy'[2:])\r\nprint('\\n')\r\n\r\n#Question 4\r\n#With a single set function can you turn the word 'Mississippi' to distinct chatacter word?\r\n\r\nprint(set('Mississippi'))\r\nprint('\\n')\r\n\r\n#Question 5\r\n#The word or whole phase which has the same sequence of letters in both directions is called a palindrome\r\n#Here are a few examples\r\n# Stats\r\n# Amore, rose\r\n# No 'x' in Nixon\r\n# Was it a cat I saw?\r\n#your goal is to determine whether the phrase represents a palindrome or not\r\n\r\n\r\ninput1 = input(\"Enter word to test: \") #prints \"Enter word to test: \" and user can input a word\r\nlist = [input1] #creates a list using the word user inputted\r\ncont = input(\"add another word?(y/n)\") #ask user if they want to add new word\r\n\r\nwhile cont != 'n': #checks if answer is NOT n\r\n if cont == 'y': #checks if answer was y\r\n input2 = input(\"Enter word to test: \") #input word prompt\r\n list = list + [input2] #update list\r\n cont = input(\"add another word?(y/n)\") #ask user if they want new word\r\n\r\nfor i in list: #prints items in list on new lines\r\n print(i)\r\n\r\nans = []\r\n\r\n\r\ndef palindrome(pal): #algorithm based off code from Sachin Bisht on geeksforgeeks\r\n j = 0\r\n k = len(pal)-1\r\n pal = pal.lower()\r\n\r\n while (j <= k): #while loop to iterate through list and test palindromes\r\n if(not(pal[j] >= 'a' and pal[j] <= 'z')):\r\n j += 1\r\n elif (not(pal[k] >= 'a' and pal[k] <= 'z')):\r\n k -= 1\r\n elif (pal[j] == pal[k]):\r\n j += 1\r\n k -= 1\r\n else:\r\n return False\r\n return True\r\n\r\nfor i in list:\r\n if(palindrome(i)):\r\n ans = ans + ['Y']\r\n else:\r\n ans = ans + ['N']\r\n\r\nprint(len(list))\r\nprint(ans) #print ans list\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","repo_name":"prhedquist/SmoothStackAssignments","sub_path":"day2a.py","file_name":"day2a.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"61"}
+{"seq_id":"9289268237","text":"import argparse\nimport doctest\nimport os\nimport sys\nfrom enum import Enum\nfrom typing import Dict, Iterable, List, TextIO\n\n\nclass Target(Enum):\n NAME = 0\n THRIFT = 1\n CPP2 = 2\n\n\nTHRIFT_HEADER = f\"\"\"# This file was generated by `thrift/test/testset/generator.py`\n# {'@'}generated\n\nnamespace cpp2 apache.thrift.test.testset\n\"\"\"\n\nCPP2_HEADER = f\"\"\"// This file was generated by `thrift/test/testset/generator.py`\n// {'@'}generated\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\nnamespace apache::thrift::test::testset {{\n\nenum class FieldModifier {{\n Optional = 1,\n Required,\n Reference,\n}};\n\nnamespace detail {{\n\ntemplate